Python - Преобразуване на n-арно дърво в двоично дърво

class Tree:

        def __init__(self, new_key):
    self.__key = new_key    # Root key value
    self.__children = []     # List of children
    self.__num_of_descendants = 0 # Number of Descendants of this node    

# Prints the given tree
def printTree(self):
    return self.printTreeGivenPrefix("", True)   

# Prints the given tree with the given prefix for the line
# last_child indicates whether the node is the last of its parent"s child
# or not
def printTreeGivenPrefix(self, line_prefix, last_child):
    print(line_prefix, end="")
    if last_child:
        print("â””--> ", end="")
    else:
        print("|--> ", end="")
    print(self.__key)

    if len(self.__children) > 0:
        next_pre = line_prefix
        if last_child:
            next_pre += "     "
        else:
            next_pre += "|    "
        for child_index in range(len(self.__children)-1):
            self.__children[child_index].\
                printTreeGivenPrefix(next_pre, False)
        self.__children[-1].printTreeGivenPrefix(next_pre, True)

def __repr__(self):
    return "[" + str(self.__key) + "".join(
        [ repr(child) for child in self.__children ]) + "]"

# This static function will load a tree with the format of below:
# [root[child_1][child_2]...[child_n]]
# Each child_i can be a tree with the above format, too
# pos is the position in the given string
@staticmethod
def loadTree(tree_str, pos = 0):
    new_node = None
    while pos < len(tree_str):
        if tree_str[pos] == "[":
            pos += 1
            new_node = Tree(tree_str[pos])
            while pos < len(tree_str) and tree_str[pos + 1] != "]":
                pos += 1
                child_tree, pos = Tree.loadTree(tree_str, pos)
                if child_tree:
                    new_node.__children.append(child_tree)
                    new_node.__num_of_descendants += \
                        1 + child_tree.__num_of_descendants
            return new_node, pos + 1
        else:
            pos += 1
    return new_node, pos

def find_largest(self):
    if self.__num_of_descendants == 1:
        return self.__children[0]

    else:
        largest_child = self.__children[0]
        for child in self.__children:
            if child.__num_of_descendants > \
               largest_child.__num_of_descendants:
                largest_child = child
            if child.__num_of_descendants == \
               largest_child.__num_of_descendants:
                if child.__key > largest_child.__key:
                    largest_child = child
    return largest_child

def convert_to_binary_tree(self):
    if self.__num_of_descendants != 0:
        if self.__num_of_descendants < 3:
            for child in self.__children:
                child.convert_to_binary_tree()

        if self.__num_of_descendants > 2:
            left_child = self.__children[0]
            for child in self.__children[1:]:
                if len(child.__children) > len(left_child.__children):
                    left_child = child
                elif len(child.__children) == len(left_child.__children):
                    if child.__key > left_child.__key:
                        left_child = child
            self.__children.remove(left_child)
            self.__num_of_descendants -= 1

            right_child = self.__children[0]
            for child in self.__children[1:]:
                if len(child.__children) > len(right_child.__children):
                    right_child = child
                elif len(child.__children) == len(right_child.__children):
                    if child.__key > right_child.__key:
                        right_child = child
            self.__children.remove(right_child)
            self.__num_of_descendants -= 1
            print(self.__num_of_descendants)
            print(self.__children)
            print(left_child)
            print(right_child)

            #Move remaining children two either left_child or right_child.
            while self.__num_of_descendants != 0:
                largest_child = self.find_largest()
                print(largest_child)
                if left_child.__num_of_descendants < \
                   right_child.__num_of_descendants:
                    left_child.__children.append(largest_child)
                    left_child.__num_of_descendants += 1
                    self.__children.remove(largest_child)
                    self.__num_of_descendants -= 1                        

                elif left_child.__num_of_descendants > \
                   right_child.__num_of_descendants:
                    right_child.__children.append(largest_child)
                    right_child.__num_of_descendants += 1
                    self.__children.remove(largest_child)
                    self.__num_of_descendants -= 1                        

                elif left_child.__num_of_descendants == \
                   right_child.__num_of_descendants:
                    if left_child.__key > right_child.__key:
                        left_child.__children.append(largest_child)
                        left_child.__num_of_descendants += 1
                        self.__children.remove(largest_child)
                        self.__num_of_descendants -= 1                            
                    else:
                        right_child.__children.append(largest_child)
                        right_child.__num_of_descendants += 1
                        self.__children.remove(largest_child)
                        self.__num_of_descendants -= 1
            #Now run recursion on left and right binary children.
            self.__children.append(left_child)
            self.__children.append(right_child)
            self.__num_of_descendants = 2
            print(self.__children)
            for child in self.__children:
                child.convert_to_binary_tree()
def main():
    tree, processed_chars = Tree.loadTree('[z[y][x][w][v]]]')
    tree.convert_to_binary_tree()
    tree.printTree()
    print(tree)

if __name__ == "__main__":
    main()

Трябва да конвертирам дадено дърво в двоично дърво. Ако възел в дървото има повече от 2 деца, трябва да присвоя детето с най-много потомци като ляв възел и детето с втория по големина брой потомци като дясно дете. Останалите деца се добавят, както следва: 1) Вземете дете с най-голям брой потомци 2) Добавете го към левия/десния възел. Която има по-малко деца по това време.

*Ако в даден момент трябва да избера детето с най-голям брой потомци, но има две+ с еднакъв брой потомци, вземам този с по-голяма стойност на ключ.

I get a print out like this...
2 #Number of 'z' children after left and right node chosen.
[[w], [v]] #Children of 'z'
[y] #Binary left child of 'z'
[x] #Binary right child of 'z'
[w] #This is a bug. It should be choosing 'v' as larger child of 'z' and assigning it to left child 'y'
[v] #This is a bug. see above.
[[y[w]], [x[v]]] #These are the children of node 'z'
â””--> z #schematic of binary tree
     |--> y
     |    â””--> w
     â””--> x
          â””--> v
[z[y[w]][x[v]]] #final binary tree 

person zachary    schedule 27.03.2014    source източник
comment
Настрана: няма причина да поставяте префикс на вашите променливи с __ тук. Ако настоявате, можете да използвате _ като приятелско напомняне, че някои не са предназначени да бъдат модифицирани извън класа, но дори това често е прекалено.   -  person DSM    schedule 27.03.2014
comment
Да, и аз не харесвам начина, по който са кръстени, но инструкторът ми настоява...   -  person zachary    schedule 27.03.2014
comment
Можете ли да проверите отстъпа на кода? Функцията main и шаблонът if __name__ == "__main__" наистина ли са отстъпени под class или всъщност са на най-високо ниво?   -  person Blckknght    schedule 27.03.2014
comment
Е, ако има повече от три деца, децата на тези възли трябва да бъдат пренаредени. Тоест, ако даден възел има три деца, най-големите две стойности се присвояват като ляво и дясно дете на възела, докато останалите деца се присвояват на новото ляво или дясно дете. Ако възелът има само две деца, той вече е във формат на двоично дърво и не трябва да се прави нищо. Но искам да стартирам форматирането на тези 2 деца, в случай че едно от тях има 3+ деца.   -  person zachary    schedule 27.03.2014
comment
Съжаляваме, отстъпът е изключен. main функция и ако name == main са на основно ниво.   -  person zachary    schedule 27.03.2014
comment

Разгледах Fira Code и исках да го изпробвам с един от изброените поддържани редактори. Така че стартирах RStudio (версия 0.99.491 на кутия Win) и зададох шрифта на Fira Code, но ... нищо. И така, как да активирам лигатури на шрифтове в RStudio?

РЕДАКТИРАНЕ: Трикът в приетия отговор по-долу все още работи за RStudio версия 1.0.44. Все още ми се иска да има прост бутон, който да го активира.

  -  person DSM    schedule 27.03.2014


Отговори (1)


Коментарът на DSM ми помогна да видя какво се случва. След като изберете left_child и right_child в първите части на вашия convert_to_binary_tree метод, вие не ги премахвате от списъка с деца. Това означава, че по-късно, когато добавите всички деца на текущия възел към нови родители, вие добавяте лявото и дясното дете към себе си (или едно към друго). Когато се върнете към тези деца, можете да се окажете в безкраен цикъл.

Наистина не разбирам логиката на вашите left_child и right_child селекции, така че нямам фиксиран код, който да ви предложа. Бързо, но грозно решение би било да поставите израз if child in (left_child, right_child): continue в горната част на цикъла for, където присвоявате другите деца на нови родители.

Обърнете внимание, че има друга грешка в текущия ви код, при която броят на потомците за левите и десните деца ще стане неправилен. Това е така, защото не актуализирате броя, когато набутате някои от техните бивши братя и сестри в тях като деца.

person Blckknght    schedule 27.03.2014
comment
Хей, благодаря, че отделихте време да разгледате кода. В крайна сметка изтрих по-голямата част от него, след като разбрах какво току-що публикувахте. Актуализирах кода си, но по някаква причина все още получавам грешка. Вижте актуализираната публикация, ако имате време :) - person zachary; 27.03.2014
comment
Стесних го. По някаква причина програмата въвежда def find_largest(self): if child.__key › large_child.__key: large_child = child Тя не регистрира v › w. - person zachary; 27.03.2014