1

我正在为一门课做一些家庭作业,作业在codingbat.com上。问题如下:

返回数组中数字的总和,对于空数组返回 0。除了数字 13 非常不吉利,因此它不算数,紧跟在 13 之后的数字也不算数。

到目前为止,我有这个:

def sum13(nums):  
    sum = 0  
    i = 0  
    while i in range(len(nums)):  
        if i == 13:  
            i += 2  
        else:  
            i += 1  
    return sum

另外,我有这个更好的代码:

def sum13(nums):
   sum = 0
   for i in range(len(nums)):
   if nums[i] != 13:
     sum += nums[i]
   return sum

我知道我应该使用 while 循环,但我就是不明白。

4

2 回答 2

1

看起来你快到了;您只需要在适当的位置实际添加nums[i]to的值。sum还要重新考虑行的缩进return sum

于 2012-06-03T22:03:36.297 回答
0

更常见的是使用for循环而不使用range(). 这种循环(在 Python 中)通常用于循环遍历元素值,而不是遍历索引值。当您需要索引时,使用该enumerate()函数同时获取索引和元素值,如下所示(但在这种情况下您不需要它):

...
for i, e in enumerate(nums):
    do something with index and/or the element
...

该问题与索引值无关。这样,for/while解决方案的不同之处仅在于访问数组的元素。您需要使用索引,while但不需要使用for.

您的方法的问题while还在于您不能简单地跳过值 13 之后的索引,因为下一个元素也可以包含 13。您需要存储前一个元素的值并使用它来决定是否应该添加当前值到sum与否。for在和解决方案中都是一样的while。像这样的东西:

last = 0  # init; whatever value different from 13
sum = 0
the chosen kind of loop:
    e ... # current element from nums
    if e != 13 bool_operator_here last != 13:  # think about what boolean operator is
        add the element to the sum
    remember e as the last element for the next loop
sum contains the result

[稍后编辑]好吧,你放弃了。这是解决问题的代码:

def sumNot13for(nums):
    last = 0  # init; whatever value different from 13
    sum = 0
    for e in nums:
        if e != 13 and last != 13:
            sum += e        # add the element to the sum
        last = e            # remember e as the last element for the next loop
    return sum


def sumNot13while(nums):
    last = 0  # init; whatever value different from 13
    sum = 0
    i = 0     # lists/arrays use zero-based indexing
    while i < len(nums):
        e = nums[i]         # get the current element
        if e != 13 and last != 13:
            sum += e        # add the element to the sum
        last = e            # remember e as the last element for the next loop
        i += 1              # the index must be incremented for the next loop
    return sum


if __name__ == '__main__':
   print(sumNot13for([2, 5, 7, 13, 15, 19]))
   print(sumNot13while([2, 5, 7, 13, 15, 19]))

   print(sumNot13for([2, 5, 7, 13, 13, 13, 13, 13, 13, 15, 19]))
   print(sumNot13while([2, 5, 7, 13, 13, 13, 13, 13, 13, 15, 19]))
于 2012-06-04T17:06:17.310 回答