Python Check Whether a Number Is an Armstrong (Narcissistic) Number
An Armstrong number (narcissistic 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_armstrong_number
(
num
)
:
Convert the number to a string to make counting digits easier
num_str
=
str
(
num
)
n
=
len
(
num_str
)
Compute the sum of the n-th powers of the digits
sum_of_powers
=
sum
(
int
(
digit
)
** n
for
digit
in
num_str
)
Check whether it is an Armstrong number
return
sum_of_powers
==
num
Testing
number
=
153
if
is_armstrong_number
(
number
)
:
(
f
"{number} is an Armstrong number"
)
else
:
(
f
"{number} is not an Armstrong number"
)
Code analysis:
num_str = str(num): convert the input number to a string so its digit count can be computed.n = len(num_str): compute the number of digits.sum_of_powers = sum(int(digit) ** n for digit in num_str): compute the sum of the n-th powers of the digits.return sum_of_powers == num: check whether the computed sum equals the original number; return True if so, otherwise False.
Output result:
153 是一个 Armstrong 数
Python3 Examples