mirror of
https://bitbucket.org/Mattrixwv/pyclasses.git
synced 2025-12-06 18:33:58 -05:00
Added 2 functions for finding Fibonacci numbers
This commit is contained in:
@@ -147,3 +147,42 @@ def getDivisors(goalNumber: int) -> list:
|
|||||||
divisors.sort()
|
divisors.sort()
|
||||||
#Return the list
|
#Return the list
|
||||||
return divisors
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user