【发布时间】:2015-09-25 01:45:30
【问题描述】:
我正在为我的编码训练营申请准备材料。这是我正在努力解决的一个实践问题(使用 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,因为第 1、第 2 和第 3 个位置的元素总和为 7。 (1 + 5 + 1 = 7)。
谁能给点建议?我将不胜感激。
【问题讨论】:
-
感谢您的链接,@Tyler。很有趣。