Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 清单2>;sum13编码bat问题:';int';对象是不可编辑的_Python_Python 3.x_Loops_Error Handling_Break - Fatal编程技术网

Python 清单2>;sum13编码bat问题:';int';对象是不可编辑的

Python 清单2>;sum13编码bat问题:';int';对象是不可编辑的,python,python-3.x,loops,error-handling,break,Python,Python 3.x,Loops,Error Handling,Break,我的代码有问题。问题是: 返回数组中数字的总和,空数组返回0。除此之外,数字13是非常不吉利的,所以它不算数,紧跟在13之后的数字也不算数。 发件人: 问题是我不能合并和(x),每次尝试时它都会给出一个错误。 有人能告诉我原因吗?错位返回是这里的许多问题之一,但可能是修复逻辑的良好开端。很难找出一个问题,一旦解决,将产生预期的结果。相反,存在一个普遍的问题,即实现与任务逻辑无关 通常,您会将问题分解为更简单的砖块,有点像这样: def sum13(nums): # "Retur

我的代码有问题。问题是:

返回数组中数字的总和,空数组返回0。除此之外,数字13是非常不吉利的,所以它不算数,紧跟在13之后的数字也不算数。 发件人:

问题是我不能合并和(x),每次尝试时它都会给出一个错误。
有人能告诉我原因吗?

错位
返回是这里的许多问题之一,但可能是修复逻辑的良好开端。很难找出一个问题,一旦解决,将产生预期的结果。相反,存在一个普遍的问题,即实现与任务逻辑无关

通常,您会将问题分解为更简单的砖块,有点像这样:

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))

您在第一次迭代时
return
,更改它会产生缩进错误?非常感谢
def sum13(nums):
    return sum(value for i, value in enumerate(nums)
               if value!= 13 and (not i or nums[i-1] != 13))