开发者

simple recursive function

This is a pretty simple task i feel like i should be able to do- but just for the life of me, cant figure out.

I'm trying to write a recursive function to replicate the following:

chars = '0123456789abcdef'

for a in chars:
    for b in chars:
        for c in chars:
            for d in chars:
                print a+b+c+d

searching for an example hasn't proven very fruitful.

code thats not worki开发者_Go百科ng:

chars = 'ABCDEF'

def resu(chars, depth = len(chars)):
    for char in chars:
        if depth == 0:
           return char
        return char + resu(chars, depth - 1)

print resu(chars)


You don't need recursion if you have itertools:

from itertools import product
for a,b,c,d in product('abc', repeat=4):
    print a+b+c+d


I'm not going to write it out, because that would defeat the purpose, but here's a hint: Think about the conditions under which you stop recursing. Here's the key bit:

for char in chars:
    return char + recurse(chars, depth - 1)

Edit: This is what I get for forgetting that Python isn't made for this sort of thing. It needs a flatten.

The reason it's not working is that return in the outermost loop will end the whole thing the first time it's called.

What you actually want to do in your case is more like this:

def resu(chars, depth = None, prefix=''):
    if depth is None:
            depth = len(chars)
    if depth == 0:
            print prefix
            return
    for ch in chars:
            resu(chars, depth - 1, ch + prefix)

Note that for even moderate length chars, this will produce a LOT (n!) of lines. As has been pointed out, this is not the best way to get this result in Python, but it is useful to learn about recursion.


With @David Heffernan's answer, you also don't need writing your own combinations function if you have itertools:

from itertools import combinations_with_replacement
for i in combinations_with_replacement("0123",4): 
    print(i)


chars = '0123456789abcdef'

def get_combinations(cur_combo=''):
    for char in chars:
        new_combo = cur_combo+char
        if len(new_combo) == 4:
            print new_combo
        else:
            get_combinations(new_combo)

get_combinations()

Disclaimer:

May not be a good example, but it is recursive and gives the correct result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜