Python Check Whether a Number Is a Narcissistic Number
A 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 a narcissistic number because 1^3 + 5^3 + 3^3 = 153.
Example
def
is_narcissistic_number
(
num
)
:
Convert the number to a string so each digit can be accessed individually
num_str
=
str
(
num
)
Get the number of digits
n
=
len
(
num_str
)
Compute the sum of the n-th powers of each digit
sum_of_powers
=
sum
(
int
(
digit
)
** n
for
digit
in
num_str
)
Check whether it equals the original number
return
sum_of_powers
==
num
Testing
number
=
153
if
is_narcissistic_number
(
number
)
:
(
f
"{number} is a narcissistic number"
)
else
:
(
f
"{number} is not a narcissistic number"
)
Code analysis:
num_str = str(num): convert the input number to a string so each digit can be accessed individually.n = len(num_str): get 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 each digit.return sum_of_powers == num: Check whether the computed sum equals the original number; if so, returnTrue; otherwise, returnsFalse。
Output result:
153 是水仙花数
Python3 Examples