Python 3.x python返回语句的主要问题
函数,该函数用于查找x或y的倍数为N(包括N)的所有数字之和 我试着把返回语句放在不同的缩进处,但还是没有希望Python 3.x python返回语句的主要问题,python-3.x,Python 3.x,函数,该函数用于查找x或y的倍数为N(包括N)的所有数字之和 我试着把返回语句放在不同的缩进处,但还是没有希望 def multipleSum(N,x,y): z=0 a=0 for i in range(0,N+1): if i%x==0: z=z+i elif i%y==0: a=a+i else: s=z+a return s 测试
def multipleSum(N,x,y):
z=0
a=0
for i in range(0,N+1):
if i%x==0:
z=z+i
elif i%y==0:
a=a+i
else:
s=z+a
return s
测试用例:
def multipleSum(N,x,y):
total=0
for i in range(N+1): # No need to mention 0(zero), as range starts from '0'
if i % x == 0 or i % y == 0: # No need to use if and elif, better to use 'or' instead
total+=i
return total
def multipleSum(N,x,y):
return sum(map(lambda v: v if v%x==0 or v%y==0 else 0, range(N+1)))
>>> multipleSum(10, 2, 3)
42
倍数(10,2,3)==42
预期结果为42,实际结果为15代码:
def multipleSum(N,x,y):
total=0
for i in range(N+1): # No need to mention 0(zero), as range starts from '0'
if i % x == 0 or i % y == 0: # No need to use if and elif, better to use 'or' instead
total+=i
return total
def multipleSum(N,x,y):
return sum(map(lambda v: v if v%x==0 or v%y==0 else 0, range(N+1)))
>>> multipleSum(10, 2, 3)
42
还有一种方法:
def multipleSum(N,x,y):
total=0
for i in range(N+1): # No need to mention 0(zero), as range starts from '0'
if i % x == 0 or i % y == 0: # No need to use if and elif, better to use 'or' instead
total+=i
return total
def multipleSum(N,x,y):
return sum(map(lambda v: v if v%x==0 or v%y==0 else 0, range(N+1)))
>>> multipleSum(10, 2, 3)
42
输出:
def multipleSum(N,x,y):
total=0
for i in range(N+1): # No need to mention 0(zero), as range starts from '0'
if i % x == 0 or i % y == 0: # No need to use if and elif, better to use 'or' instead
total+=i
return total
def multipleSum(N,x,y):
return sum(map(lambda v: v if v%x==0 or v%y==0 else 0, range(N+1)))
>>> multipleSum(10, 2, 3)
42