[Tutor] Trying to find all pairs of numbers from list whose sum is 10

Alan Gauld alan.gauld at yahoo.co.uk
Sat Jun 19 14:47:43 EDT 2021


On 19/06/2021 19:24, Manprit Singh wrote:

> lst = [2, 4, 7, 5, 9, 0, 8, 5, 3, 8]
> in this list there are 3 pairs (2, 8), (5, 5), (7, 3) whose sum is 10. To
> finding these pairs i have written the code as below :
> 
> def pair_ten(x):
>     y, st  = x[:], set()
>     for i in x:
>         y.remove(i)
>         st.update((i, ele) for ele in y if i+ele == 10)
>     return st

> But i feel the code is still more complex, due to two for loops, in
> what way this ccan be dome more efficiently.

More concisely, but not necessarily more efficiently(in terms of
excution speed)

import itertools as it

lst = [2, 4, 7, 5, 9, 0, 8, 5, 3, 8]

result = [pr for pr in set(it.combinations(lst,2))
             if sum(pr) == 10]
print(result)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list