简体   繁体   中英

Checking whether a 3 digit number is an armstrong number and returning boolean by describing a function in python3

I tried as input method but unable to return a boolean value as the function's output. Given a 3 digit number, check whether it is an angstrom number or not.

An Amstrong number is a number where the sum of cubes of the digits are equal to the number.

If your input is taken as a string, you can iterate over the digits since strings are iterable in python:

def is_armstrong(num):
    return str(sum(int(digit)**3 for digit in num)) == num

If you already have the input as a number, you can "iterate" over the digits by taking modolu 10 of the number in each iteration to extract the last digit:

def is_armstrong(num):
    n = num
    s = 0
    while n > 0:
        digit = n % 10
        s += digit ** 3
        n //= 10

    return s == num
input_number = input("Enter input number :")
input_value = int(input_number)
sum = 0
for i in range(len(input_number)):
    d = int(input_number[i])**len(input_number)
    sum = sum + d

if sum == input_value:
    print("True")
else:
    print("False")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM