+ 1

Can you help me improve this Python code?

Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17 This is the code I came up with : alist=[1,3,5,6,9] check=False k=int(input("Enter a number : ")) for i in range(5): for j in range(5): if((alist[i]+alist[j])==k): print(alist[i],"+",alist[j],"=",k) check=True if check!=True: print("Numbers dont add up") else : print("Therefore numbers add up") The code is running fine, but if I enter the value of k as 10, this is what I get as output : Enter a number : 10 1+9=10 5+5=10 9+1=10 Notice that 5 is repeated twice, which should not happen. A number should be used only once. I could add this condition while alist[i]!=alist[j] But is there a better way to write this code?

21st Apr 2019, 6:23 PM
Yash Ahuja
Yash Ahuja - avatar
5 Réponses
+ 7
One thing I would do would be to change the range you have set for your for loops. Just to make it a bit more dynamic, you can set the first for loop to have a range of len(alist) so that it loops through the entirety of the list, no matter its size. For the inner loop, instead of having it loop through every single element in that list, you could have it loop through every element ahead of it (ex. The first iteration would check if 1 + 3 = 10, 1 + 5 = 10, and so forth, the second would check if 3 + 5 = 10, 3 + 6 = 10, and so forth). All you would need to do to do that is set the range to range(i+1, len(alist)) to loop through everything correctly.
21st Apr 2019, 6:44 PM
Faisal
Faisal - avatar
+ 3
#i have this try :) alist=[1,3,5,6,9] check=False k=int(input("Enter a number : ")) for i in alist: for j in alist: if(i != j and i+j==k): print(i,"+",j,"=",k) if(check==False): print("Numbers dont add up") else: print("Therefore numbers add up")
21st Apr 2019, 6:44 PM
Sousou
Sousou - avatar
+ 2
Thanks Faisal and Sousou
21st Apr 2019, 7:27 PM
Yash Ahuja
Yash Ahuja - avatar
+ 1
My implimentation is based on simplicity. Hope you like it🙂 # my implementation alist = [1,3,5,6,9] check = False k = int(input("Enter a number: ")) result = 0 second = 0 for i in alist: result = k - i if result in alist and result != i: check = True second = i break if check == False: print("Numbers dont add up") else: print(f"{second} + {result} = {k}")
23rd Apr 2019, 11:15 AM
Trigger
Trigger - avatar
0
Thanks Thomas. Thats a nice approach to the problem👍👍
23rd Apr 2019, 5:54 PM
Yash Ahuja
Yash Ahuja - avatar