Silver
Silver

Reputation: 141

Python Itertools permutations with strings

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’)]

Upvotes: 1

Views: 2286

Answers (2)

Tiny.D
Tiny.D

Reputation: 6556

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')]

Upvotes: 3

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

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')]

Upvotes: 2

Related Questions