python3 for sum_Python for循环和“sum13”方法
我是一個剛開始學習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'
總結
以上是生活随笔為你收集整理的python3 for sum_Python for循环和“sum13”方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue2实践揭秘pdf_《Vue2实践揭
- 下一篇: php 鼠标点击图片放大,css3如何实