Backwards
Backwards

Reputation: 29

How to check if input number is unique [Python]

I want to check if the user's 3-digit number input has no repeat digits (eg. 122, 221, 212, 555).

num = 0

while True:
  try:
    num = int(input("Enter a 3-Digit number: "))
    if (num % 10) == 2:
      print("ensure all digits are different")

This somewhat works, tells me that the numbers 122 or 212 are have repeats, but not for 221, or any other 3-digit number

Upvotes: 0

Views: 2320

Answers (3)

Rohith V
Rohith V

Reputation: 1123

You can also make use of a dictionary to check whether digits are repeated or not. Take the remainder as you did in your code (taking mod 10)and add that remainder into the dictionary. Everytime we take the remainder, we check inside the dictionary whether the number is present or not because if the number is present inside the dictionary, then it is not unique.

Code :

    num = int(input())
    dictionary = {}
    while num > 0:
        remainder = num % 10
        if remainder in dictionary.keys():
            print("Not unique")
            break
        else:
            dictionary[remainder] = True
        num = num // 10
    

Upvotes: 0

maria maria
maria maria

Reputation: 76

A %b gives the remainder if a is divided by b. Rather than doing this just take the number as string and check if any of the two characters present in the string are same.

num = 0

while True:
  try:
    num = (input("Enter a 3-Digit number: "))
    if (num[0] == num[1] or num[1]==num[2] or num[2]==num[0])
      print("ensure all digits are different")

Upvotes: 0

revmatcher
revmatcher

Reputation: 950

num = input()
if len(set(num)) != len(num):
    print("The number has repeat digits!")
else:
    print("No repeat digits")

Upvotes: 1

Related Questions