1

i want to use itertools permutations for strings instead of just letters.

import itertools
lst = list(permutations(("red","blue"),3))
#This returns []

I know i can do something like:

a = list(permutations(range(3),3))
for i in range(len(a)):
a[i] = list(map(lambda x: 'red' if x==0 else 'blue' if x==1 else 'green',a[i]))

EDIT: I want to key in this as my input, and get this as my output

input: ("red","red","blue")

output:
[(’red’, ’red’, ’red’), (’red’, ’red’, ’blue’),\
(’red’, ’blue’, ’red’), (’red’, ’blue’, ’blue’), (’blue’, ’red’, ’red’), \
(’blue’, ’red’, ’blue’), (’blue’, ’blue’, ’red’), (’blue’, ’blue’, ’blue’)]
3
  • 1
    what is your expected output? your original idea looks ok to me, the reason why it's returning [] is because you're asking for length-3 permutations in a list of length-2 -- there aren't any! Commented Jun 9, 2017 at 4:30
  • 2
    It works perfectly fine to permute strings. However, you cannot take three elements from a list of two, in any order. That is why you get the empty list as output. Commented Jun 9, 2017 at 4:31
  • 2
    looks like you want product Commented Jun 9, 2017 at 5:01

2 Answers 2

3

You can try with itertools.product like this:

import itertools
lst = list(set(itertools.product(("red","red","blue"),repeat=3))) # use set to drop duplicates
lst

lst will be:

[('red', 'blue', 'red'),
 ('blue', 'red', 'red'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue'),
 ('blue', 'red', 'blue'),
 ('red', 'blue', 'blue'),
 ('red', 'red', 'blue'),
 ('red', 'red', 'red')]

Update:

import itertools
lst = list(itertools.product(("red","blue"),repeat=3))
lst

output:

[('red', 'red', 'red'),
 ('red', 'red', 'blue'),
 ('red', 'blue', 'red'),
 ('red', 'blue', 'blue'),
 ('blue', 'red', 'red'),
 ('blue', 'red', 'blue'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue')]
Sign up to request clarification or add additional context in comments.

1 Comment

How do i get the same output if my input is just ['red' , 'blue'] and i want the same product?
2

You can do it, also, with combinations from itertools module, like this example:

from itertools import combinations 
final = list(set(combinations(("red","red","blue")*3, 3)))

print(final)

Output:

[('red', 'blue', 'red'),
 ('blue', 'red', 'red'),
 ('blue', 'blue', 'red'),
 ('blue', 'blue', 'blue'),
 ('blue', 'red', 'blue'),
 ('red', 'blue', 'blue'),
 ('red', 'red', 'blue'),
 ('red', 'red', 'red')]

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.