方法一
import
functools
sum
=
0
for
i
in
range
(
1
,
21
):
sum
=
sum
+
functools.
reduce
(
lambda
x,y: x
*
y,
range
(
1
, i
+
1
))
print
(
sum
)
lambda x,y: x*y 的意思是:有一个函数,接受x, y两个参数做乘法。
import
functools
方法二
def
f(n):
if
n
=
=
1
:
return
1
else
:
return
functools.
reduce
(
lambda
x,y: x
*
y,
range
(
1
, n
+
1
))
+
f(n
-
1
)
print
(f(
20
))
方法三
def
plus(n):
if
n
=
=
1
:
return
1
else
:
return
reduce
(
lambda
x,y: x
*
y,
range
(
1
,n
+
1
))
+
plus(n
-
1
)
print
plus(
20
)
方法四
sum
=
0
x
=
1
for
i
in
range
(
1
,
21
):
x
=
x
*
i
sum
=
sum
+
x
print
(
sum
)