[英]How to get the sum of a list of numbers excluding integers that are divisible by 3 and 7 with recursion?
I am trying to find the summation of integer in list with elements that are divisible by 3 or 7 excluded我试图在列表中找到 integer 的总和,其中排除了可被 3 或 7 整除的元素
def SumSkip37(numList,sum = 0):
if numList:
i = numList.pop()
if i % 3 == 0 or i % 7 == 0:
return sum
else:
sum += i
return SumSkip37(numList, sum=sum)
numList = [1, 3, 5, 7, 9]
print(f'The result is {SumSkip37(numList)}.')
Pls help me figure out请帮我弄清楚
You can update your code to:您可以将代码更新为:
def SumSkip37(numList, my_sum = 0): # avoid using sum
if numList:
i = numList.pop()
if i % 3 == 0 or i % 7 == 0:
return SumSkip37(numList, my_sum=my_sum) # pass the unchanged sum
else:
return SumSkip37(numList, my_sum=my_sum+i) # pass the sum + i
else:
return my_sum
NB.注意。 I tried to stay as close as possible to the original, but you can simplify greatly!
我试图尽可能地接近原作,但你可以大大简化!
To avoid mutating the input:为了避免改变输入:
def SumSkip37(numList, my_sum = 0):
if numList:
if numList[0] % 3 != 0 and numList[0] % 7 != 0:
my_sum += numList[0]
return SumSkip37(numList[1:], my_sum=my_sum)
return my_sum
print(f'The result is {SumSkip37(numList)}.')
Better approach than the alternative above suggested by @Stef to run in linear time:比@Stef 建议的以线性时间运行的上述替代方法更好的方法:
def SumSkip37(numList, my_sum=0, idx=0):
if idx >= len(numList):
return my_sum
elif numList[idx] % 3 != 0 and numList[idx] % 7 != 0:
return SumSkip37(numList, my_sum + numList[idx], idx + 1)
return SumSkip37(numList, my_sum, idx + 1)
Also, recursion is overkill here, better use a short generator expression:此外,递归在这里是多余的,最好使用简短的生成器表达式:
sum(i for i in numList if i%7!=0 and i%3!=0)
On relatively clean way:在相对干净的方式上:
def SumSkip37(numList):
if not numList:
return 0
head, *tail = numList
return head * bool(head % 3 and head % 7) + SumSkip37(tail)
You are on the right track.你在正确的轨道上。 You just weren't iterating through the whole list:
您只是没有遍历整个列表:
def SumSkip37(numList, total=0):
if numList:
i = numList.pop()
if i % 3 != 0 and i % 7 != 0:
total += i
return SumSkip37(numList, total=total)
return total
I flipped the comparison to remove the unnecessary else
branch.我翻转了比较以删除不必要的
else
分支。 It doesn't matter if the current number is divisible with 3 or 7 or not, you always want to continue the recursion until the list runs out.当前数字是否可以被 3 或 7 整除并不重要,您总是希望继续递归直到列表用完。
Without Recursive function:没有递归 function:
def SumSkip37(list):
sum = 0
for i in list:
if i % 3 == 0 or i % 7 == 0:
continue
else:
sum += i
return sum
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(SumSkip37(list))
With Recursive Function:使用递归 Function:
def SumSkip37(lst):
if len(lst) == 0:
return 0
else:
if lst[0] % 3 == 0 or lst[0] % 7 == 0:
return SumSkip37(lst[1:])
else:
return lst[0] + SumSkip37(lst[1:])
print(SumSkip37([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.