我正在尝试编写一个名为sum_square_differencen 的函数,并返回前n个自然数的平方和与它们的和的平方之间的差值.
我想我知道如何编写一个定义平方和的函数
def sum_of_squares(numbers):
total = 0
for num in numbers:
total += (num ** 2)
return(total)
Run Code Online (Sandbox Code Playgroud)
我试图实现一个sums函数的平方:
def square_sum(numbers):
total = 0
for each in range:
total = total + each
return total**2
Run Code Online (Sandbox Code Playgroud)
我不知道如何结合功能来区分,我不知道我的功能是否正确.
有什么建议吗?我使用的是Python 3.3
谢谢.
我必须编写一个递归函数asterisk_triangle,它接受一个整数,然后返回一个由许多行组成的星号三角形.
例如,这是一个4行星号三角形.
*
**
***
****
Run Code Online (Sandbox Code Playgroud)
我想出了这个功能:
def asterisk_triangle(n):
"""
takes an integer n and then returns an
asterisk triangle consisting of (n) many lines
"""
x = 1
while (x <= n):
print("*" * x)
x = x + 1
return
Run Code Online (Sandbox Code Playgroud)
而且我还必须通过操纵第一个函数来创建一个颠倒的星号三角形.
我想出了这个功能和结果:
def upside_down_asterisk_triangle(n):
"""
takes an integer n and then returns a backwards
asterisk triangle consisting of (n) many lines
"""
x = 0
while (x < n):
print("*" * (n-x))
x = x + 1
return …Run Code Online (Sandbox Code Playgroud) 我需要派生一个函数,它接受一个字符串并返回该字符串是否是回文并且我的函数应该在字符串上返回True如果不考虑空格(所以它应该说'一个人计划运河巴拿马'或'是我看到的'厕所'是'回文),但它不需要考虑大写字母或标点符号的变化(所以它可能会在"一个人,一个计划,一条运河 - 巴拿马!'上回归假,而'它是艾略特的'我看到厕所?').
我试过了
def palindrome(s):
return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
Run Code Online (Sandbox Code Playgroud)
和
def ispalindrome(word):
if len(word) < 2: return True
if word[0] != word[-1]: return False
return ispalindrome(word[1:-1])
Run Code Online (Sandbox Code Playgroud)
但两者都不起作用.有什么建议?我正在使用python 3.3