How do I check if all the elements of a nested list tree are identical?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:53 Accepted answer (Score 3)
01:14 Answer 2 (Score 1)
02:31 Thank you
--
Full question
https://stackoverflow.com/questions/6412...
Answer 1 links:
[Here's]: https://repl.it/repls/MediumpurpleExciti...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #recursion
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:53 Accepted answer (Score 3)
01:14 Answer 2 (Score 1)
02:31 Thank you
--
Full question
https://stackoverflow.com/questions/6412...
Answer 1 links:
[Here's]: https://repl.it/repls/MediumpurpleExciti...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #recursion
#avk47
ACCEPTED ANSWER
Score 3
You can recursively convert the list to a set of items and return true if the length of the overall set is 1:
def allsametree(tree):
def to_set(tree):
if isinstance(tree, list):
return {item for obj in tree for item in to_set(obj)}
return {tree}
return len(to_set(tree)) == 1
ANSWER 2
Score 1
Another way to do it. Split it into two operations a flatten and a check that all the values are the same.
The flatten will convert a nested iterable into one of a single dimension. So [1, [[[[[2]]]]]] becomes [1,2].
Then read the first value and cycle through the rest to check they are the same as it.
Here's the code
from collections.abc import Iterable
def flatten(iterable):
for i in iterable:
if isinstance(i, Iterable):
yield from flatten(i)
else:
yield i
def allsametree(tree):
flat = flatten(tree)
iterator = iter(flat)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == rest for rest in iterator)
This will work for any iterable not just lists and because it uses lazy evaluation, it will stop when it finds two values that are not equal. This saves you from doing unnecessary work. It also avoid instantiating temporary collections (lists, sets etc.) being constructed on each recursive call.
Here's a few test inputs.