Permutations without Recursion

I remember when I was in college, a very tricky quiz was to convert recursive code to a non-recursive one. I have always found it very challenging.

Permutation can easily be solved with recursion. So I tried to solve it without recursion. It was a fun exercise.

alpha = 'xyz'

def main():
    n = list(alpha)
    while n:
        print n
        n = next(n)


def next(str):
    str.pop()
    # loop to find a upgradable tail
    while str:
        tail = str[-1]
        # search for an upgrade to the tail
        new_tail = [i for i in alpha if i > tail and i not in str]
        if not new_tail:
            str.pop()
            continue
        str[-1] = new_tail[0]
        # fill the rest
        return str + [i for i in alpha if i not in str]