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.

sten
  • 7,028
  • 9
  • 41
  • 63

2 Answers2

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
Transhuman
  • 3,527
  • 1
  • 9
  • 15
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))

shreyy
  • 5
  • 4