mirror of
https://bitbucket.org/Mattrixwv/pyclasses.git
synced 2025-12-06 18:33:58 -05:00
Created fibonacci generator
This commit is contained in:
@@ -52,6 +52,14 @@ def primeGenerator():
|
||||
#Skip all multiples of 2
|
||||
possiblePrime += 2
|
||||
|
||||
def fibGenerator():
|
||||
#The first and second fibonacci numbers are 1 and 1
|
||||
a, b = 1, 1
|
||||
|
||||
while(True):
|
||||
yield a
|
||||
a, b = b, a + b
|
||||
|
||||
#This function returns a list with all the prime numbers <= goalNumber
|
||||
def getPrimes(goalNumber: int) -> list:
|
||||
primes = []
|
||||
@@ -148,38 +156,30 @@ def getDivisors(goalNumber: int) -> list:
|
||||
|
||||
#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
|
||||
gen = fibGenerator() #The fibonacci number generator
|
||||
|
||||
#If the number is <= 0 return 0
|
||||
if(goalSubscript <= 0):
|
||||
return 0
|
||||
#Loop through the numbers up to the subscript we want
|
||||
for _ in range(1, goalSubscript):
|
||||
next(gen)
|
||||
|
||||
#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]
|
||||
#The next number is F(goalSub), return it
|
||||
return next(gen)
|
||||
|
||||
#This function returns a list of all Fibonacci numbers <= num
|
||||
def getAllFib(goalNumber: int) -> list:
|
||||
#Setup the variables
|
||||
gen = fibGenerator() #The Fibonacci number generator
|
||||
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)
|
||||
#There is at least one number in the list now
|
||||
fibNums.append(next(gen))
|
||||
|
||||
#Loop to generate the rest of the Fibonacci numbers
|
||||
while(fibNums[len(fibNums) - 1] <= goalNumber):
|
||||
fibNums.append(fibNums[len(fibNums) - 1] + fibNums[len(fibNums) - 2])
|
||||
fibNums.append(next(gen))
|
||||
|
||||
#At this point the most recent number is > goalNumber, so remove it
|
||||
fibNums.pop()
|
||||
|
||||
Reference in New Issue
Block a user