程序分析:此程序只是把累加变成了累乘。

方案一:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

n = 0
s = 0
t = 1
for n in range(1,21):
    t *= n
    s += t
print '1! + 2! + 3! + ... + 20! = %d' % s
方案二:

#!/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))
print '1! + 2! + 3! + ... + 20! = %d' % s
方案三:输入任一个数的前n项和

    def theJieCheng(self, num):
        '返回一个数的阶乘'
        sum = 1
        for i in range(2, num + 1):
            sum *= i
        return sum

    def theSumOfNum(self, num):
        '求num的阶乘之和'
        num = int(num)
        sum = 1
        for i in range(2, num + 1):
            sum += code.theJieCheng(i)
        print(sum)




Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐