Calculate the sum of two numbers in python, with a nums list and target value

1. Given an integer list nums and a target value target, please find the two integers whose sum is the target value in the array, and return their list indexes. ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬ ‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

Each input needs to correspond to only one answer. However, you cannot reuse elements at the same position in this array. ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬
If no solution is found , output "Fail"
input two lines, ‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮ ‬‫‬‫‬


3 2 4 1 5
6

The first line enters a set of integers separated by spaces, and the data is all int type. ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬
The second line of input an integer
output


1 2

If there is a solution, output the solution of the first set of data (the first element with the smallest index). ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬
If there is no solution, output "Fail"

2. Code part


lst=list(map(int,input().split()))
# split()是将输入的字符以空格分隔,map是转换为int类型的数据,最后再转换为列表
# 转化后为[3,2,4,1,5]
target=eval(input())
t=len(lst)
# 求lst的长度
flag=0
# 设置一个标志数
for i in range(t):
    if flag==1:
        break
    else:
    # 说明是从小到大来进行遍历的
        for j in range(t):
            if lst[i]+lst[j]==target and i!=j :
                print("{} {}".format(i,j))
                flag=1
                break
# 找不到数据,就是flag==0,按规定返回
if flag==0:
    print("Fail")


3. The results are as follows

3 2 4 1 5
6
1 2

Guess you like

Origin blog.csdn.net/m0_74459049/article/details/130126201