python三个数求和_Python:list是否包含3个连续的整数,总和为7...
我正在為我的編碼訓練營準備應用程序的準備材料.這是我在使用(使用Python)時遇到的實踐問題:
“編寫一個函數’lucky_sevens(numbers)’,該函數接收一個整數列表,如果任意三個連續元素的總和為7,則輸出True.
確保您的代碼正確檢查數組的第一個和最后一個元素.”
我知道如何一次在一個元素中循環遍歷一個數組,但是不知道如何“保留”一個元素,同時還根據提示要求評估相對于第一個元素的第二個和第三個元素.從下面的嘗試中可以看出,我不確定何時/何地/如何增加索引值來搜索整個列表.
def lucky_sevens(numbers):
index1 = 0 # For assessing 1st of 3 numbers
index2 = index1 + 1 # For assessing 2nd of 3 numbers
index3 = index2 + 1 # For assessing 3rd of 3 numbers
# If all index values are within the list...
if index1 <= (len(numbers) - 2) and index2 <= (len(numbers) - 1) and index3 <= len(numbers):
# If the values at those indices sum to 7...
if numbers[index1] + numbers[index2] + numbers[index3] == 7:
print True
else:
print False
# I think the increments below may be one of the places I am incorrect
index1 += 1
index2 += 1
index3 += 1
當我跑步
lucky_sevens([2, 1, 5, 1, 0])
我認為這是打印False,因為它只考慮第0、1和2位置的元素(總和為8,而不是7).
它應該顯示True,因為位于第一,第二和第三位置的元素總計為7.(1 5 1 = 7).
有人可以提供建議嗎?我會很感激.
總結
以上是生活随笔為你收集整理的python三个数求和_Python:list是否包含3个连续的整数,总和为7...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: settimeout( )是全局函数吗_
- 下一篇: python自动化开发_python自动