求1+2+3+...+n python

递归

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return n and n + self.Sum_Solution(n-1)

reduce()函数

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        def f(n,m):
            return n+m
        return reduce(f,list(range(1,n+1)))

猜你喜欢

转载自blog.csdn.net/qq_41359265/article/details/84254752
今日推荐