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 Number

Python Check Whether a Number Is an Armstrong Number

Document Object Reference Manual Python3 Examples

An Armstrong number (also called 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 an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Below is a Python program that checks whether a number is an Armstrong number.

Example

def

is_armstrong_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 the sum equals the original 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 each digit can be accessed individually.
  2. n = len(num_str): get 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 each digit. A list comprehension iterates over each digit, converts it to an integer, raises it to the power, and finally the sum() function sums them.
  4. return sum_of_powers == num: check whether the computed sum equals the original number, and if so return True; otherwise, returns False。

Output result:

153 是一个 Armstrong 数

Document Object Reference Manual Python3 Examples