更常见的是使用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]))