Home > Software engineering >  problem with a list checking mini algorithm in python
problem with a list checking mini algorithm in python

Time:02-23

i want to make a mini programme to get all the couples(x,y) of a list that satisfy 'x y = sum'



ar= [1,2,3,4,5,3,6,7,9,8,10,13,18]

sum = 9


for i in ar:

    noclubs = [x for x in ar if x != ar[i]]
    for z in noclubs:
        if ar[i]   noclubs[z] == sum:
            print(ar[i],noclubs[z])

it shows me this error" if ar[i] noclubs[z] == sum: IndexError: list index out of range"

here is the code plz help me

CodePudding user response:

You can use iteration variables instead

ar= [1,2,3,4,5,3,6,7,9,8,10,13,18]

sum = 9


for i in ar:

    noclubs = [x for x in ar if x != i]
    for z in noclubs:
        if i   z == sum:
            print(i,z)

CodePudding user response:

More code but potentially more efficient. This is because if any element in the list is greater than or equal to the target value then there's no point in including it or any higher in the calculations. So:

from itertools import combinations

ar = [1,1,2,3,4,5,3,6,7,9,8,10,13,18]

total = 9

def get_pairs(a, s):
    result = set()
    for combo in combinations([e for e in a if e < s], 2):
        if sum(combo) == s:
            result.add(combo)
    return result

print(get_pairs(ar, total))

Output:

{(4, 5), (1, 8), (2, 7), (3, 6)}
  • Related