So I’m trying to make a program that tells the user how many numbers both inputted numbers have in common
FOR EXAMPLE: if inputted n1 = 765 and n2 = 572 then the program returns 2 because both numbers have 7 and 5 in them.
I made this but it isn’t working:
JavaScript
x
28
28
1
p = []
2
i = []
3
counter = [0] * 10
4
answer = 0
5
6
def conv(a):
7
p = [list(map(int, a))]
8
return p
9
10
def fed(a):
11
i = [list(map(int, a))]
12
return i
13
14
while True:
15
n = str(input("Enter the first number :"))
16
conv(n)
17
v = str(input("Enter the second number: " ))
18
fed(v)
19
counter = [0] * 10
20
answer = 0
21
for x in p:
22
counter[x] += 1
23
for x in i:
24
if counter[x] > 0:
25
counter[x] -= 1
26
answer += 1
27
print(answer)```
28
Advertisement
Answer
Use list comprehension and sets instead, like so:
JavaScript
1
8
1
while True:
2
nums = []
3
nums.append(input('Enter first number: '))
4
nums.append(input('Enter second number: '))
5
digits = [set(x) for x in nums]
6
num_comm = len(digits[0] & digits[1])
7
print(num_comm)
8