我是一个刚开始学习Python的本地C++程序员,我已经给出了以下的写作方法:Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
我的解决方案是:def sum13(nums):
elem_sum = 0
index = 0
while index < len(nums):
if nums[index] != 13:
elem_sum += nums[index]
else:
index += 1 #nums[i] is 13, so skip the next element'
index += 1
return elem_sum
熟悉其他基于C语言的人会发现这里的循环类似于(相当干净)
^{pr2}$
请注意,我几天前才开始学习Python,所以我对这门语言还是很陌生的。我希望有人能提供一些关于如何以“Python”的方式编写这个循环的建议,或者使用一些我可能不知道的语言特性提供一个更干净的解决方案。在
在我之前的尝试中(没有成功),我有:for i in range(len(nums)):
if nums[i] != 13:
elem_sum += nums[i]
else:
i += 1 #nums[i] is 13, so skip the next element'