0

I have implemented fibonacci series using recursion:

def fibonacci(n): 
    if n==0: 
        return 0
    elif n==1: 
        return 1
    else: 
        return fibonacci(n-1) + fibonacci(n-2)

I have also implemented it using dynamic programming:

def fibonacci(n): 
    result = [0, 1]

    if n > 1:
        for i in range(2, n+1):
            result.append(result[i-1] + result[i-2])
    return result[n]

I want to implement it using greedy approach. I am unable to think of it in greedy terms. Please provide a greedy approach for this problem.

  • 6
    I don't think the greedy paradigm fits to this problem very well. What would the locally, but not necessarily globally, optimal subsolutions be? – timgeb Oct 18 '18 at 08:02
  • The *dynamic programming* approach can be improved to take *constant* memory, you only need to store the "last two" values, not a list of all values. – Willem Van Onsem Oct 18 '18 at 08:10
  • FWIW, due to the double recursion, your 1st solution is extremely slow for even modest `n`, unless you use memoization, eg `functools.lru_cache`. As other have said, a greedy algorithm isn't applicable here. Why not do something more practical, eg use the fibo(2n) & fibo(2n-1) formulas [here](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form). Those formulas are slowish for small `n`, but if implemented properly, they are very impressive for large `n`. – PM 2Ring Oct 18 '18 at 08:16

1 Answers1

0

I didn't understand what you wanted to say by saying the word 'greedy'. But these are ways:

Example 1: Using looping technique

 def fib(n):
     a,b = 1,1
     for i in range(n-1):
      a,b = b,a+b
     return a
    print fib(5)

Example 2: Using recursion

def fibR(n):
 if n==1 or n==2:
  return 1
 return fibR(n-1)+fibR(n-2)
print fibR(5)

Example 3: Using generators

a,b = 0,1
def fibI():
 global a,b
 while True:
  a,b = b, a+b
  yield a
f=fibI()
f.next()
f.next()
f.next()
f.next()
print f.next()

Example 4: Using memoization

def memoize(fn, arg):
 memo = {}
 if arg not in memo:
  memo[arg] = fn(arg)
  return memo[arg]

fib() as written in example 1.

fibm = memoize(fib,5)
print fibm

Example 5: Using memoization as the decorator

class Memoize:
 def __init__(self, fn):
  self.fn = fn
  self.memo = {}
 def __call__(self, arg):
  if arg not in self.memo:
   self.memo[arg] = self.fn(arg)
   return self.memo[arg]

@Memoize
def fib(n):
 a,b = 1,1
 for i in range(n-1):
  a,b = b,a+b
 return a
print fib(5)
Rarblack
  • 4,559
  • 4
  • 22
  • 33
  • 2
    Your code is mostly fine, but in general it's not a good idea to answer questions that you don't understand. You can read about [greedy algorithms](https://en.wikipedia.org/wiki/Greedy_algorithm) on Wikipedia. – PM 2Ring Oct 18 '18 at 08:21
  • 5
    You clearly put in some effort creating all these solutions, but it's not answering the question. – timgeb Oct 18 '18 at 08:36