Posted on:

27 Jun 2022

1

Resolved: I just would like to share a more complete solution (a bit more complicated)

It uses the brutal way, but it accounts also for the case of many pairs that satisfy the target and it shows either the positions or the numbers in those positions (it could be useful to someone, I have already found a similar question here):

def calc(l,num):
    pos=[]
    acc=0
    for i in range(len(l)-1):
        for j in range(i+1,len(l)):
            if l[i]+l[j]==num:
                pos.append([i,j])
                acc+=1
    if acc>0:
        return pos,acc
    else:
        return -1,acc
l=[2,5,3,55,6,1,5,12,1,1,2,123,54,2,6,12,6,3,5,1,4,7,3,7,2,1,4,5,3,7,8,5,8,55,23,54,12,6,23,12,11,10,9,78,32,31,13,43,55,76,23,15,87,45,78,34,85,72,61,94,42]
pos=calc(l,161)
if pos[1]>0:
    print(f'There have been found {pos[1]} pairs and they are in the following positions:\n')
    for i in range(pos[1]):
        print(f'{pos[0][i]} -> {l[pos[0][i][0]]}+{l[pos[0][i][1]]}\n')
else:
    print('There haven't been found any pairs')

0 answers ( 0 marked as helpful)

Submit an answer