Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Number Is a Narcissistic Number

Python Check Whether a Number Is a Narcissistic Number

Document Object Reference Manual Python3 Examples

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.

Below is a Python program to check whether a number is a narcissistic number:

Example

def

is_narcissistic_number

(

num

)

:

   

Convert the number to a string for easy per-digit processing

    num_str

=

str

(

num

)

   

Get the number of digits

    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 equals the original number

   

return

sum_of_powers

==

num

Testing

number

=

153

if

is_narcissistic_number

(

number

)

:

   

print

(

f

"{number} is a narcissistic number"

)

else

:

   

print

(

f

"{number} is not a narcissistic number"

)

Code analysis:

  1. is_narcissistic_number The function takes an integer num as its argument.
  2. num_str = str(num) Convert the integer to a string for per-digit processing.
  3. n = len(num_str) Get the number of digits.
  4. sum_of_powers = sum(int(digit) ** n for digit in num_str) Compute the sum of the n-th powers of each digit.
  5. return sum_of_powers == num Check whether the computed sum equals the original number; if equal, return True; otherwise, returns False。
  6. In the test section, we tested the number 153 and output the result.

Output result:

153 是水仙花数

Document Object Reference Manual Python3 Examples