comparing lists
mark mceahern
marknews at mceahern.com
Fri May 10 08:57:15 EDT 2002
[Alex Martelli]
> Here's a O(N) solution:
>
> def compare_via_dicts(L, M):
> def makebag(L):
> dL = {}
> for x in L:
> x = x.lower()
> dL[x] = 1 + dL.get(x, 0)
> return makebag(L) == makebag(M)
>
> Note we use a 'bag' (x -> #instances of x in list), not a set, to take care
> of repetitions so ['a', 'A'] will not appear equal to ['a', 'A', 'A'], &c.
Checking the lengths of the lists would also work to prevent ['a'] ==
['a', 'a']. Thank you for this code.
Cheers,
// mark
More information about the Python-list
mailing list