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

Python Exercise Example 18

Python Exercise Example 18

Python 100 Examples Python 100 Examples

**Question:** Find the value of s=a+aa+aaa+aaaa+aa...a, where a is a digit. For example, 2+22+222+2222+22222 (five numbers added together in this case); the number of terms is controlled by the keyboard.

**Analysis:** The key is to compute the value of each term.

Program source code:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

Tn

=

0

Sn

=

[

]

n

=

int

(

raw_input

(

'

n =

'

)

)

a

=

int

(

raw_input

(

'

a =

'

)

)

for

count

in

range

(

n

)

:

Tn

=

Tn

a

a

=

a

10

Sn

.

append

(

Tn

)

print

Tn

Sn

=

reduce

(

lambda

x

,

y

:

x

y

,

Sn

)

print

"

The calculated sum is:

"

,

Sn

Example (Python 3.0+)

#!/usr/bin/python

from

functools

import

reduce

Tn

=

0

Sn

=

[

]

n

=

int

(

input

(

'

n =

'

)

)

a

=

int

(

input

(

'

a =

'

)

)

for

count

in

range

(

n

)

:

Tn

=

Tn

a

a

=

a

10

Sn

.

append

(

Tn

)

print

(

Tn

)

Sn

=

reduce

(

lambda

x

,

y

:

x

y

,

Sn

)

print

(

"

The calculated sum is:

"

,

Sn

)

The output of the above example is:


n = 4
a = 4
4
44
444
4444
计算和为: 4936

Python 100 Examples Python 100 Examples