我该如何修复我的功能?

时间:2016-09-12 23:09:30

标签: python function

我被告知......从评论中修复我的功能,让它看起来更清洁"。我已经尝试了很多..但我不知道如何使用llambda来完成我想要做的事情。我的代码有效......它不仅仅是对我的要求。

以下是我的代码,其中包含有关如何修复它的建议。

def immutable_fibonacci(position):

    #define a lambda instead of def here
    def compute_fib (previousSeries, ignore):
        newList = previousSeries

        if len(newList) < 2: # Do this outside and keep this function focused only on returning a new list with last element being sum of previous two elements
           newList.append(1)

        else:
           first = newList[-1]
           second = newList[-2]
           newList.append(first+second)
        return newList

    range=[None]*position
    return reduce(compute_fib, range, []) 

#Above is too much code. How about something like this:
#next_series = lambda series,_ : (Use these instead of the above line)
#return reduce(next_series, range(position - 2), [1, 1])

任何事情都有帮助......我对如何实施这些建议感到困惑。

这是我的尝试。

def immutable_fibonacci(position):
    range=[None]*position
    next_series = lambda series, _ : series.append(series[-1] + series[-2])
    return reduce(next_series, range(position - 2), [1, 1])

1 个答案:

答案 0 :(得分:0)

append函数返回None。您需要返回更新的数组

next_series = lambda series: series + [series[-1] + series[-2]]

同时重命名range不能用于任何目的。

def immutable_fibonacci(position):
    next_series = lambda series: series + [series[-1] + series[-2]]
    return reduce(next_series, range(position - 2), [1, 1])

这假设您只调用位置&gt; = 2的函数。传统的fib(0)为0,fib(1)为1.