Despite the well-known calculation formula in O(1) , it fails for large numbers (i.e. 100).
I would do the following for fibonacci:
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
And for the last numbers I would create a model.
from django.db import models class Fibonacci(models.Model): parameter = models.IntegerField(primary_key=True) result = models.CharField(max_length=200) time = models.DateTimeField()
And for presentation, I would just do this:
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})
Using models to retrieve the last n records is pretty simple.
razpeitia
source share