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

Python Check Whether a Number Is an Armstrong (Narcissistic) Number

Python Check Whether a Number Is an Armstrong (Narcissistic) Number

Document Object Reference Manual Python3 Examples

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

)

:

   

print

(

f

"{number} is an Armstrong number"

)

else

:

   

print

(

f

"{number} is not an Armstrong number"

)

Code analysis:

  1. num_str = str(num): convert the input number to a string so its digit count can be computed.
  2. n = len(num_str): compute the number of digits.
  3. sum_of_powers = sum(int(digit) ** n for digit in num_str): compute the sum of the n-th powers of the digits.
  4. return sum_of_powers == num: check whether the computed sum equals the original number; return True if so, otherwise False.

Output result:

153 是一个 Armstrong 数

Document Object Reference Manual Python3 Examples