0

How to modify the program so that it does not repeat the pairs, without creating new array

# Print all pairs of numbers in array A whose sum is greater than 10 A = [4,5,2,1,3,7] for value_1 in A: for value_2 in A: total = value_1 + value_2 if (total > 10): print (value_1, " + ", value_2, " > 10") # OUTPUT # 4 + 7 > 10 # 5 + 7 > 10 # 7 + 4 > 10 <-- Repeated # 7 + 5 > 10 <-- Repeated # 7 + 7 > 10 <-- same element

17th Feb 2017, 11:49 PM
Javier I. Rivera R.
Javier I. Rivera R. - avatar
4 odpowiedzi
+ 8
This is the best solution I could think of: def pair(li,n): pairs = [] for i in li: for j in li: c = sorted((i,j)) total = i + j if total > n: if c not in pairs: pairs.append(c) yield c A = [4,5,2,1,3,7] for (x,y) in pair(A,10): print(x,y) #output: 4 7 #output: 5 7 #output: 7 7 I hope it helps :)
18th Feb 2017, 1:06 AM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 7
@richard Great solution!
18th Feb 2017, 7:46 AM
Aidan Haddon-Wright
Aidan Haddon-Wright - avatar
+ 2
test = [4,5,2,1,3,7] for ind,item in enumerate(test,1): indx = ind while indx < len(test): if item + test[indx] > 10: print(item,test[indx]) indx +=1 # or you may want to research itertools # for more wide ranging applications of list pairings import itertools for i in itertools.combinations(test,2): if sum(i)>10: print(i)
19th Feb 2017, 6:23 AM
richard
0
Thank you very much Aidan, very good answer, but your code makes use of an array to save the pairs. I try to do it without that array.
18th Feb 2017, 2:08 AM
Javier I. Rivera R.
Javier I. Rivera R. - avatar