简体   繁体   中英

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. 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}

I'm running in 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. 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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