无法确定使用哪种数据结构来提高效率

时间:2018-03-15 08:05:54

标签: python tree

我来自目前正在学习Python的C背景。我的任务是创建一个通用树。该程序的输入是两次通过。在第一关中,我必须收集一个人的身份,姓名,角色和部门。在第二遍中,我将了解节点的父节点,即管理器。所以我必须暂时存储这些值。在C中,我通常会使用结构数组或链表,具体取决于大小信息的可用性。但我在Python中迷失了方向,甚至不确定我所做的事情是否可行,更不用说效率了。

提前致谢, Preeti。

if __name__ == "__main__": 
  # Have successfully created the tree and added nodes by hardcoding values as shown below in commented code
  # create_tree = Tree()
  # Tree.add_node(42, "Stephen", "Time Cone Radiation", "Black Hole")

  # But unable to figure out how to store transient info and use it later to create the tree. 
  num = 8
  list = []
  backup_num = num
  while num:
    id, name, role, dept = raw_input().split()
    num -= 1
    list.append((id, name, role, dept))

  while backup_num:
    id, parent = raw_input().split()
    backup_num -= 1
    #For an id in the list above locate it, and call add_node.
    # But not sure how and what is an efficient way. 

1 个答案:

答案 0 :(得分:0)

这会给你一个票价的想法。希望这可以帮助。

class Tree():
    def __init__(self):
        self.length = 0
        self.data = {}

    def add_node(self, nodeid, name, role, dept):
        obj = {}
        obj["child"] = {"left": None, "right": None}
        obj["parent_id"] = None
        obj["name"] = name
        obj["role"] = role
        obj["dept"] = dept

        self.data[nodeid] = obj
        self.length += 1
        return True

    # which_one : Left or Right
    def update_child_id(self, which_one, nodeid_parent, nodeid_child):
        self.data[nodeid_parent]["child"][which_one] = nodeid_child
        return True

    def update_parent(self, nodeid, parent_id):
        self.data[nodeid]["parent_id"] = parent_id
        return True

    def display_node(self, nodeid):
        obj = self.data[nodeid]
        print("Node:", nodeid)
        print("Parent:", obj["parent_id"], ", Name:", obj["name"], ", Role: ", obj["role"], ", Dept: ", obj["dept"])

    def display_child(self, nodeid):
        print(self.data[nodeid]["child"].items())


# Main 
test = Tree()

# Get the identity and then add here
node_id, name, role, dept = [42, "Stephen", "Time Cone Radiation", "Black Hole"]
test.add_node(node_id, name, role, dept)

# Get the parent id and add here
parent_id, parent = [6, "James"]
test.update_parent(node_id, parent_id)

test.display_node(42)
test.display_child(42)