Skip to content

Instantly share code, notes, and snippets.

@Mark24Code
Forked from upsuper/tree.md
Created May 11, 2016 08:37
Show Gist options
  • Select an option

  • Save Mark24Code/8f3f2011e0bdb8843b3d6da21f022398 to your computer and use it in GitHub Desktop.

Select an option

Save Mark24Code/8f3f2011e0bdb8843b3d6da21f022398 to your computer and use it in GitHub Desktop.

Revisions

  1. @upsuper upsuper revised this gist Apr 28, 2012. 1 changed file with 24 additions and 24 deletions.
    48 changes: 24 additions & 24 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -1,37 +1,37 @@
    # One-line Tree in Python
    # 一行 Python 实现树

    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:
    使用 Python 内置的 [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict),我们可以很容易的定义一个树形数据结构:

    ```python
    def tree(): return defaultdict(tree)
    ```

    That's it!
    就是这样!

    It simply says that a tree is a dict whose default values are trees.
    简单地来说,一颗树就是一个默认值是其子树的字典。

    (If you're following along at home, make sure to `from collections import defaultdict`)
    (使用之前需要确认已经 `from collections import defaultdict`)

    (Also: Hacker News reader @zbuc points out that this is called [autovivification](https://en.wikipedia.org/wiki/Autovivification). Cool!)
    (: Hacker News 读者 @zbuc 指出这种结构被称为 [autovivification](https://en.wikipedia.org/wiki/Autovivification)。 太酷了!)

    ## Examples
    ### JSON-esque
    Now we can create JSON-esque nested dictionaries without explicitly creating sub-dictionaries—they magically come into existence as we reference them:
    ## 例子
    ### JSON 风格
    现在我们可以创建一个 JSON 风格的嵌套字典,我们不需要显式地创建子字典——当我们需要时,它们神奇地自动出现了:

    ```python
    users = tree()
    users['harold']['username'] = 'hrldcpr'
    users['handler']['username'] = 'matthandlersux'
    ```

    We can print this as json with `print(json.dumps(users))` and we get the expected:
    我们可以将这些用 `print(json.dumps(users))` 以 JSON 的形式输出,于是我们得到:

    ```python
    ```javascript
    {"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
    ```

    ### Without assignment
    We can even create structure with no assignment at all:
    ### 不需要赋值
    我们甚至可以不需要任何赋值就可以创建整个树结构:

    ```python
    taxonomy = tree()
    @@ -44,13 +44,13 @@ taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato']
    taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']
    ```

    We'll prettyprint this time, which requires us to convert to standard dicts first:
    我们接下来将漂亮地输出他们,不过需要先将他们转换为标准的字典:

    ```python
    def dicts(t): return {k: dicts(t[k]) for k in t}
    ```

    Now we can prettyprint the structure with `pprint(dicts(taxonomy))`:
    现在我们用 `pprint(dicts(taxonomy))` 来漂亮地输出结构:

    ```python
    {'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
    @@ -62,26 +62,26 @@ Now we can prettyprint the structure with `pprint(dicts(taxonomy))`:
    'tomato': {}}}}}}
    ```

    So the substructures we referenced now exist as dicts, with empty dicts at the leaves.
    于是我们引用到的子结构以字典的形式存在,空字典即代表了叶子。

    ### Iteration
    This tree can be fun to iteratively walk through, again because structure comes into being simply by referring to it.
    ### 迭代
    这棵树可以很欢乐地被迭代处理,同样因为只要简单地引用一个结构它就会出现。

    For example, suppose we are parsing a list of new animals to add to our taxonomy above, so we want to call a function like:
    举例来说,假设我们想要解析一个新动物的列表,将它们加入我们上面的 taxonomy,我们只要这样调用一个函数:
    ```python
    add(taxonomy,
    'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
    ```

    We can implement this simply as:
    我们可以简单地这样实现它:

    ```python
    def add(t, keys):
    for key in keys:
    t = t[key]
    ```

    Again we are never assigning to the dictionary, but just by referencing the keys we have created our new structure:
    再一次,我们完全没有对字典使用任何赋值,仅仅是引用了这些键,我们便创建了我们新的结构:

    ```python
    {'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
    @@ -94,7 +94,7 @@ Again we are never assigning to the dictionary, but just by referencing the keys
    'tomato': {}}}}}}
    ```

    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above).
    ## 结论
    这也许并不特别实用,而且也出现了一些令人困惑的代码 (见上面的 `add()`)。

    But if you like Python then I hope this was fun to think about or worthwhile to understand.
    不过如果你喜欢 Python,我希望思考这些会让你觉得有趣,或者值得去理解。
  2. @hrldcpr hrldcpr revised this gist Apr 23, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -12,7 +12,7 @@ It simply says that a tree is a dict whose default values are trees.

    (If you're following along at home, make sure to `from collections import defaultdict`)

    Edit: Hacker News reader @zbuc points out that this is called [autovivification](https://en.wikipedia.org/wiki/Autovivification). Cool!
    (Also: Hacker News reader @zbuc points out that this is called [autovivification](https://en.wikipedia.org/wiki/Autovivification). Cool!)

    ## Examples
    ### JSON-esque
  3. @hrldcpr hrldcpr revised this gist Apr 23, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -12,6 +12,7 @@ It simply says that a tree is a dict whose default values are trees.

    (If you're following along at home, make sure to `from collections import defaultdict`)

    Edit: Hacker News reader @zbuc points out that this is called [autovivification](https://en.wikipedia.org/wiki/Autovivification). Cool!

    ## Examples
    ### JSON-esque
  4. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -49,8 +49,6 @@ We'll prettyprint this time, which requires us to convert to standard dicts firs
    def dicts(t): return {k: dicts(t[k]) for k in t}
    ```

    (Compare this to the definition of `tree()` above, as it is in some sense its inverse.)

    Now we can prettyprint the structure with `pprint(dicts(taxonomy))`:

    ```python
  5. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -49,7 +49,7 @@ We'll prettyprint this time, which requires us to convert to standard dicts firs
    def dicts(t): return {k: dicts(t[k]) for k in t}
    ```

    (Compare this to the definition of `tree` above, as it is in some sense its inverse.)
    (Compare this to the definition of `tree()` above, as it is in some sense its inverse.)

    Now we can prettyprint the structure with `pprint(dicts(taxonomy))`:

  6. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -49,7 +49,7 @@ We'll prettyprint this time, which requires us to convert to standard dicts firs
    def dicts(t): return {k: dicts(t[k]) for k in t}
    ```

    (Note how similar this is to the definition of `tree` above, as it is in some sense the "inverse".)
    (Compare this to the definition of `tree` above, as it is in some sense its inverse.)

    Now we can prettyprint the structure with `pprint(dicts(taxonomy))`:

  7. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -49,7 +49,9 @@ We'll prettyprint this time, which requires us to convert to standard dicts firs
    def dicts(t): return {k: dicts(t[k]) for k in t}
    ```

    Now we can print the structure with `pprint(dicts(taxonomy))`:
    (Note how similar this is to the definition of `tree` above, as it is in some sense the "inverse".)

    Now we can prettyprint the structure with `pprint(dicts(taxonomy))`:

    ```python
    {'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
  8. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -46,7 +46,7 @@ taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']
    We'll prettyprint this time, which requires us to convert to standard dicts first:

    ```python
    def dicts(t): return {k: dicts(v) for k,v in t.items()}
    def dicts(t): return {k: dicts(t[k]) for k in t}
    ```

    Now we can print the structure with `pprint(dicts(taxonomy))`:
  9. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -8,7 +8,7 @@ def tree(): return defaultdict(tree)

    That's it!

    It simply says that a tree is a dict whose default values are trees. Think about it.
    It simply says that a tree is a dict whose default values are trees.

    (If you're following along at home, make sure to `from collections import defaultdict`)

  10. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    ## One-line Tree in Python
    # One-line Tree in Python

    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
  11. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 3 deletions.
    4 changes: 1 addition & 3 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,4 @@
    # One-line Tree in Python

    ## Definition
    ## One-line Tree in Python
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
  12. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    # One-line Tree in Python

    ## Definition
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
  13. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -96,4 +96,4 @@ Again we are never assigning to the dictionary, but just by referencing the keys
    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above).

    But if you like Python then it might be fun to think about and worthwhile to understand.
    But if you like Python then I hope this was fun to think about or worthwhile to understand.
  14. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -13,8 +13,6 @@ It simply says that a tree is a dict whose default values are trees. Think about
    (If you're following along at home, make sure to `from collections import defaultdict`)




    ## Examples
    ### JSON-esque
    Now we can create JSON-esque nested dictionaries without explicitly creating sub-dictionaries—they magically come into existence as we reference them:
  15. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -3,9 +3,7 @@
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
    ####################################
    def tree(): return defaultdict(tree)
    ####################################
    ```

    That's it!
    @@ -15,6 +13,8 @@ It simply says that a tree is a dict whose default values are trees. Think about
    (If you're following along at home, make sure to `from collections import defaultdict`)




    ## Examples
    ### JSON-esque
    Now we can create JSON-esque nested dictionaries without explicitly creating sub-dictionaries—they magically come into existence as we reference them:
  16. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,9 @@
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
    ####################################
    def tree(): return defaultdict(tree)
    ####################################
    ```

    That's it!
    @@ -96,4 +98,4 @@ Again we are never assigning to the dictionary, but just by referencing the keys
    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above).

    But if you like Python then it might be fun to think about and worthwhile to understand.
    But if you like Python then it might be fun to think about and worthwhile to understand.
  17. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,5 @@
    # One-line Tree in Python

    ## Definition
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
  18. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -7,7 +7,9 @@ Using Python's built-in [defaultdict](http://docs.python.org/library/collections
    def tree(): return defaultdict(tree)
    ```

    That's it! Think about it.
    That's it!

    It simply says that a tree is a dict whose default values are trees. Think about it.

    (If you're following along at home, make sure to `from collections import defaultdict`)

  19. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -93,6 +93,6 @@ Again we are never assigning to the dictionary, but just by referencing the keys
    ```

    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above),
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above).

    but if you like Python then it might be fun to think about and worthwhile to understand.
    But if you like Python then it might be fun to think about and worthwhile to understand.
  20. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -94,4 +94,5 @@ Again we are never assigning to the dictionary, but just by referencing the keys

    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above),

    but if you like Python then it might be fun to think about and worthwhile to understand.
  21. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -94,4 +94,4 @@ Again we are never assigning to the dictionary, but just by referencing the keys

    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above),
    but if you like Python then hopefully it's fun to think about and interesting to understand.
    but if you like Python then it might be fun to think about and worthwhile to understand.
  22. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -91,3 +91,7 @@ Again we are never assigning to the dictionary, but just by referencing the keys
    'Solanaceae': {'Solanum': {'potato': {},
    'tomato': {}}}}}}
    ```

    ## Conclusion
    This probably isn't very useful, and it makes for some perplexing code (see `add()` above),
    but if you like Python then hopefully it's fun to think about and interesting to understand.
  23. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -67,14 +67,14 @@ This tree can be fun to iteratively walk through, again because structure comes

    For example, suppose we are parsing a list of new animals to add to our taxonomy above, so we want to call a function like:
    ```python
    insert(taxonomy,
    'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
    add(taxonomy,
    'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
    ```

    We can implement this simply as:

    ```python
    def insert(t, keys):
    def add(t, keys):
    for key in keys:
    t = t[key]
    ```
  24. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -67,7 +67,8 @@ This tree can be fun to iteratively walk through, again because structure comes

    For example, suppose we are parsing a list of new animals to add to our taxonomy above, so we want to call a function like:
    ```python
    insert(taxonomy, 'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
    insert(taxonomy,
    'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
    ```

    We can implement this simply as:
  25. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    # One-line Tree in Python

    ## Definition
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree datastructure:
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree data structure:

    ```python
    def tree(): return defaultdict(tree)
  26. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    # One-line Tree in Python

    ## Definition
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree structure:
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree datastructure:

    ```python
    def tree(): return defaultdict(tree)
  27. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    # One-line Tree Datastructure in Python
    # One-line Tree in Python

    ## Definition
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree structure:
  28. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion tree.md
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    # One-line Tree Datastructure in Python

    ## Definition
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a versatile tree structure:
    Using Python's built-in [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) we can easily define a tree structure:

    ```python
    def tree(): return defaultdict(tree)
  29. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 32 additions and 2 deletions.
    34 changes: 32 additions & 2 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -13,6 +13,7 @@ That's it! Think about it.


    ## Examples
    ### JSON-esque
    Now we can create JSON-esque nested dictionaries without explicitly creating sub-dictionaries—they magically come into existence as we reference them:

    ```python
    @@ -27,7 +28,7 @@ We can print this as json with `print(json.dumps(users))` and we get the expecte
    {"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
    ```


    ### Without assignment
    We can even create structure with no assignment at all:

    ```python
    @@ -59,4 +60,33 @@ Now we can print the structure with `pprint(dicts(taxonomy))`:
    'tomato': {}}}}}}
    ```

    So the substructures we referenced now exist as dicts, with empty dicts at the leaves.
    So the substructures we referenced now exist as dicts, with empty dicts at the leaves.

    ### Iteration
    This tree can be fun to iteratively walk through, again because structure comes into being simply by referring to it.

    For example, suppose we are parsing a list of new animals to add to our taxonomy above, so we want to call a function like:
    ```python
    insert(taxonomy, 'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
    ```

    We can implement this simply as:

    ```python
    def insert(t, keys):
    for key in keys:
    t = t[key]
    ```

    Again we are never assigning to the dictionary, but just by referencing the keys we have created our new structure:

    ```python
    {'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
    'dog': {}}},
    'Felidae': {'Felis': {'cat': {}},
    'Panthera': {'lion': {}}}},
    'Cetacea': {'Balaenopteridae': {'Balaenoptera': {'blue whale': {}}}}}}},
    'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}},
    'Solanaceae': {'Solanum': {'potato': {},
    'tomato': {}}}}}}
    ```
  30. @hrldcpr hrldcpr revised this gist Apr 20, 2012. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions tree.md
    Original file line number Diff line number Diff line change
    @@ -11,6 +11,7 @@ That's it! Think about it.

    (If you're following along at home, make sure to `from collections import defaultdict`)


    ## Examples
    Now we can create JSON-esque nested dictionaries without explicitly creating sub-dictionaries—they magically come into existence as we reference them: