Python Forum
Review for my Fibonacci sequence, please. (´。• ω •。`)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Review for my Fibonacci sequence, please. (´。• ω •。`)
#1
Lightbulb 
Salutations, Pythonistas! python
I hope you are all well and that your families and friends are doing well. ヽ(・∀・)ノ

I have developed a simple piece of code that prints the Fibonacci sequence. I would like to get feedback on my novice coding skills from people more experienced than me. I applied things I have learned from courses, the official documentation and playing with the Python IDLE, ha, ha. Tongue

Before posting the code, I should clarify that the reason I avoided commenting on it was for two reasons:

  1. I would like to know how self-explanatory my code is.
  2. The truth is that I am terrible at it, ha, ha. Could you give me some advice, please?

That being said, now with you, the code:

def fibonacci(limit: int) -> 'Sequence in a List':
    n1, n2 = 0, 1
    accumulated: int = 0
    sequence: list = []
    while accumulated < limit:
        accumulated = n1 + n2
        n1 = n2
        n2 = accumulated
        sequence.append(accumulated)
    return sequence

while True:
    limit = input("Please, enter a limit for the sequence: ")
    try:
        print(fibonacci(int(limit)))
        break
    except ValueError:
        print(f"{limit} is not an integer.")
I'll stay tuned to the thread for any critiques, reviews, comments, etc. Thank you very much in advance, my friends! I hope your day is going well. ٩(。•́‿•̀。)۶
Reply
#2
1) I think your code is quite self-explanatory, that's a good point.

2) The interaction loop could be written this way, so that the exception catches the exact conversion that we want to check
if __name__ == '__main__':
    while True:
        user_input = input("Please, enter a limit for the sequence: ")
        try:
            limit = int(user_input)
        except ValueError:
            print(f"{user_input!r} is not an integer.")
        else:
            break
    print(fibonacci(limit))
You could use multiple assignment to avoid a temporary variable
def fibonacci(limit: int) -> 'Sequence in a List':
    n1, n2 = 0, 1
    sequence: list = []
    while n2 < limit:
        n1, n2 = n2, n1 + n2
        sequence.append(n2)
    return sequence
Finally, here is an screwball version for you to study
from itertools import accumulate, chain, takewhile, tee

def fibonacci(limit: int) -> "Sequence in a list":
    def S():
        yield from _s
    s, _s = tee(accumulate(chain((1, 0), S())))
    return list(takewhile(limit.__ge__, s))

if __name__ == '__main__':
    while True:
        user_input = input("Please, enter a limit for the sequence: ")
        try:
            limit = int(user_input)
        except ValueError:
            print(f"{user_input!r} is not an integer.")
        else:
            break
    print(fibonacci(limit))
Carmazum likes this post
Reply
#3
barebones, similar to w3 schools example:
>>> def fibseq(n): 
...     if n in (0,1):
...         return n
...     return fibseq(n-1) + fibseq(n-2)
... 
>>> print([fibseq(n) for n in range(12)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Carmazum likes this post
Reply
#4
(Jun-06-2023, 10:11 AM)Larz60+ Wrote: barebones:
Barbones, but an example of algorithmic antipattern. Improve this with @functools.lru_cache perhaps. Use dynamic programming.
Carmazum and Larz60+ like this post
Reply
#5
Griboullis Wrote:Barbones, but an example of algorithmic antipattern. Improve this with @functools.lru_cache perhaps. Use dynamic programming.
From Python.org
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print([fib(n) for n in range(16)])
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
Gribouillis and Carmazum like this post
Reply
#6
There is one issue
Reply
#7
Consider the complexity of your solution. How would you solve it in a more efficient way?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020