【发布时间】:2021-04-11 12:54:11
【问题描述】:
我正在练习 Python,我想编写一个函数,它接受一个整数数组 x 和一个整数 y,并返回一个布尔值,用于判断 x 中的任何两个不同的数字加起来是否等于 y,例如:
add_check([1, 1, 2], 2) # Returns True
add_check([1, 1, 2], 3) # Returns True
add_check([2, 3], 4) # Returns False
这是我不完整的解决方案:
def add_check(x: list, y: int):
# create a dict object and add all the element in the list to the list
dictionary = {}
for i in range(len(x)):
dictionary.update({x[i]: i})
#print(dictionary)
for i in range(len(x)):
second_num = y - x[i]
if second_num in dictionary.values():
second_index = x.index(second_num)
if i != second_index:
print(True)
else:
print(False)
但是当我运行add_check([1, 1, 2], 2) 时,它会返回True False。
我现在有点迷茫,谁能帮忙,非常感谢。
【问题讨论】:
-
打印不等于返回。只有 return 会停止函数并将其值提供给调用者。
标签: python python-3.x dictionary arraylist