0

I'm trying to write a Fibonacci sequence that can take a user's input as the multiplier for the generational increase in rabbits, i.e., 4 pairs of offspring produced for each pair of mature rabbits.

I have tried storing the integer form of the input in a new variable and moving around the position of when the raw input is asked:

def fibonacci(x):
    if x == 1:
        rabbit_pairs = 1
        return rabbit_pairs
    elif x == 2:
        rabbit_pairs = 1
        return rabbit_pairs
    elif x > 2:
        y = int(input("How many offspring per pair? ")) 
        rabbit_pairs = fibonacci(x-1) + (y * fibonacci(x-2))
        return rabbit_pairs

When I run my code, if x > 2, my input question is asked but it keeps getting asked instead of returning the corresponding number of rabbits. If x == 5, the command prompts for the number of rabbits per pair and then keeps asking for the number of rabbits per pair.

Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
  • Just try to execute the given code in your mind you will know the exact problem. You are getting input in the function and calling the function again and again. – damjad Aug 04 '19 at 16:22
  • **y = int(input("How many offspring per pair? "))** This line is executing with every function call. You need to replace it to the correct position – Lalit Mehra Aug 04 '19 at 16:34

1 Answers1

0

As per your code you are recursively calling the fibonacci for x > 2, So when you pass x == 5, The function call are ,

fibonacci(x-1) + (y * fibonacci(x-2))

fibonacci(4) + (5 * fibonacci(3))
In this case fibonacci(4) and fibonacci(3), x > 2  

so the following statement will be executed until x <= 2

y = int(input("How many offspring per pair? ")) 

Ideally you should put this question outside the recursive function and pass the value in you fibonacci(x)

Neha Jirafe
  • 741
  • 5
  • 14