From 0b31ecd522a43e2290fb7ce53b676a4640d0e6e4 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Thu, 29 Oct 2020 10:56:58 -0400 Subject: [PATCH] Created fibonacci generator --- Algorithms.py | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Algorithms.py b/Algorithms.py index 9cdaf67..cc0a6a5 100644 --- a/Algorithms.py +++ b/Algorithms.py @@ -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()