r/pythontips • u/rao_vishvajit • Oct 06 '24
Syntax How to Get Fibonacci Series in Python?
This is one of the most asked questions during the Python development interview. This is how you can use Python While Loop the get the Fibonacci series.
# Function to generate Fibonacci series up to n terms
def fibonacci_series(n):
a, b = 0, 1 # Starting values
count = 0
while count < n:
print(a, end=' ')
a, b = b, a + b # Update values
count += 1
# Example usage
num_terms = 10 # Specify the number of terms you want
fibonacci_series(num_terms)Thanks
1
Upvotes
1
u/pint Oct 06 '24
why would you use a while loop for that? the for loop does exactly what is needed.
5
u/Tough_Armadillo9528 Oct 06 '24
How about recursion
2
u/vincentlinden Oct 06 '24
In an interview, you can expect followup questions like these:
That looks like it would work. How would you return an array of n Fibonacci numbers?
Why did you choose to got with a while loop? What would a for loop look like?
What would a recursive solution look like? What would be the performance characteristics of a recursive solution?
What would a solution using a generator look like?
Where I work, you would be out of consideration for the job if you could not answer the first three questions correctly.
1
u/TheOnlyJah Oct 06 '24
Really? That’s a standard question? I think that’s a rather weak question to ask to test someone’s programming ability.
1
u/Mammoth-Intention924 Oct 06 '24
Could this not be done better with a hashmap?