Question:

How do you make a Django app that is test driven and will display Fibonacci’s sequence?

Answer:

Keep in mind that it should take an index number and output the sequence. Additionally, there should be a page that shows the most recent generated sequences.

Following is one of the solution for generating fibonacci series:

def fib(n):
    "Complexity: O(log(n))"
    if n <= 0:
        return 0
    i = n - 1
    (a, b) = (1, 0)
    (c, d) = (0, 1)
    while i > 0:
        if i % 2:
            (a, b) = (d * b + c * a,  d * (b + a) + c * b)
        (c, d) = (c * c + d * d, d * (2 * c + d))
        i = i / 2
    return a + b

Below is a model that would keep track of latest numbers:

from django.db import models
 
class Fibonacci(models.Model):
    parameter = models.IntegerField(primary_key=True)
    result = models.CharField(max_length=200)
    time = models.DateTimeField()

For view, you can simply use the following code:

from models import Fibonacci
 
def index(request):
    result = None
    if request.method=="POST":
        try:
            n=int(request.POST.get('n'))
        except:
            return Http404
        try:
            result = Fibonacci.objects.get(pk=n)
            result.time = datetime.now()
        except DoesNotExist:
            result = str(fib(n))
            result = Fibonacci(n, result, datetime.now())
        result.save()
    return direct_to_template(request, 'base.html', {'result':result.result})

You could use models to get last ‘n’ entities.


Keywords:

© 2017 QuizBucket.org