A tutorial that demonstrates numerical data structures using Python
- 2020-05-05 11:27:21
- OfStack
You can easily define a tree's data structure using Python's built-in defaultdict method.
Simply put, a tree can also be a dictionary data structure
def tree(): return defaultdict(tree)
That's all, just one line of code.
If you continue with the following code, you need to introduce
first
from collections import defaultdict
instance
JSON-esque
Now we create an JSON-esque nested dictionary without explicitly creating a subdictionary:
users = tree()
users['harold']['username'] = 'hrldcpr'
users['handler']['username'] = 'matthandlersux'
Then you can go through <
code
>
print(json.dumps(users))
<
/code
>
To print JSON data, the result is:
{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
does not require an
assignment
We do not need to assign a value to create a structure:
taxonomy = tree()
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Felis']['cat']
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Panthera']['lion']
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['dog']
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['coyote']
taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['tomato']
taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato']
taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']
To print good information, turn it into a standard dictionary object:
def dicts(t): return {k: dicts(t[k]) for k in t}
You can now print pprint(dicts(taxonomy)) :
{'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
'dog': {}}},
'Felidae': {'Felis': {'cat': {}},
'Panthera': {'lion': {}}}}}}},
'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}},
'Solanaceae': {'Solanum': {'potato': {},
'tomato': {}}}}}}
The substructure is also treated as a dictionary object, while the leaf node is an empty dictionary object
iteration
There are interesting ways to iterate over the tree.
For example, if we parse a list of animals and add them to the taxonomy we defined earlier, we can use the following code:
add(taxonomy,
'Animalia,Chordata,Mammalia,Cetacea,Balaenopteridae,Balaenoptera,blue whale'.split(','))
Simplified implementation:
def add(t, keys):
for key in keys:
t = t[key]
We still don't need to assign:
{'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': {}}}}}}
conclusion
All of this is probably not very useful, just some interesting code.
If you like Python, think of this as fun to understand.