Simple recursive function

This is a fairly simple task, which I feel is how I should do it, but only for the life of me, I canโ€™t understand.

I am 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 is not very useful.

the code does not work:

 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) 
+4
source share
4 answers

I'm not going to write this because it will defeat the goal, 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 something I can forget that Python is not made for this kind of thing. It needs smoothing.

The reason it doesn't work is because returning in the outer loop will end all this on the first call.

What you really want to do in your case looks 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 chars this will result in LOT ( n! ) Lines. As already stated, this is not the best way to get this result in Python, but it is useful to learn about recursion.

+4
source

You do not 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 
+5
source

With @David Heffernan's answer, you also don't need to write your own combination functions if you have itertools :

 from itertools import combinations_with_replacement for i in combinations_with_replacement("0123",4): print(i) 
+2
source
 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() 

Denial of responsibility:

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

+1
source

All Articles