Fibonacci Sequence based question slightly changed

Question:

I was recently given this question in one of my interview which I ofcourse, failed.

Question

I just want to know how this will be solved. The code I tried to use was this:

def gibonacci(n, x, y):
    # Base case
    if n == 0:
        return x
    elif n == 1:
        return y
    else:
        sequence = [x, y]
        for i in range(2, n):
            next_term = sequence[i-1] - sequence[i-2]
            sequence.append(next_term)
        return sequence[-1]

Any help, even just the logical help will be enough. Thanks!

Asked By: Avi Thour

||

Answers:

Your question was a bit vague for me, but try the following code, it might help you.

Try this:

def gibonacci(n,x,y):   
    if n == 0:
        return x

    elif n == 1:
        return y

    else:
        for i in range(1, n):
            c = y - x
            x = y
            y = c

        return y

print(gibonacci(2,0,1))
Answered By: Ali

As I said in comments, I am pretty sure the interview was made to check who can think to the problem before thinking to the solution.

See what your sequence is
g₀ = x
g₁ = y
g₂ = y-x
g₃ = y-x – y = -x
g₄ = -x – (y-x) = -y
g₅ = -y – (-x) = x-y
g₆ = x-y – (-y) = x
g₇ = x – (x-y) = y

Once you got 2 repeating items in the sequence, you can’t do anything other than repeat the rest. Said otherwise, gₙ₊₆=gₙ forever. So, the pattern is always the same length-6 cycle: x, y, y-x, -x, -y, x-y

Hence the faster solution, without any iteration

def gibonacci(n, x, y):
   if n%3==0:
       r=x
   elif n%3==1:
       r=y
   else:
       r=y-x
   if (n//3)%2:
       return -r
   else: 
       return r

Works in O(1) (contrarily to iterative methods that are O(n)).

More "raw" (faster, but less explicit with the logic. Anyway, all O(1)) variants can exist. Such as this one-liner:

def gibonacci(n, x, y):
    return [x,y,y-x,-x,-y,x-y][n%6]

I am not the interviewer. So I can’t presume what was they looking for. But my instinct is that the accepted answer would have failed the interview, even if it works, and that the expected answer was in the line of this one.

Answered By: chrslg
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.