我一直在用python練習遞回,目前正試圖停止遞回到單個位元組,而是停止在某個位元組大小。在此示例中,我選擇 2,因此在我的代碼中,如果要生成的潛在子節點中的任何一個小于 2,它將不會遞回,只會回傳當前節點。它適用于第一個位元組字串,但適用于接下來的兩個。為什么會發生這種情況,我該如何解決?
第一個 b 的正確輸出:停止遞回/創建大小為 3 的孩子,因為下一代孩子至少有 1 個小于大小 2 的孩子
b'\x00\x01\x00\x02\x00\x03'
b'\x00\x01\x00'
b'\x02\x00\x03'
第二個 b 的輸出不正確:似乎是遞回的,直到單個位元組
b'L_]ju\x87\xd4\x14j\x1b> \xc52'
b'L_]ju\x87\xd4'
b'L_]'
b'ju\x87\xd4'
b'ju'
b'\x87\xd4'
b'\x14j\x1b> \xc52'
b'\x14j\x1b'
b'> \xc52'
b'> '
b'\xc52'
from random import randbytes
class Node:
def __init__(self, value):
self.value = value
self.children = []
self.parent = None
self.bytesize = len(value)
def make_children(self, child):
child.parent = self
self.children.append(child)
def print_tree(self):
print(self.value)
if len(self.children) > 0: # leaf node case
for child in self.children:
child.print_tree()
def build_tree(value_list):
root = Node(value_list)
#if len(value_list) == 1:
if len(value_list) / 2 < 2: # MODIFY TO STOP RECURSING IF SIZE OF CHILDREN WILL BE BELOW 2
return root
mid_point = len(value_list) // 2
left_half = value_list[:mid_point]
right_half = value_list[mid_point:]
child1 = build_tree(left_half)
root.make_children(child1)
child2 = build_tree(right_half)
root.make_children(child2)
return root
if __name__ == '__main__':
#list1 = [12, 7, 8, 15, 9]
b = b'\x00\x01\x00\x02\x00\x03'
#b = b'\x4c\x5f\x5d\x6a\x75\x87\xd4\x14\x6a\x1b\x3e\x20\xc5\x32'
#b = randbytes(6)
file = build_tree(b)
file.print_tree()
print(len(b))
uj5u.com熱心網友回復:
您的代碼實際上按預期作業。您提到的兩個位元組字串都有 2 個位元組,而不是 1 個。
這是顯示位元組串的一種方法,可能會使它更清晰:
def print_string(s):
print(' '.join(map('{:#2x}'.format, s)))
print_string(b'> ')
# 0x3e 0x20
print_string(b'\xc52')
# 0xc5 0x32
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470942.html
上一篇:使用clearTimeout()后遞回setTimeout()回圈未停止
下一篇:二叉樹中序遍歷-遞回
