0

I'm trying to make a list of numbers on a single line that follow the Fib sequence. 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:

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.


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. 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. This list has spaces between each number though, and I don't want that. Is there a solution to this?

smollma
  • 239
  • 3
  • 12

6 Answers6

2

Slightly more streamlined than d-coder's version:

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]
swstephe
  • 1,840
  • 11
  • 17
  • OK, so as it goes I've got the standard recursive method and I'm asking the user for an nth fib number, let's call it x. I've then got a while loop with the condition x > 0 : print(fib(x)) and decrement f by one... This gives me a column output though? How do I use a function like list to make it as you have? – smollma Oct 25 '14 at 15:34
  • list accepts any sequence, even a "generator", (see the link I put in your OP), so it does the "for ... append" for you. I'm not using recursion here, just looping and returning each sequential value. – swstephe Oct 25 '14 at 16:55
2

An iterator is the "most Pythonic solution".

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]
Pi Marillion
  • 4,465
  • 1
  • 19
  • 20
  • OK, so as it goes I've got the standard recursive method and I'm asking the user for an nth fib number, let's call it x. I've then got a while loop with the condition x > 0 : print(fib(x)) and decrement f by one... This gives me a column output though? How do I use a function like list to make it as you have? Could I not just do print(list(fib(x))) – smollma Oct 25 '14 at 15:40
0

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:

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]]
parchment
  • 4,063
  • 1
  • 19
  • 30
0

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
Community
  • 1
  • 1
d-coder
  • 12,813
  • 4
  • 26
  • 36
0

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]
uselpa
  • 18,732
  • 2
  • 34
  • 52
-1
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)
4b0
  • 21,981
  • 30
  • 95
  • 142
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney May 09 '22 at 00:49