Introduction
If you recently started out learning python, one of the ways to gain mastery of the language is to practice problem solving with Data Structures and Algorithm. There are a lot of sites that compile DSA problems that you can attempt as a beginner, eg Hackerrank, leet code, codewars etc.
In this article, we would write a simple python program that automatically generates a fibonacci sequence, when the user provides random starting points, and a limit.
Understanding the Logic
A fibonacci sequence is a set of integers, usually starting with 0 and 1, in which the next number in the sequence is a sum of the two preceding numbersEg : 0, 1, 1, 2, 3, 5, 8, 13...
In the example, after the starting points, 0 and 1, the next number(1) is a sum of 0 and 1, and (2) is a sum of 1 and 1, and so on.
Now, although a typical fibonacci sequence starts with a 0 and 1, we want to make our python program very flexible. It will require the user to choose any two starting points, and it will generate the rest of the numbers in that sequence.
For this function, we would be using a while loop. Loops essentially keep a program running until a particular condition is met.
Firstly, we would define our function, and define the parameters required.
def fibonacci_generator(sp1, sp2, lim):
Where sp1 = starting point 1, sp2 = starting point 2, and lim = limit. Then we would store our expected number sequence in a list, and set a condition for which the while loop will run. According to the logic for the program, we want to keep appending numbers in the sequence until the limit provided is reached(ie the last number in the sequence should be less than the limit)
def fibonacci_generator(sp1, sp2, lim):
sequence = [sp1, sp2]
while sequence[-1] < lim:
Next, we would write the body of the while loop. We want this loop to continously append the sum of the Last two numbers in the sequence list to the list, until we have reached the last possible number in the sequence, which is less than the limit. Ie; if the limit is 500, and the next number to be appended is 503, the loop should break, and return the list.
def fibonacci_generator(sp1, sp2, lim):
sequence = [sp1, sp2]
while sequence[-1] < lim:
next_num = sequence[-1] + sequence[-2]
if next_num > lim:
break
else:
sequence.append(next_num)
return sequence
Voila. We have a working program. You can test the program by calling the function and passing in the required arguments. Example:
Print(fibonacci_generator(2, 6, 50))
Output:
[2, 6, 8, 14, 22, 36]
In the example above, the next number in the sequence is 58, but will not be appended, because the limit is 50.
Conclusion
You can add more functionalities to the program, for practice. Eg, make the function return the number of numbers in a sequence, with the same parameters(starting points and limit). Hint: The len() function.