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. (´。• ω •。`)
#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


Messages In This Thread
RE: Review for my Fibonacci sequence, please. (´。• ω •。`) - by Gribouillis - Jun-06-2023, 10:09 AM

Forum Jump:

User Panel Messages

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