Python: Check Whether a Number is an Armstrong Number
An Armstrong number is an n-digit number whose sum of the n-th powers of its digits equals the number itself. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
Example
def is_narcissistic_number(num):
# Convert the number to a string to access each digit individually
num_str = str(num)
# Get the number of digits
n = len(num_str)
# Calculate the sum of the n-th powers of each digit
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check if it equals the original number
return sum_of_powers == num
# Test
number = 153
if is_narcissistic_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
# Convert the number to a string to access each digit individually
num_str = str(num)
# Get the number of digits
n = len(num_str)
# Calculate the sum of the n-th powers of each digit
sum_of_powers = sum(int(digit) ** n for digit in num_str)
# Check if it equals the original number
return sum_of_powers == num
# Test
number = 153
if is_narcissistic_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
Code analysis:
num_str = str(num): Convert the input number to a string to access each digit individually.n = len(num_str): Get the number of digits.sum_of_powers = sum(int(digit) ** n for digit in num_str): Calculate the sum of the n-th powers of each digit.return sum_of_powers == num: Determine whether the calculated sum equals the original number. If true, returnTrue, otherwise returnFalse。
Output result:
153 是水仙花数Other extensions
Python3 Examples