简体   繁体   English

如何将这个 Python 可变函数转换为不可变函数?

[英]How can I convert this Python mutable function into immutable?

I have a mutable Fibonacci function that mutates a list in order to return that list as a fib sequence.我有一个可变的 Fibonacci 函数,它改变一个列表,以便将该列表作为 fib 序列返回。 I want to do the same thing... but the list (or tuple in this case) should not be able to change.我想做同样的事情……但列表(或本例中的元组)不应该改变。 The return still has to send the whole list, how can I implement this, without using recursion.返回仍然必须发送整个列表,我如何在不使用递归的情况下实现这一点。

Ex) if x = 6... list should return {1,1,2,3,5,8}例如) 如果 x = 6... 列表应该返回 {1,1,2,3,5,8}

I'm running in python 3.5我在 python 3.5 中运行

Here is my code:这是我的代码:

def mutableFib(x):
result = []
for y in range(0,x):
    if y < 2:
        result.append(1)
    else:
        last = result[y - 1]
        previous = result[y - 2]
        result.append(last + previous) //result is being changed
return result

You could create a new list for every new element.您可以为每个新元素创建一个新列表。

def fibonacci(x):
    list_of_fibonaccis = []
    for y in range(0,x):
        if y < 2:
            temp_fibonacci = [1] * (y + 1)
        else:
            last = list_of_fibonaccis[y-1][-1]
            previous = list_of_fibonaccis[y-1][-2]
            temp_fibonacci = list_of_fibonaccis[y-1] + [last + previous]
        list_of_fibonaccis.append(temp_fibonacci)
    return list_of_fibonaccis[-1]

If I understand what you mean by "a functional approach that doesn't use recursion," it seems like the input parameter should be a list of the first n Fibonacci numbers and the output should be a list of the first n+1 Fibonacci numbers.如果我理解你所说的“不使用递归的函数式方法”是什么意思,似乎输入参数应该是前 n 个斐波那契数的列表,输出应该是前 n+1 个斐波那契数的列表. If this is correct, then you could use如果这是正确的,那么你可以使用

def fibonacci(fib):
    if not fib: return [1]
    if len(fib) == 1: return [1,1]
    return fib + [fib[-1]+fib[-2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM