0

I have array-of-arrays like the ones below :

[[0, 3], [0, 4, 1, 5], [0, 2]]
[[0, 4, 1, 5], [0, 3], [0, 2]]
[[0, 2], [0, 4, 1, 5], [0, 3]]

[[0, 4, 1, 5, 3], [0, 2]]
[[0, 4, 1, 5, 3, 2]]

If you look at the first 3 examples they are the same array, just ordered differently.

At any time I have to compare two such AoA and figure out if they are the same.

What is the fastest way to do that ? The arrays themselves are small, but I have to do this check very often.

2

2 Answers 2

1

You can convert the sub-lists to tuples(immutable) using map(tuple,list)) + sort the main list (which sorts the tuples based on the integer element ordering).

l1 = [[0, 3], [0, 4, 1, 5], [0, 2]]
l2 = [[0, 4, 1, 5], [0, 3], [0, 2]]
l3 = [[0, 2], [0, 4, 1, 5], [0, 3]]
print (sorted(map(tuple,l1)) == sorted(map(tuple,l2)))
#True
print(sorted(map(tuple,l2)) == sorted(map(tuple,l3)))
#True
print (sorted(map(tuple,l3)) == sorted(map(tuple,l1)))
#True

l4 = [[0, 4, 1, 5, 3], [0, 2]]
l5 = [[0, 4, 1, 5, 3, 2]]
sorted(map(tuple,l4)) == sorted(map(tuple,l5))
#False
Sign up to request clarification or add additional context in comments.

Comments

0

One way is to flatten the two arrays and compare. Like this:

list1 = [[0, 3], [0, 4, 1, 5], [0, 2]]

list2 = [[0, 4, 1, 5], [0, 3], [0, 2]]

def flat(ls): return [val for sublist in ls for val in sublist]

set(flat(list1)) == set(flat(list2))

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.