2 Pairs 2 Lists - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: 2 Pairs 2 Lists (/thread-28980.html) |
2 Pairs 2 Lists - Harshil - Aug-12-2020 Problem: So Hey! Friends I Have Another Challenge And Is From My Friends! He Challenged Me For The Problem Below But I Failed SO I Decided To Ask Here So, I Have 2 Lists and i have to loop through each character and get a pair of 2 numbers that add upto 24 Fun Part: He Also Don't Know Answer Here Is The List1 And List2: list1 = [-1,3,8,2,9,5] list2 = [4,1,2,10,5,20] RE: 2 Pairs 2 Lists - DPaul - Aug-12-2020 Do you need to take one element from each list or not? (disregarding the fact that we can spot a solution a mile away) (or do you mean a pair each of 2 numbers = 4?) If you don't , add the lists together and loop over them. If you do, you may need 2 loops. Paul RE: 2 Pairs 2 Lists - Harshil - Aug-12-2020 (Aug-12-2020, 05:13 PM)DPaul Wrote: Do you need to take one element from each list or not? (disregarding the fact that we can spot a solution a mile away) Ahh, Sorry But I Don't Understand What are you telling RE: 2 Pairs 2 Lists - DPaul - Aug-12-2020 (Aug-12-2020, 05:14 PM)Harshil Wrote: Ahh, Sorry But I Don't Understand What are you telling Not so fast, i was still typing Then you can take several routes, one of them is examine combinations of 2. You will need to import itertools -> combinations. paul RE: 2 Pairs 2 Lists - Harshil - Aug-12-2020 (Aug-12-2020, 05:22 PM)DPaul Wrote:(Aug-12-2020, 05:14 PM)Harshil Wrote: Ahh, Sorry But I Don't Understand What are you telling Wait Wait Combos Do You Mean RE: 2 Pairs 2 Lists - DPaul - Aug-13-2020 OK, let's take this one step at the time. Your post is called "2 pairs, 2 lists". Are you looking to find a pair in each list that will sum up to 24 ? If so the algorithm for 1 list, will be the same for the other. Paul RE: 2 Pairs 2 Lists - DeaD_EyE - Aug-13-2020 list1 = [-1,3,8,2,9,5] list2 = [4,1,2,10,5,20] for e1, e2 in zip(list1, list2): print(e1, e2) Or if you want to make a new list from it:list12 = list(zip(list1, list2))If you require other results, then give us an example. RE: 2 Pairs 2 Lists - deanhystad - Aug-13-2020 There are only two numbers that add up to 24; 4 + 20, and they are both in the same list. You cannot add a number from list1 to a number from list2 to get 24. If you are just looking for two different numbers and the numbers can be from either list, the answer is 4 and 20 To solve the answer using one number from each list: for a in list1: for b in list2: if a + b == 24: print(f'{a} + {b} = 24')Tp solve for any combination of numbers in either list: numbers = list1 + list2 for a in numbers: for b in numbers: if a + b == 24: print(f'{a} + {b} = 24')This could be made more efficient if the lists were large or if you wanted to avoid double answers (4, 20 and 20, 4) |