如何获得函数来返回2个数字的索引,这些数字加起来就是一个目标值



我正在编写一个函数,以获取一个整数列表和一个名为target的整数,并返回列表中两个数字的索引,使它们相加为target。但我的代码并没有按应有的方式工作。该函数最终根本不打印任何内容。我该怎么解决这个问题?我是一个初学者,我不知道出了什么问题:(

def solution(list, target):
firstindex = 0
secondindex = -1
while(firstindex <= len(list)-1):
if list[firstindex] + list[secondindex] == target:
print(f"The sum was found at index {firstindex} and {secondindex}")
break
else:
firstindex = firstindex + 1
secondindex = secondindex - 1
#I am calling the function here
solution([1,2,3,4,5, 6], 5)

您可以使用这种方法来解决问题。

def solution(list, target):
n = len(list)
for firstindex in range(n - 1):
for secondindex in range(firstindex + 1, n):
if list[firstindex] + list[secondindex] == target:
print(f"The sum was found at index {firstindex} and {secondindex}")
solution([1,2,3,4,5, 6], 5)

不太确定您试图解决的任务的总体方法,这取决于您实现的算法和启动参数,您可能会收到多个结果,而不是一个值。

查看您的示例列表和目标值,对(1,4((2,3(都将求解目标值。

原则上,如果你不使用任何跟踪变量值的IDE,或者不想使用任何库来保持轻量级,我建议你用笔和纸遍历循环的变量值,或者在代码中打印输出,作为一种简单的调试方法,比如:

def解决方案(列表,目标(:firstindex=0secondindex=-1

while(firstindex <= len(list)-1):
print(firstindex)
print(secondindex)
if list[firstindex] + list[secondindex] == target:
print(f"The sum was found at index {firstindex} and {secondindex}")
break
else:
firstindex = firstindex + 1
secondindex = secondindex - 1

#我正在调用这里的函数溶液([1,2,3,4,5,6],5(

您会发现,从-1开始的第二个索引将同时递减到第一个索引,而在迭代第一个索引时它不会保持固定。希望对调试有所帮助。真的,试着先在纸上用算法解决这个问题。

干杯,让我知道进展如何

编辑:我完全搞砸了我的想法,因为Python确实使用了负索引来从列表的最后一项开始并返回。需要停止思考C…

不要将list用作函数获取的第一个列表的变量名,它是python中的一个关键字。

edit:
您引用的是函数中的关键字list,它表示python中的类型对象。你基本上是指物体的分类。相反,将变量分配给另一个名称,如def solution(original, target):

相关内容

最新更新