Check if two unordered sequence are equal

Question:

I’m looking for an easy (and quick) way to determine if two unordered sequence contain the same elements:

For example:

GTTUIP and EGTP 
return [[0,1],[1,2],[2,2],[5,3]]
Asked By: KKK07

||

Answers:

The following comprehensions will do:

s1, s2 = 'GTTUIP', 'EGTP'

i2 = {char: i for i, char in reversed(list(enumerate(s2)))}
# {'P': 3, 'G': 1, 'T': 2, 'E': 0}

[[i, i2[char]] for i, char in enumerate(s1) if char in i2]
# [[0, 1], [1, 2], [2, 2], [5, 3]]

The former creates a lookup mapping from characters to their indexes in the second sequence. The reversed in there is to ensure we map to the index of each char’s first occurrence. The latter builds the final structure by iterating the first sequence and looking up the indexes from the second.

Answered By: user2390182
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.