Computer Science, asked by 2908955956, 8 months ago

Daffodil number" means a three-digit number whose sum of the cubes of the digits is equal to the number itself. Write a python program to ask the user to input a three-digit positive integer n. If n is a “daffodil number”, print “YES”, otherwise, print “NO”.

Answers

Answered by QGP
1

Daffodil Number - Python

An Armstrong Number is a number whose sum of cubes of digits is equal to the number itself.

A Daffodil Number is a three-digit Armstrong Number.

Here, we will first take user input, and then check length of input string. If the length is not 3, we print error message.

We use a try-except block for the int() typecasting operation so that we can catch any exception and print an appropriate error message. So, if the 3 digit string contains any non-numerical characters, we can handle the error.

Now, we use list comprehension to extract the digits and simulatneously find their cubes and store in a list. Finally, we sum the list and if it is equal to the original number, we print "YES". Else, we print "NO".

 \rule{300}{1}

The Code

# Take input

n = input("Enter a three digit number: ")

if(len(n)!=3):   # If length is not 3, print error message

   print("Not a 3 digit number")

else:

   try:    # try-except block to catch exception

       # Extract list of cubes of digits with list comprehension

       digits_cubed = [int(i)**3 for i in n]

       

       # Sum the digits

       cube_sum = sum(digits_cubed)

       if (int(n) == cube_sum):

           print("YES")

       else:

           print("NO")

   

   except:     # Print error in case of exception

       print("Please enter only digits")

Attachments:
Similar questions