我正在为一堂课做一些作业,作业在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循环,但我只是不明白。
答案 0 :(得分:1)
看起来你快到了;您只需要在适当的位置实际将nums[i]
的值添加到sum
。还要重新考虑return sum
行的缩进。
答案 1 :(得分: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]))