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

Python Exercise Example 13

Python Exercise Example 13

Python 100 Examples Python 100 Examples

**Question:** Print all "narcissistic numbers". A so-called narcissistic number is a three-digit number whose sum of the cubes of its digits equals the number itself. For example, 153 is a narcissistic number because 153 = 1 cubed + 5 cubed + 3 cubed.

**Analysis:** Use a for loop to iterate over the numbers from 100 to 999, splitting each number into its units, tens, and hundreds digits.

Program source code:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

for

n

in

range

(

100

,

1000

)

:

i

=

n

/

100

j

=

n

/

10

%

10

k

=

n

%

10

if

n

==

i

**

3

j

**

3

k

**

3

:

print

n

Example (Python 3.0+)

for

n

in

range

(

100

,

1000

)

:

i

=

n

//

100

j

=

n

//

10

%

10

k

=

n

%

10

if

n

==

i

i

i

j

j

j

k

k

k

:

print

(

n

)

The output of the above example is:


153
370
371
407

Python 100 Examples Python 100 Examples