Python Exercise Example 25
**Question:** Find the sum of 1+2!+3!+...+20!.
**Analysis:** This program simply changes accumulation into multiplication.
Method 1
#!/usr/bin/python
-- coding: UTF-8 --
n
=
0
s
=
0
t
=
1
for
n
in
range
(
1
,
21
)
:
t
*=
n
s
+=
t
(
'
1! + 2! + 3! + ... + 20! = %d
'
%
s
)
Method 2
#!/usr/bin/python
-- coding: UTF-8 --
s
=
0
l
=
range
(
1
,
21
)
def
op
(
x
)
:
r
=
1
for
i
in
range
(
1
,
x
1
)
:
r
*=
i
return
r
s
=
sum
(
map
(
op
,
l
)
)
(
'
1! + 2! + 3! + ... + 20! = %d
'
%
s
)
The output of the above example is:
1! + 2! + 3! + ... + 20! = 2561327494111820313
Python 100 Examples