Self-Descriptive Numbers Program

Self-Descriptive Numbers Program

Coding Project in Python

Write a Python program that asks the user to enter a number and checks whether the number is self-descriptive.

Considering the digit positions are labeled 0 to N-1, it is a self-descriptive number if the digit in each position is equal to the number of times that digit appears in the number.

For example: 2020 is a self-descriptive number beacause:

  • Position 0 is 2 and there are two 0’s in the number
  • Position 1 is 0 and 1 doesn´t appear.
  • Position 2 is 2 and 2 appears twice in the number.
  • Position 3 is 0 and there are no 3 0’s

Steps

  1. Input:
    • Ask the user to enter a number.
  2. Check Self-Descriptiveness:
    • Loop over each digit in the number and count the occurrences of that digit.
  3. Verify Self-Descriptiveness:
    • Compare the count of each digit with the digit itself to verify if the number is self-descriptive.

Solution


def is_self_descriptive(number):
    num_str = str(number)
    length = len(num_str)

    for i in range(length):
        count = num_str.count(str(i))
        if count != int(num_str[i]):
            return False
    return True

# Step 1: Take Input
user_number = input("Enter a number: ")

try:
    user_number = int(user_number)

    # Step 2 & 3: Check Self-Descriptiveness and Verify Self-Descriptiveness
    if is_self_descriptive(user_number):
        print(f"The number {user_number} is self-descriptive")
    else:
        print(f"The number {user_number} is not self-descriptive")

except ValueError:
    print("Please enter a valid number")

 

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for Practice
Register New Account
Shopping cart