简体   繁体   中英

Attribute binary code as the path from binary tree in Python

How can I attribute a binary code to a symbol, based on their path within a binary tree? In other words, a dictionary.

Example of a tree:

tree=[['a', 'p'], [[['n', 'u'], 'o'], ' ']]

or if you prefer:

tree=[
        ['a', 'p'],
        [
            [
                ['n', 'u'],
                'o'
            ],
            ' '
        ]
     ]

I've tried using a recursive method to reach a specified symbol, and record it's path as a string, either adding a 0 or 1, as it iterated through the branches, but without success and I don't know how to traverse the tree from the root.

Can anyone give me an hint of the best way to do this?

Going off your previous question, if you need to feed a long string of characters and you don't know when each one is cut off:

global tree #just declare the tree globally -- this is just shorthand
def findMessage(t, s):
    if (s == ""):
        return ""
    if(isinstance(t, str)):
        return t + findMessage(tree[int(s[0])], s[1:])
    return findMessage(t[int(s[0])], s[1:])

s is the string that you're trying to read, and t is the fraction of the tree that you have left to explore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM