Drzewo w pythonie

20 November 2013, 21:25

"Jednolinijkowe" drzewo w pythonie. Całkiem ciekawy kawałek kodu:

from collections import defaultdict

def Tree():
    return defaultdict(Tree)

Działa np. tak:

>>> t = Tree()
>>> t["a"]["b"] = 2
>>> t["a"]["c"] = 3
>>> t["a"][4]
defaultdict(<function Tree at 0x456e9b0>, {})
>>> json.dumps(t)
'{"a": {"c": 3, "b": 2, "4": {}}}'

Więcej na temat:

This entry was tagged as python programowanie