Last active
December 17, 2019 20:44
-
-
Save harrybiddle/7261582b6d90e6d74323904b57ff4ded to your computer and use it in GitHub Desktop.
Equality of nested iterables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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