Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Generate Fibonacci Series
- # Mike Kerry - 25-Jan-2021 - acclivity2@gmail.com
- # Very often, the solution to generating the Fibonacci series is coded to use a recursive function
- # I don't see the point as it is trivial to use a simple loop
- while True: # keep looping until an acceptable value is entered for the number of fibonacci elements
- strin = input("How many numbers in the Fibonacci series do you want? " ).strip()
- # isdecimal() checks that the input string consists of 0 to 9 only
- if strin.isdecimal() and int(strin) > 2:
- break # here we exit the loop if an acceptable value has been entered
- limit = int(strin) # convert the valid input to an integer
- fiblist = [1, 1] # We start with knowledge of the first 2 numbers in the Fibonacci sequence
- # We want to loop (limit - 2) times, but we have no need to know what loop number we are on, hence _ is used as loop control
- for _ in range(limit - 2):
- # use list splicing to access the last two integers in the series so far, and add them together using sum()
- # fiblist[-2:] references the last 2 numbers in fiblist.
- # The first time, this will be 1, 1 which are summed and appended to the list. So the list then becomes 1, 1, 2
- # On the second time, the last 2 items in fiblist are 1, 2. These are summed and appended, resulting in 1, 1, 2, 3
- # On cycle three, 2 + 3 = 5 resulting in 1, 1, 2, 3, 5 in fiblist
- # and so on
- fiblist.append(sum(fiblist[-2:]))
- print(*fiblist)
- # Results:
- # How many numbers in the Fibonacci series do you want? 18
- # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement