0

I want to replace my function foo with foo2(non-resursion), but foo2 works incorrect. What's wrong with foo2?

def foo(n, k=0,s=0):
    if k < n:
        for i in xrange(k==0,10):
            foo(n, k+1, 10*s + i)
    else: 
        print s,

def foo2(n):
    s=0
    for k in xrange(n):
        st = s
        for i in xrange(k==0, 10):
            st = 10* st + i
        print st
foo(3)
foo2(3)

Updated

If I replace 10*s + i with s + i**3, How can I rewrite it?

0

1 Answer 1

3

foo prints 10n-1 ~ 10n-1; Iterate xrange(10**(n-1), 10**n).

def foo2(n):
    for s in xrange(10**(n-1), 10**n):
        print s,

Following is a translation of the recursive funciton using stack:

def foo2(n):
    stack = [(0, 0)] # corresponding to (..., k=0, s=0)
    while stack:
        k, s = stack.pop(0)
        if k < n:
            for i in xrange(k==0, 10):
                stack.append((k+1, 10*s + i))
        else:
            print s,

NOTE To implement strictly equivalent iterative version, you should also push iterator (xrange...); consume only one item at a time in a loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.