gpt4 book ai didi

python - 列表2> sum13编码 bat 问题: 'int' object is not iterable

转载 作者:行者123 更新时间:2023-12-03 07:51:47 37 4
gpt4 key购买 nike

我的代码有问题。问题是:
返回数组中数字的总和,对于空数组返回0。除非数字13非常不幸,所以它不计数,紧接在13之后的数字也不计数。
来自:https://codingbat.com/prob/p167025

def sum13(nums):
if not nums:
return 0
for x in nums:
if x == 13:
break
return sum(x)
if 13 not in nums:
return sums(nums)
问题是我无法合并sum(x),并且每次尝试都会给出错误。
有人可以暗示为什么吗?

最佳答案

return放错位置是这里的许多问题之一,但可能是修复逻辑的一个好开始。很难确定一旦解决将产生预期结果的单个问题。相反,存在一个普遍的问题,即实现与任务逻辑无关。
通常,您将问题分解为更简单的积木,如下所示:

def sum13(nums):
# "Return the sum of the numbers in the array"
# - let's iterate the array, increasing the sum
res = 0
previous_is_13 = False # introduced later

# "returning 0 for an empty array."
# for loop will do nothing on empty arrays, as desired
for i in nums:
# "Except the number 13 is very unlucky, so it does not count"
# so, let's guard it with an if:
if i == 13:
# "numbers that come immediately after a 13 also do not count."
# ok, let's set a flag to indicate that and clear it once we're past 13
previous_is_13 = True
continue

if previous_is_13:
previous_is_13 = False # clear the flag and proceed to the next item
continue
res += i
return res
获得基线解决方案后,使其变得更好,例如使用迭代器:
def sum13(nums):
return sum(value for i, value in enumerate(nums)
if value!= 13 and (not i or nums[i-1] != 13))

关于python - 列表2> sum13编码 bat 问题: 'int' object is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64649815/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com