views:

72

answers:

2

I have 2 variables - a and b. I need to fill up k places using these variables. So if k = 3 output should be

[a,a,a], [a,a,b] , [a,b,a], [b,a,a], [a,b,b], [b,a,b], [b,b,a] and [b,b,b]

Input - k

Output - All the combinations

How do I code this in Python? Can itertools be of any help here?

+6  A: 
>>> import itertools
>>> list(itertools.product('ab', repeat=3))
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'b', 'a'), ('b', 'b', 'b')]
SilentGhost
`product([a, b], repeat=k)`
Glenn Maynard
That's what I call "batteries included" :-)
tsimbalar
@Glenn: you forgot convert each result to list.
SilentGhost
@SilentGhost: It's your answer, I'm just pointing out the missing pieces...
Glenn Maynard
+1  A: 
def genPerm(varslist, pos,resultLen, result, resultsList)
   if pos>resultLen:
       return;
   for e in varslist:
       if pos==resultLen:
           resultsList.append(result + [e]);
       else
           genPerm(varsList, pos+1, resultLen, result + [e], resultsList);

Call with:

genPerm([a,b], 0, resLength, [], resultsList);
Andy