Skip to content Skip to sidebar Skip to footer

How Do I Print A Fibonacci Sequence To The Nth Number In Python?

I have a homework assignment that I'm stumped on. I'm trying to write a program that outputs the fibonacci sequence up the nth number. Here's what I have so far: def fib(): n =

Solution 1:

Non-recursive solution

deffib(n):
    cur = 1
    old = 1
    i = 1while (i < n):
        cur, old, i = cur+old, cur, i+1return cur

for i inrange(10):
    print(fib(i))

Generator solution:

deffib(n):
    old = 0
    cur = 1
    i = 1yield cur
    while (i < n):
        cur, old, i = cur+old, cur, i+1yield cur

for f in fib(10):
    print(f)

Note that generator solution outperforms the non-recursive (and non-recursive outperforms recursive, if memoization is not applied to recursive solution)

One more time, recursive with memoization:

defmemoize(func):
    memo = dict()
    defdecorated(n):
        if n notin memo:
            memo[n] = func(n)
        return memo[n]

    return decorated

@memoizedeffib(n):
    #added for demonstration purposes only - not really neededglobal call_count
    call_count = call_count + 1#end demonstration purposesif n<=1:
        return1else:
        return fib(n-1) + fib(n-2)

call_count = 0#added for demonstration purposes only - not really neededfor i inrange(100):
    print(fib(i))
print(call_count) #prints 100

This time each fibbonacci number calculated exactly once, and than stored. So, this solution would outperform all the rest. However, the decorator implementation is just quick and dirty, don't let it into production. (see this amazing question on SO for details about python decorators :)

So, having fib defined, the program would be something like (sorry, just looping is boring, here's some more cool python stuff: list comprehensions)

fib_n = int(input("Fib number?"))
fibs = [fib(i) for i inrange(fib_n)]
print" ".join(fibs) 

this prints all numbers in ONE line, separated by spaces. If you want each on it's own line - replace " " with "\n"

Solution 2:

deffibonacci(n):
  if n <= 1:
    return n
  else:
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(int(input())))

And since you want to print up to the nth number:

[print(fibonacci(n)) for n inrange (int(input()))]

And for python2.7 change input to raw_input.

Solution 3:

Please note, in your call

  1. You are not calling fib() recursively
  2. You need a wrapper method so that the input is not requested every time the method is called recursively
  3. You do not need to send in a list. Just the number n is good enough.

This method would only give you the nth number in the sequence. It does not print the sequence.

You need to return fib(n-1) + fib(n-2)

deff():
    n = int(input("Please Enter a number: "))
    print fib(n)

deffib(n):    
    if n == 0: 
        return0elif n == 1: 
        return1else: 
        return fib(n-1)+fib(n-2)

Solution 4:

This might be faster incase of long list

# Get nth Fibonacci number defnfib(nth):
  sq5 = 5**.5
  phi1 = (1+sq5)/2
  phi2 = -1 * (phi1 -1)
  resp = (phi1**(nth+1) - phi2**(nth+1))/sq5
  return long(resp)

for i inrange(10):
  print i+1, ": ",  nfib(i)

OUTPUT

1 :12 :13 :24 :35 :56 :87 :138 :219 :3410 :55

Solution 5:

deffib(n):
   if n == 1:
      return(1)
   elif n == 0:   
      return(0)            
   else:                      
      return fib(n-1) + fib(n-2)

my_num = int(input("Enter a number:"))
print fib(my_num)

Im not really sure what your question is... but the answer is probably something like this

Post a Comment for "How Do I Print A Fibonacci Sequence To The Nth Number In Python?"