0

So just for fun I created a small little python script that prompts the user for a number and then prints out that many digits of the Fibonacci sequence. The script that I came up with works, but I can't help but feel its a bit convoluted and there is a probably a better and simpler way to do it.

How could I simplify this script and still have it accomplish the same thing?

def fib(number):
    if number == 0:
        return 0
    elif number == 1:
        return 1
    else:
        numbers = [1, 1]
        for i in range(number - 2):
            i = numbers[-2] + numbers[-1]
            numbers.append(i)
        return numbers

x = int(raw_input("How many digits of the Fibonacci sequence would you like to see?"))

Results = fib(x)

print Results
Nikita Petrov
  • 51
  • 1
  • 1
  • 5

1 Answers1

0
  def fib(n):
        cur = 1
        old = 1
        i = 1
        while (i < n):
            cur, old, i = cur+old, cur, i+1
        return cur

    for i in range(10):
        print(fib(i))
Keshav Kumar
  • 1,057
  • 1
  • 19
  • 34
  • The indentation of this code is broken. But even when we fix that it doesn't "accomplish the same thing" as the OP's code, which returns a list of Fibonacci numbers for an arg > 1. BTW, the usual modern convention is that Fibonacci(0) is 0, not 1. That's mostly to be consistent with [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression). – PM 2Ring Mar 25 '17 at 08:58