Home > database >  Write a function which verifies if the number it takes as parameter is an Armstrong number or not
Write a function which verifies if the number it takes as parameter is an Armstrong number or not

Time:11-14

Write a function which verifies if the number it takes as parameter is an Armstrong number or not. Armstrong number is the number that, it should be equal to the powers of its digits (the power here is the number of digits)

I did with an if statement. I need help to make this with a function.

n = int(input("Enter a number: "))

a = n /1000
b = n/100%10
c = n/10%10
d = n%10

if (a**4) (b**4) (c**4) (d**4) == n:
    print("Its an Armstrong number!")
else
    print("Its Not an Armstrong")
    

CodePudding user response:

I find it easier to work with str(num) when dealing with digits of num. You can first construct a list of digits by using this str trick. Then you can apply sum and comprehension to the list.

def is_armstrong(num):
    digits = [int(d) for d in str(num)] # list of digits
    return sum(d ** len(digits) for d in digits) == num

print(*(x for x in range(10000) if is_armstrong(x))) # armstrong numbers < 10000
# 0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474

CodePudding user response:

def is_amstrong_number(n : int):
    return n == sum([int(x)**3 for x in str(n)])

You can try this

  • Related