简体   繁体   中英

Printing tree levels in reverse

I have a code where it prints the Huffman Tree. It is this part:

while len(numArr) > 1:
    numArr = [numArr[0] + numArr[1]] + numArr[2:]
    numArr = sorted(numArr)
    valHold = numArr[0] * 8
    print(numArr)

Don't mind the valHold variables I use it to compute for the uncompressed bits of the input string.

Let's say I have 1,1,1,2,3,4 as the elements of list numArr (the elements comes from a Counter and transferred to letter_ar r and numArr to separate the two).

I can only print it like this:

1,1,1,1,2,3,4
1,1,2,2,3,4
2,2,2,3,4
2,3,4,4
4,4,5
5,8
13

Is there a way I can print it the other way? The way it will more look like a tree? Like this:

13
5,8
4,4,5
2,3,4,4
2,2,2,3,4
1,1,2,2,3,4
1,1,1,1,2,3,4

It will be much better if you can teach me how to print it with indent:

     13
     5,8
    4,4,5
   2,3,4,4
  2,2,2,3,4
 1,1,2,2,3,4
1,1,1,1,2,3,4

Please note that the elements of the numArr list is not predefined. It is based on what the user inputs in the program.

Sure:

tree = []
while len(numArr) > 1:
    numArr = [numArr[0] + numArr[1]] + numArr[2:]
    numArr = sorted(numArr)
    valHold = numArr[0] * 8
    tree.append(numArr)

indent = len(tree)
for row in tree[::-1]:
    print(" " * indent, row)
    indent -= 1

You could output your data in a tree format as follows:

numArray = [
    [1, 2, 1, 4, 1, 1, 3],
    [2, 4, 1, 3, 2, 1],
    [2, 3, 2, 4, 2],
    [4, 2, 3, 4],
    [5, 4, 4],
    [8, 5],
    [13]]

output = [','.join(str(x) for x in sorted(row)) for row in numArray[::-1]]

for row in output:
    print row.center(len(output[-1]))

This would display:

      13     
     5,8     
    4,4,5    
   2,3,4,4   
  2,2,2,3,4  
 1,1,2,2,3,4 
1,1,1,1,2,3,4

[::-1] can be used to read an array in reverse order. So the idea here is to read each row and convert each element into a string. These are then joined using commas to create a list of numbers. Finally each row is then displayed centred based on the length of the longest entry.

In order to print in reverse order, you can put it in a list first and later reverse it.

array = []
while len(numArr) > 1:
    numArr = [numArr[0] + numArr[1]] + numArr[2:]
    numArr = sorted(numArr)
    array.append(numArr)
array.reverse()

To indent the output and align it with each number might need a little extra work, but you can try to center the output as a work-around. First convert each list to a string, and compute maximum width. Then use str.center to center the text.

array_str = list(map(lambda level: ','.join(str(i) for i in level), array))
width = max(len(s) for s in array_str)
for s in array_str:
    print(s.center(width))

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