简体   繁体   English

Python 3 斐波那契数列的递归 - 列出

[英]Python 3 Recursion for Fibonacci Sequence - Listed

I'm trying to make a list of numbers on a single line that follow the Fib sequence.我正在尝试在 Fib 序列之后的一行中列出数字列表。 I'm using the recursive method of Fib(n) = Fib(n-1)+Fib(n-2) and this gives me a single value of course, when I use:我正在使用 Fib(n) = Fib(n-1)+Fib(n-2) 的递归方法,这当然给了我一个单一的值,当我使用:

return fib(n-1)+fib(n-2)

How can I make this loop and give me a list?我怎样才能制作这个循环并给我一个列表? For example: [1,1,2,3,5,8,13] if I typed in: 7 for n .例如: [1,1,2,3,5,8,13]如果我输入: 7 for n


OK, so in some ways I have fixed it.好的,所以在某些方面我已经修复了它。 I now ask the user to input a value, say x, which is then used in a while loop.我现在要求用户输入一个值,比如 x,然后在 while 循环中使用它。 It passes the x value through the recursive fib function, appends this new value to a list and then decrements f by 1. Then I used list.reverse() to reverse the list so that the numbers appear in ascending order and I then print the list.它通过递归 fib function 传递 x 值,将这个新值附加到列表中,然后将 f 减 1。然后我使用 list.reverse() 反转列表,以便数字按升序显示,然后我打印列表。 This list has spaces between each number though, and I don't want that.虽然这个列表在每个数字之间都有空格,但我不希望这样。 Is there a solution to this?有针对这个的解决方法吗?

Slightly more streamlined than d-coder's version: 比d编码器的版本略精简:

def fib(n):
    a,b = 1,1
    for i in xrange(n):
        yield a
        a,b = b,a+b

>>> list(fib(11))
>>> [1,1,2,3,5,8,13,21,34,55,89]

An iterator is the "most Pythonic solution". 迭代器是“最Python化的解决方案”。

class Fib:
    # init creates the iterator
    def __init__(self, start=0, end=None):
        self.now = 0   # the most recent number in the Fibonacci sequence
        self.last = 0  # second most recent number in the Fibonacci sequence
        self.i = 0     # current place in the sequence
        self.end = end # last place before we stop
        # loop through sequence until we get to start
        for i in range(start):
            void = self.next()

    def __iter__(self):
        return self

    # next() for Python 2
    def next(self):
        # stop if end is reached
        if self.end is not None and self.i > self.end:
            raise StopIteration
        # find the next Fibonacci number
        next = self.now + self.last
        self.last = self.now
        self.now = next if next > 0 else 1
        # keep track of how many numbers we've output
        self.i += 1
        # return the next number
        return self.last

    # __next__() for Python 3
    def __next__(self):
        return next(self)

Then use it like so: 然后像这样使用它:

# print starting at 0
for i in Fib(0, 5):
    print i
0
1
1
2
3

# print starting at 1
for i in Fib(1, 6):
    print i
1
1
2
3
5

# make a list
list(Fib(end=10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

The obvious solution would be: 显而易见的解决方案是:

l = []
for i in range(n):
    l.append(fib(i))

However, this would be rather inefficient. 然而,这将是相当低效的。 Another approach would be modifying your recursive function to return a list of fibonacci numbers until n: 另一种方法是修改递归函数以返回斐波那契数的列表,直到n:

def fib(n):
    if n <= 0:
        raise ValueError
    elif n == 1:
        return [1]
    elif n == 2:
        return [1, 1]
    else:
        prev = fib(n-1)
        return prev + [prev[-2] + prev[-1]]

Try the following code and let me know it helped you.About generators you can find help here and here 尝试以下代码,让我知道它对您有所帮助。关于生成器,您可以在此处此处找到帮助。

def fibonacci(n):
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(7)                  ## pass the value here
my_list =[]
for x in f:
    my_list.append(x)
print my_list

Recursive version, using memoization for performance: 递归版本,使用记忆来提高性能:

def fib(n, hash = {0:1, 1:1}):
    if n not in hash:
        hash[n] = fib(n-1) + fib(n-2)
    return hash[n]

testing: 测试:

>>> print(list(fib(i) for i in range(7)))
[1, 1, 2, 3, 5, 8, 13]
>>> print(list(fib(i) for i in range(11)))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def fib(n):
    if n <= 0:
        return 0
    elif n == 1 or n == 2:
        return 1
    else:
        return fib(n-1)+ fib(n-2)
        
n=10      
l = []
for i in range(n):
    l.append(fib(i))
print(l)

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

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