首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >List-2 > sum13编码bat问题:'int‘对象不可迭代

List-2 > sum13编码bat问题:'int‘对象不可迭代
EN

Stack Overflow用户
提问于 2020-11-02 16:52:23
回答 1查看 103关注 0票数 1

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

返回数组中数字的和,返回空数组的0。除了数字13是非常不吉利的,所以它不计数和数字后面的一个13也不算数。来自:https://codingbat.com/prob/p167025

代码语言:javascript
复制
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)

问题是,我不能组合和(X),每次尝试它都会产生一个错误。有人能告诉我为什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-02 18:34:31

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

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

代码语言:javascript
复制
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

一旦有了基线解决方案,就会变得更好(如使用迭代器):

代码语言:javascript
复制
def sum13(nums):
    return sum(value for i, value in enumerate(nums)
               if value!= 13 and (not i or nums[i-1] != 13))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64649815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档