【每日一题20220610】链式计算

:mage:‍ 给定一个初始数字和一个函数对象列表,我们的任务就是,将初始值依次传入函数中,后续的函数输入正是前面函数的输出。请编写一个函数,计算出最终的结果值。

【示例】

def add10(x): return x + 10
def mul30(x): return x * 30

输入:50, [add10, mul30]
输出:1800
解释:首先将50传入add10函数,50+10=60;再将60传入mul30函数,得到30*60=1800

题目难度:简单
题目来源:codewars-Chain me

def solution(n, funcs: list)-> int:
    # your code here

assert solution(50, [add10, mul30]) == 1800
assert solution(50, [mul30]) == 1500
assert solution(42, []) == 42
def add10(x): return x + 10
def mul30(x): return x * 30


def solution(n, funcs: list) -> int:
    # your code here
    if (l := len(funcs)) > 0:
        return funcs[l-1](solution(n, funcs[:l-1]))
    else:
        return n


assert solution(50, [add10, mul30]) == 1800
assert solution(50, [mul30]) == 1500
assert solution(42, []) == 42
1 Like
def solution(n, funcs: list)-> int:
    if funcs is None:
        return n
    for i in funcs:
        n = i(n)
    return n

assert solution(50, [add10, mul30]) == 1800
assert solution(50, [mul30]) == 1500
assert solution(42, []) == 42
1 Like
def solution(n, funcs: list) -> int:
    if len(funcs):
        for fun in funcs:
            n = fun(n)
        return n
    return n

assert solution(50, [add10, mul30]) == 1800
assert solution(50, [mul30]) == 1500
assert solution(42, ) == 42

1 Like

image

def solution(n, funcs: list)-> int:
    for func in funcs:
        n=func (n)
    return n

def solution(n, funcs: list)-> int:
    if funcs==[]:
        return n
    for i in funcs:
        n=i(n)
    return n
关闭