Advertisement
acclivity

pyFibonacci (Without Recursion)

Jan 25th, 2021 (edited)
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. # Generate Fibonacci Series
  2.  
  3. # Mike Kerry - 25-Jan-2021 - acclivity2@gmail.com
  4.  
  5. # Very often, the solution to generating the Fibonacci series is coded to use a recursive function
  6. # I don't see the point as it is trivial to use a simple loop
  7.  
  8. while True:     # keep looping until an acceptable value is entered for the number of fibonacci elements
  9.     strin = input("How many numbers in the Fibonacci series do you want? " ).strip()
  10.  
  11.     # isdecimal() checks that the input string consists of 0 to 9 only
  12.     if strin.isdecimal() and int(strin) > 2:
  13.         break               # here we exit the loop if an acceptable value has been entered
  14.  
  15. limit = int(strin)          # convert the valid input to an integer
  16.  
  17. fiblist = [1, 1]            # We start with knowledge of the first 2 numbers in the Fibonacci sequence
  18.  
  19. # 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
  20. for _ in range(limit - 2):
  21.     # use list splicing to access the last two integers in the series so far, and add them together using sum()
  22.     # fiblist[-2:] references the last 2 numbers in fiblist.
  23.     # The first time, this will be 1, 1 which are summed and appended to the list. So the list then becomes 1, 1, 2
  24.     # On the second time, the last 2 items in fiblist are 1, 2. These are summed and appended, resulting in 1, 1, 2, 3
  25.     # On cycle three, 2 + 3 = 5 resulting in 1, 1, 2, 3, 5 in fiblist
  26.     # and so on
  27.     fiblist.append(sum(fiblist[-2:]))
  28.  
  29. print(*fiblist)
  30.  
  31. # Results:
  32.  
  33. # How many numbers in the Fibonacci series do you want? 18
  34. # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement