0

I am writing a program where a user inputs data for two lists ( numbers ) and then the program outputs the matching numbers from both of the lists. I have written a bit of code to manually achieve this but I need to implement a way where the user can input numbers for themselves instead of just hardcoding them in.

see below desired output:

List 1: 1 2 3 4
List 2: 4 2 0 0 
output: [4 , 2 ]

My bellow code achieves the desired result but not how it's intended, my code takes values from a list and calculates the intersection, and prints the result but not as outlined as above.

a = [1,2,3,4]
b = [4,2,0,0]
c = set(a) & set(b)  
print('Output:',c)

could you please help and explain how this is achieved. thanks

Yakob
  • 159
  • 1
  • 7

1 Answers1

1

If you need to keep the order in the list, you can work directly on the lists and use a simple list comprehension:

a = [1,2,3,4]
b = [4,2,0,0]    
c = [el for el in b if el in a]
print('Output:',c)

Output:

[4, 2]

EDIT 1. If you want the user to input the numbers one by one, you can do something like this:

n = int(input('Provide the amount of numbers for each list: '))

a = [int(input(f'List a, element {i+1}: ')) for i in range(n)]
b = [int(input(f'List b, element {i+1}: ')) for i in range(n)]
c = [el for el in b if el in a]
print('Output:',c)

For more variants, you can use this as a baseline and add up type checks or variable length arrays (by making user input two initial numbers n and m) and similar.


EDIT 2. If you want the user to input the lists directly, you can do something like this:

a = map(int, input('List 1: ').strip().split())  # e.g. "1 2 3 4"
b = map(int, input('List 2: ').strip().split())  # e.g. "4 2 0 0"
c = [el for el in b if el in a]
print('Output:',c)

I wouldn't recommend this solution as this is easily more prone to user input errors.

lemon
  • 14,875
  • 6
  • 18
  • 38
  • the list is fine, i just need a way to let a user input the numbers in the list instead of hard coding them in – Yakob May 09 '22 at 23:11
  • edited my answer accordingly @Yakob – lemon May 09 '22 at 23:18
  • that sort of works, but is there a way to do this without having to continually ask for multiple numbers, just have the user input [ 1,2,3,4] in one go ? – Yakob May 09 '22 at 23:26
  • 1
    added an edit 2 that will let you input all numbers for each list in one go, though as I've mentioned in the side note, I wouldn't advise a solution that relies too much on human attention @Yakob – lemon May 09 '22 at 23:39
  • thanks for your answer @lemon however, the code works but only produces one number that is similar instead of all instances of similar numbers between lists – Yakob May 10 '22 at 00:58
  • edit your question to include any border-line case @Yakob – lemon May 10 '22 at 01:00