Your functions do too many things:
- get input from user
- do some calculation
- print result
It would be better to separate these responsibilities,
following the single responsibility principle.
When you separate these responsibilities, the Fibonacci generation logic will naturally end up in its own function, and the reusability becomes obvious.
Consider this rewrite of your
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
:param n: the number of items to calculate
:return: list of the first n items in the sequence
a = 1
b = 1
k = 2
seq = [a, b]
while k < n:
c = a + b
k += 1
a = b
b = c
- removed the printing
- removed the user input
- follows PEP8
- better variable names
- has a doctest
The most interesting part is the doctest.
You can run doctests with the command:
python -m doctest script.py
Let's add a bunch more doctests:
[1, 1, 2]
And let's rerun the doctests. Which of these new tests will fail?
fib_sequence(1) will fail. Just like your original implementation always printed the first two 1s, this one also always returns a list starting with
[1, 1, ...].
The good thing is that now that we have the tests, we can go ahead and confidently refactor the implementation.
As a matter of fact, a nice way to generate sequences in Python is using generators. Here's an implementation of the Fibonacci sequence using a generator:
prev = 1
current = 1
prev, current = current, prev + current
Now we can rewrite
fib_sequence in terms of this new
it = fib()
return [next(it) for _ in range(n)]
If we rerun the doctests, now they all pass.
We can further simplify this implementation using
return list(itertools.islice(fib(), 0, n, 1))
To finish up, let's rewrite
Fibonnacci_sequence in terms of
n = int(input("How many numbers of the Fibonacci sequence do you want to see: "))
for num in fib_sequence(n):
It's a lot cleaner isn't it.
I invite you to write a
fib_nth method similarly, following the same logical steps we took for
- remove the prompting and printing, make it return a value
- write doctests, for all the interesting cases
fib_nth in terms of
fib_seqnum in terms of