Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you answer this django interview question?

Tags:

python

django

I recently did a programming question for a pre-interview for a certain company. The questions was:

Create a django app, test driven of course, to display Fibonacci's sequence to the world. The app should take an index number and display the resulting Fibonacci sequence. Additionally, there should be a page that shows the most recent generated sequences. Also, Fibonacci is a bit impatient and doesn’t want to wait around forever, so make sure you take steps to make sure your webserver runs efficiently.

I came up with the following:

from django.views.generic.simple import direct_to_template
from django.http import Http404

LARGEST_SEQUENCE = [0,1] 
LARGEST = 1 
LATEST = []

def fib(n): 
    """Calculate the nth fibonacci sequence""" 
    global LARGEST
    if n > LARGEST: 
        while n > LARGEST: 
            next = LARGEST_SEQUENCE[LARGEST] + LARGEST_SEQUENCE[LARGEST-1] 
            #print 'appending ', next
            LARGEST_SEQUENCE.append(next)   
            LARGEST += 1  
        return LARGEST_SEQUENCE 
    else: 
        return LARGEST_SEQUENCE[0:n+1] 

def latest(request):
    results=[]
    for n in LATEST:
        result = fib(n)
        results.append((n,result))
    return direct_to_template(request, 'latest.html', {'results':results})

def index(request):
    if request.method=="POST":
        try:
            n=int(request.POST.get('n'))
        except:
            return Http404
        result = fib(n)
        if len(LATEST) >=  5:
            LATEST.pop()
        LATEST.insert(0,n)
    else:
        result = None
    return direct_to_template(request, 'base.html', {'result':result})

The "latest" view is my 2nd version because the 1st version didn't work consistently. The original version stored the result from "index" in LATEST. LATEST was originally a list of fib sequences (lists) instead of a list of recent values of N.

I guess my main question is, is it bad to store the largest fib sequence generated during runtime in the views.py file? I know this isn't persistent, but the instructions never really gave details on how things should be done. What do you guys think, and how would you have approached the problem?

Thanks guys!

like image 271
user701632 Avatar asked Sep 18 '11 20:09

user701632


1 Answers

Every linear reccurence equation can be solve directly. In fibonacci's case the equation is

f_n+2 = f_n+1 + f_n
f_1 = 1
f_2 = 1

The solution to this is:

f_n = 1/sqrt(5) * ((1+sqrt(5))/2)^n - 1/sqrt(5) * ((1-sqrt(5))/2)^n

Use this direct formula. For how to get to it look for linear reccurence equation solving. E.g. here.

Because of floating point errors, you should round the result to the nearest integer.

like image 74
Petar Ivanov Avatar answered Sep 24 '22 17:09

Petar Ivanov