Skip to content

Instantly share code, notes, and snippets.

@jdittrich
Last active June 18, 2017 10:25
Show Gist options
  • Save jdittrich/b87e14ea06441df96dbdc80e5dc8f8bb to your computer and use it in GitHub Desktop.
Save jdittrich/b87e14ea06441df96dbdc80e5dc8f8bb to your computer and use it in GitHub Desktop.
creates a tree. Each item (the things with "name") can be in multiple paths. Imagine it like a tree for a media collection with nested tags – every photo can have multiple (nested) tags
'''
The function call behaviour seems to be identical to the javascript version; I could not find any differences
However, the resulting tree is not identical, the javascript version "reuses" the paths,
whereas the python one seems to create a new path on every occasion.
'''
#following adapted from https://stackoverflow.com/a/44185784/263398 and ported to Python
from functools import reduce
data2 = [{
"name": "Children C1",
"paths": [["A", "B", "C"],["A", "B"]]
}, {
"name": "Children C2",
"paths": [["A", "B", "C"]]
}, {
"name": "Children C3",
"paths": [["A", "B", "C"]]
}, {
"name": "Children B1",
"paths": [["A", "B"],["C"]]
}, {
"name": "Children B2",
"paths": [["A", "B"],["D", "E"],["X"]]
}, {
"name": "Children A1",
"paths": [["A"],["B"]]
}, {
"name": "Children E1",
"paths": [["D", "E"],["A", "B"]]
}];
def constructTree(commentsArray):
result = []
initialValue = {
"_":result
}
def reducerfunction(accumulator,pathpart):
print("pathpart", pathpart)
if not pathpart in accumulator:
print("IF!")
accumulator[pathpart] = {
"_":[]
}
accumulator["_"].append({
"name":pathpart,
"children":accumulator[pathpart]["_"]
})
print("accumulator")
return accumulator[pathpart]
for comment in commentsArray:
for path in comment["paths"]:
print(path)
reduce(reducerfunction ,path+[comment["name"]],initialValue)
return result
tree = constructTree(data2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment