Skip to content

Instantly share code, notes, and snippets.

@harrybiddle
Last active December 17, 2019 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrybiddle/7261582b6d90e6d74323904b57ff4ded to your computer and use it in GitHub Desktop.
Save harrybiddle/7261582b6d90e6d74323904b57ff4ded to your computer and use it in GitHub Desktop.
Equality of nested iterables
from collections import Counter
def iterables_equal(a, b):
"""
Returns true if and only if two iterables of hashable objects are equal up to their
order. Iterables can be nested.
For example:
iterable_equality([1, 2], [2, 1]) # True
iterable_equality([1], [1, 1]) # False
"""
def isiterable(obj: Any) -> bool:
try:
iter(obj)
return not isinstance(obj, str)
except TypeError:
return False
def counts(c):
if isiterable(c):
return tuple(Counter([counts(d) for d in c]).items())
return c
if isiterable(a) and isiterable(b):
return set(counts(a)) == set(counts(b))
return a == b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment