【每日一题0623】自行设计一个函数mysum,支持输入任意个参数,输出求和结果

用python实现
例如 输入 1,2,3 输出6
可能参数里面有字符串形式的数字,需转换,如’1’,2,3 输出6

def add_1(*n):
    result = 0
    n2 = [] #str和int的全部转换成int格式
    for i in range(len(n)):
        n2.append(int(n[i]))
    for j in n2:
        result += j
    return result


assert add_1('1', 2, 3) == 6
assert add_1(1, 2, -6, 0, 10) == 7
assert add_1(1) == 1
assert add_1(1, -2, '10') == 9

题解1:使用内置函数 sum

def fn(*values):
    return sum([int(str(x)) for x in values])

assert 6 == fn(1,2,3)
assert 6 == fn('1',2,3)

解法2:使用生成器itertools.accumulate

import itertools
import operator
def fn2(*values):
    return itertools.accumulate([int(str(x)) for x in values], operator.add)[-1]
    
assert 6 == fn(1,2,3)
assert 6 == fn('1',2,3)
def mysum(*args):
    return sum(map(int,args))

assert  mysum(1, 2, 3) == 6
assert  mysum('1', 2, 3) == 6
#coding=utf-8

def fn(*values):
    sum=0
    for i in range(len(values)):
        sum+=int(values[i])
    return sum

if __name__ == '__main__':
    print(fn(1,2,5,6))
    print(fn('1','4',6))
# 方法 1
def fun_sum(args: List):
    sum_num = sum([int(i) for i in args])
    print(sum_num)


# 方法 2
def fun_sum2(*args):
    sum_num = sum(list(map(lambda x: int(x), args)))  # map(function, iterable....)
    print(sum_num)
    sum_num2 = sum(map(int, args))
    print(sum_num2)

// TODO:未考虑参数里面有字符串形式的文字。