2

I'm trying to have the program count how many elements in 2 different lists are shared.

One list is randomized.

import random

Lotterya = [random.randint(1,49) for _ in range(6)]

And the other is user-input.

Lotteryb = []
while len(Lotteryb) < 6:
    n = int(input("enter number: "))
    Lotteryb.append(n)

What code do I use to let the program say: "There are _ numbers in common."?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
BETTY
  • 29
  • 2
  • Nothing in your code counts anything. The simples (not efficient's - but with 6 numbers this "efficiency" is a moot point due to overhead of set-tification) way would be a loop through one and check if the number is `in` the other list and then increment a counter. Next time please make your code a [mre] (hint: includes, what you tried to solve it) and show your effort and what went wrong with it. – Patrick Artner Jun 23 '21 at 05:26

2 Answers2

2

Convert both to set and take intersection

x = set(Lotterya)
y = set(Lotteryb)

z = x.intersection(y)

print(z)
Saharsh
  • 1,056
  • 10
  • 26
1

Converting the two lists into sets and the finding the intersection to fin the common elements. As shown below:-

list1 = [1, 2, 3, 2, 3, 2, 1, 1, 1]
list2 = [1, 4, 3, 5, 2, 7, 8, 2, 1]

set1 = set(list1)
set2 = set(list2)

result = set1.intersection(set2)
print(result)  # elements that are common
print(len(result))  # number of elements that are common

This might help.

sam2611
  • 455
  • 5
  • 15