我尝试将满足目标的唯一对传递给函数调用。python有点新,所以请告诉我如何修复它
array = [ 3, 4, 5, 9, 10, -1, 6 ]
target = 9
def twoSum (array, target):
for i in range(0, len(array)):
for x in range( i + 1, len(array)):
totalOfTwo = array[i] + array[x]
if (totalOfTwo == target):
pairsList = (array[i], array[x])
return -1
result = twoSum (array, target)
if result != -1:
print ("the intergers numbers meet target", result)
else:
print ("result is not in range")
我想这就是你要找的
您需要将这些对添加到列表中,如果找到,则返回它们
另外,就我个人而言,如果没有找到空列表,我会返回空列表,而不是-1,因为它们是不同的数据类型
您忘记返回结果
你的密码
我的代码
但这只是第一个结果,所以
如果我们没有正确的答案,结果是一个空列表(
[]
),那么实现这一点最具python风格的方式是作为列表理解,它只是一行
(请注意,这有助于提前终止,但您可以只分割第[0]个元素。)
关于您的代码/函数方法,我将其改写为(下次请要求对CodeReview.SE上的工作代码进行审查,而不是在这里进行审查):
评论:
if result:
测试返回值,您不需要任何笨重的if result != -1
或if result is None
twoSum
重命名为two_sum
以遵循函数名和变量的Python命名约定(PEP-8):小写字母带下划线return (a[i], a[j])
更改为yield (a[i], a[j])
,这将使它成为一个按顺序返回所有(/any)匹配元组的生成器。(您需要将return None
替换为yield StopIteration
)totalOfTwo
将被称为total_of_two
或pair_sum
totalOfTwo
,pairsList
声明临时变量,直接使用表达式即可pairsList
不是列表,而是元组array
不是数组,而是列表。但我只能称之为a
李>i
到len(a)-1而不是len(a),因为我们知道需要j来索引其右侧的元素李>相关问题 更多 >
编程相关推荐