From 2e149da67abbec28026b18221f0e09f8032ff48d Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Sat, 9 Feb 2019 12:07:18 -0500 Subject: [PATCH] Added 2 functions for finding Fibonacci numbers --- Algorithms.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Algorithms.py b/Algorithms.py index b64bf2e..4461efd 100644 --- a/Algorithms.py +++ b/Algorithms.py @@ -147,3 +147,42 @@ def getDivisors(goalNumber: int) -> list: divisors.sort() #Return the list return divisors + +#This function returns the numth Fibonacci number +def getFib(goalSubscript: int) -> int: + #Setup the variables + fibNums = [1, 1, 0] #A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2 + + #If the number is <= 0 return 0 + if(goalSubscript <= 0): + return 0 + + #Loop through the list, generating Fibonacci numbers until it finds the correct subscript + fibLoc = 2 + while(fibLoc < goalSubscript): + fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3] + fibLoc += 1 + + #Return the propper number. The location counter is 1 off of the subscript + return fibNums[(fibLoc - 1) % 3] + +#This function returns a list of all Fibonacci numbers <= num +def getAllFib(goalNumber: int) -> list: + #Setup the variables + fibNums = [] #A list to save the Fibonacci numbers + + #If the number is <= 0 return an empty list + if(goalNumber <= 0): + return fibNums + + #This means that at least 2 1's are elements + fibNums.append(1) + fibNums.append(1) + + #Loop to generate the rest of the Fibonacci numbers + while(fibNums[len(fibNums) - 1] <= goalNumber): + fibNums.append(fibNums[len(fibNums) - 2] + fibNums[len(fibNums) - 3]) + + #At this point the most recent number is > goalNumber, so remove it + fibNums.pop() + return fibNums