Note that there are some explanatory texts on larger screens.

plurals
  1. POExtracting data from nested tuples
    primarykey
    data
    text
    <p>For an application I'm working on I need to create lists from nested tuples, representing the data contained in each branch. </p> <p>For reference the tuples represent a Huffman tree, an example is:</p> <pre><code>tree = (1.0, (0.5, (0.25, (0.125, 'd'),(0.125, 'c')), (0.25, 'b')), (0.5,'a')) </code></pre> <p>This was created from a Huffman routine with the following probabilities:</p> <pre><code>a:0.5, b:0.25, c:0.125, d:0.125 </code></pre> <p>I would like to out put a list which looks like </p> <pre><code>[['a'],['b','c','d']] </code></pre> <p>I've tried the following code:</p> <pre><code>def makeList(tree): if len(tree) == 2: return [tree[0]] else: rightlist = [] leftlist = [] right = list(tree[1]) left = list(tree[2]) for i in range(1, len(right)): rightlist.append(right[i]) for i in range(1, len(left)): leftlist.append(left[i]) return [rightlist, leftlist] </code></pre> <p>However this returns</p> <pre><code>[['a'],[(0.25, (0.125, 'd'),(0.125,'c')),(0.25,'b')] </code></pre> <p>Which isn't quite what I want. </p> <p>How could I go about modifying my code above to produce the output I want?</p> <p><strong>EDIT</strong></p> <p>I have produced some code which given a balanced input: </p> <pre><code>('a',0.25), ('b', 0.25), ('c', 0.25), ('d',0.25) </code></pre> <p>produces the output I want:</p> <pre><code>[['a','b'], ['c','d']] def makeList(tree): if len(tree) == 2: print("I'm in here") return [tree[1]] else: right = tree[1] left = tree[2] rightlist = [] leftlist = [] for i in range(0, len(right)): if type(right[i]) == tuple: print('right: ' + str(right[i])) rightlist.append(right[i][1]) for i in range(0, len(left)): if type(left[i]) == tuple: print('left: ' + str(left[i])) leftlist.append(left[i][1]) return [rightlist, leftlist] </code></pre> <p>However, it fails on the following inputs (output below):</p> <pre><code>exampleData = [(0.5, 'a'), (0.5,'b')] [[],[[]] exampleData = [(0.5, 'a'), (0.25,'b'), (0.25,'c')] [[],['b'.'c']] exampleData = [(0.5,'a'), (0.25,'b'), (0.125,'c'), (0.125,'d')] [[]],['b',(0.125, 'd')]] </code></pre> <p>However, the gold-standard test that this needs to pass is creating these lists for random trees:</p> <pre><code>probs = np.random.dirichlet([1]*4).tolist() indices = range(0,4) exampleData = zip(probs, indices) huffTree = makeHuffmanTree(exampleData) groups = makeLists(groups) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload