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?

2 Answers 2

6
>>> 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')]
Sign up to request clarification or add additional context in comments.

2 Comments

That's what I call "batteries included" :-)
@Glenn: you forgot convert each result to list.
1
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);

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.