How do I print a fibonacci sequence to the nth number in Python?

前端 未结 7 1620
忘了有多久
忘了有多久 2020-12-31 22:24

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:

7条回答
  •  渐次进展
    2020-12-31 22:32

    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)

    def f():
        n = int(input("Please Enter a number: "))
        print fib(n)
    
    def fib(n):    
        if n == 0: 
            return 0
        elif n == 1: 
            return 1
        else: 
            return fib(n-1)+fib(n-2)
    

提交回复
热议问题