Discuss / Python / 至少有四种写法

至少有四种写法

Topic source

写法一:

def product(*args):
    j = 1
    i = 0
    if len(args) == 0:
        raise TypeError
    while i < len(args):
        j = j * args[i]
        i += 1
    return j

写法二:

def product(*args):
    if len(args) == 0:
        raise TypeError
    j = 1
    for i in args:
        j = j * i
    return j

写法三:

from functools import reduce
def product(*args):
    return reduce(lambda x,y:x*y,args)

写法四:

def product(*args):
    if not len(args):
        raise TypeError    
    result="1"
    for i in args:
        result=result+"*"+str(i)
    return eval(result)

均能实现最终的效果,供大家参考。

第五种写法,基本思路都差不多,写法上有些差异。

def product(*args):
    if not len(args):
        raise TypeError    
    lst=[str(i) for i in list(args)]
    result="*".join(lst)
    return eval(result)

第六种写法,使用嵌套函数:

def product(*args):
    def cal(lst):
        if len(lst) == 0:
            raise TypeError
        if len(lst) == 1:
            return lst[0]
        else:
            return lst.pop() * cal(lst) 
    return cal(list(args))

520bv

#4 Created at ... [Delete] [Delete and Lock User]

写法三赞一个,学习了

第七种写法

def product(x,*y):

    for i in y:

        x = x * i

    return x


  • 1

Reply