-3

I've tried this code but it does not work and results with 0. I've known the recursive one, but I'm trying to do it using for loop.

def minsteps(n):
    memo =[0]*(n+1)
    memo[0] = 0
    memo[1] = 0
    for i in range(2,n,1):
        r = 1+memo[i-1]
        if i%2 == 0:
            r = min(r, 1+memo[i//2])
        elif i%3 == 0:
            r = min(r, 1+memo[i//3])
        memo[i] = r
    return memo[n]

This code is to provide a minimum steps requires for certain number to be 1 undergoing processes of minus 1, divide 2 and divide 3. For example: 6->2->1 [3] or 6->3->1 [3] or 6->5->4->2->4 [5]

Thus, the minimum steps is 3.

Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
J.Doe
  • 71
  • 2
  • 9
  • 6
    Could you please explain what your code is supposed to do. Provide a sample input and expected output. It would also help if you provided any insight in where you believe the problem to be as well. Would be worth your time to also read [this](http://stackoverflow.com/help/mcve). – idjaw Nov 02 '15 at 14:52
  • 3
    I'm not sure what your function does (or is supposed to do) but for sure due to `range(2,n,1)` you modify items up to `n-1` (that's the last element of the range) while you take `memo[n]` at the end. I.e. use `range(2, n+1)`? – freakish Nov 02 '15 at 14:55
  • One thing which is also missing in your script are `print()` commands, writing intermediate information. – Dominique Nov 02 '15 at 14:57

2 Answers2

1

Your code contains an "off-by-one error". Your loop is controlled by range(2,n,1), that is, the numbers from 2 to n-1, inclusive, so you intiialize the list values memo[2] through memo[n-1], inclusive. But you return your result from memo[n], which still has its initial 0 value.

You can fix that error by using this for statement:

 for i in range(2,n+1,1):

Alternatively, here is another solution:

import collections

def minsteps(n):
    memo = collections.defaultdict(lambda: n+1)
    memo[1] = 0
    for i in range(1, n+1):
        memo[i+1] = min(memo[i+1], memo[i]+1)
        memo[i*2] = min(memo[i*2], memo[i]+1)
        memo[i*3] = min(memo[i*3], memo[i]+1)
    return memo[n]

for i in range(10):
    print i, minsteps(i)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
-2

Try this one.

def minsteps1(n):
    memo = [0]*(n+1)
    def loop(n):
        if n>1:
            if memo[n]!=0:
                return memo[n]
            else:
                memo[n] = 1 + loop(n-1)
                if n%2 == 0:
                    memo[n] = min(memo[n], 1+loop(n//2))
                if n%3 == 0:
                    memo[n] = min(memo[n], 1+loop(n//3))
                return memo[n]
        else:
            return 0
    return loop(n)
Buksy
  • 11,571
  • 9
  • 62
  • 69
MinJi
  • 1