Skip to content
Advertisement

Find how many numbers two numbers have in common

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:

    p = []
i = []
counter = [0] * 10
answer = 0

def conv(a):
  p = [list(map(int, a))]
  return p

def fed(a):
  i = [list(map(int, a))]
  return i

while True:
 n = str(input("Enter the first number :"))
 conv(n)
 v = str(input("Enter the second number: " ))
 fed(v)
 counter = [0] * 10
 answer = 0
 for x in p:
   counter[x] += 1
   for x in i:
      if counter[x] > 0:
        counter[x] -= 1
        answer += 1
  print(answer)```

Advertisement

Answer

Use list comprehension and sets instead, like so:

while True:
    nums = []
    nums.append(input('Enter first number: '))
    nums.append(input('Enter second number: '))
    digits = [set(x) for x in nums]
    num_comm = len(digits[0] & digits[1])
    print(num_comm)
Advertisement