我正在准备申请编程训练营的资料,以下是一道我遇到困难的练习题(使用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)。
请问有人能提供建议吗?我将非常感激。