mrani
mrani

Reputation: 21

Enumerating all possible scenarios

I am trying to find all of the possible combinations for a set. Suppose I have 2 vehicles (A and B) and I want to use them by sending them and then return. Send and return are two distinct actions, and I want to enumerate all of the possible sequences of sending and returning this vehicle. Thus the set is [ A, A, B, B]. I use this code to enumerate:

from itertools import permutations 

a = permutations(['A', 'A', 'B', 'B']) 
   
# Print the permutations
seq = []
for i in list(a):
    seq.append(i)
seq = list(set(seq)) # remove duplicates

The result is as follows:

('A', 'B', 'B', 'A')
('A', 'B', 'A', 'B')
('A', 'A', 'B', 'B')
('B', 'A', 'B', 'A')
('B', 'B', 'A', 'A')
('B', 'A', 'A', 'B')

Suppose my assumption is the two vehicles identical. Thus, it doesn't matter which one is on the first order (i.e. ABBA is the same as BAAB). Here's what I expect the result is:

 ('A', 'B', 'B', 'A')
 ('A', 'B', 'A', 'B')
 ('A', 'A', 'B', 'B')

I can do this easily by removing the last three elements. However, I encounter a problem when I try to do the same thing for three vehicles ( a = permutations(['A', 'A', 'B', 'B', 'C', 'C']). How to ensure that the result already considers the three identical vehicles?

Upvotes: 0

Views: 351

Answers (2)

VishwasR Vibhu
VishwasR Vibhu

Reputation: 119

from itertools import permutations 

a = permutations(['A', 'A', 'B', 'B']) 
   
seq = []
for i in list(a):
    if i[0]=='A':
        seq.append(i)
seq = list(set(seq))
print(seq)

Try this, I think this should do

Upvotes: 1

Jiří Baum
Jiří Baum

Reputation: 6930

One way would be to generate all the combinations, then filter for only those where the first mention of each vehicle is in alphabetical order.

In recent versions of Python, dict retains first-insertion order, so we can use it to determine the first mention; something like:

from itertools import permutations 

seq = set()
for i in permutations(['A', 'A', 'B', 'B']):
    first_mentions = {car: None for car in i}.keys()
    if list(first_mentions) == sorted(first_mentions):
        seq.add(i)

(This works in practice since Python 3.5, and officially since Python 3.7)

Upvotes: 1

Related Questions