Sunday, July 7, 2013

Rosalind day 4

I'm not spending much time on this.  I've worked through 13 of the "problems".  I'm definitely learning python.  Today's problems were related to Fibonacci numbers.  I'm pretty sure I'll have to use this tomorrow in one of the two Coursera classes I'm currently taking.  The Rosalind problems I've solved so far are pretty simple.  I've reviewed some of the web pages concerning dynamic programming in python.  The example at Math ∩ Programming deals with Fibonacci numbers.  I'm not ready to create a complex dynamic solution.  I ended up with something like this:

def fib(n):
   fibValues = [0,1]
   for i in range(2,n+1):
      fibValues.append(fibValues[i-1] + fibValues[i-2])
   return fibValues[n]


rather than something like this:

def memoize(f):
   cache = {}

   def memoizedFunction(*args):
      if args not in cache:
         cache[args] = f(*args)
      return cache[args]

   memoizedFunction.cache = cache
   return memoizedFunction


@memoize
def fib(n):
   if n <= 2:
      return 1
   else:
      return fib(n-1) + fib(n-2)


It doesn't matter that the latter is a more elegant solution.  I'm just glad my solution was nearly identical to other people's solutions.

No comments:

Post a Comment