Search code examples
pythonarrayscomparisonarrayofarrays

Fastest way to compare Array-of-array?


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.


Solution

  • 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