मैं पायथन में एक पेड़ कैसे लागू कर सकता हूं?


203

मैं एक सामान्य पेड़ बनाने की कोशिश कर रहा हूं।

इसे लागू करने के लिए पायथन में कोई अंतर्निहित डेटा संरचनाएं हैं?



@GrvTyagi लिंक काम नहीं करता।
टोनी लुकास

जवाबों:


231

anytree

मैं https://pypi.python.org/pypi/anytree (मैं लेखक हूं) की सलाह देता हूं

उदाहरण

from anytree import Node, RenderTree

udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')

for pre, fill, node in RenderTree(udo):
    print("%s%s" % (pre, node.name))
Udo
├── Marc
   └── Lian
└── Dan
    ├── Jet
    ├── Jan
    └── Joe

print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))

विशेषताएं

anytree के साथ एक शक्तिशाली एपीआई भी है:

  • सरल पेड़ निर्माण
  • सरल पेड़ संशोधन
  • पूर्व-क्रम वृक्ष पुनरावृत्ति
  • आदेश के बाद पेड़ पुनरावृत्ति
  • सापेक्ष और निरपेक्ष नोड पथ को हल करें
  • एक नोड से दूसरे तक चलना।
  • वृक्ष प्रतिपादन (ऊपर उदाहरण देखें)
  • नोड अटैच / डिटक हुकअप

31
बस सबसे अच्छा जवाब है, दूसरों को पहिया को सुदृढ़ कर रहे हैं।
ओन्ड्रेज

66
यह बताना अच्छा है कि आप उस पैकेज के लेखक हैं जिसे आप अपने उत्तर में सुझा रहे हैं।
जॉन वाई

3
@ c0fec0de मैं तुमसे प्यार करता हूँ !!!! यह पुस्तकालय अद्भुत है, यहां तक ​​कि एक दृश्य कार्यक्षमता भी है
लेसर

2
@ ऑन्ड्रेज अन्य जवाबों पर निर्भरता कम है और मूल प्रश्न में निर्मित डेटा-संरचनाओं के बारे में पूछा गया था। जबकि anytreeशायद एक महान पुस्तकालय है, यह एक अजगर प्रश्न है, न कि Node.js प्रश्न।
रॉब रोज़

मुझे Google के माध्यम से यह उत्तर आया। यह पुस्तकालय वास्तव में अच्छा है। मुझे विशेष रूप से किसी भी वस्तु का पेड़ बनाने के लिए मिक्सिन वर्ग का उपयोग करने की क्षमता पसंद है!
नॉकिंग

104

पायथन के पास "बिल्ट-इन" डेटा संरचनाओं की व्यापक रेंज नहीं है जैसा कि जावा करता है। हालांकि, क्योंकि पायथन गतिशील है, एक सामान्य पेड़ बनाना आसान है। उदाहरण के लिए, एक बाइनरी ट्री हो सकता है:

class Tree:
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

आप इसे इस तरह से उपयोग कर सकते हैं:

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

109
यह वास्तव में एक उपयोगी पेड़ कार्यान्वयन बनाने के बारे में बहुत कुछ नहीं समझाता है।
माइक ग्राहम

14
प्रश्न Python3 के साथ टैग किया गया है, class Treeफिर ऑब्जेक्ट से प्राप्त करने की कोई आवश्यकता नहीं है
cfi

3
@cfi से प्राप्त करना objectकभी-कभी केवल एक दिशानिर्देश होता है: यदि कोई वर्ग किसी अन्य आधार वर्ग से विरासत में मिला है, तो स्पष्ट रूप से वस्तु से विरासत में मिला है। यह नेस्टेड कक्षाओं पर भी लागू होता है। Google पायथन स्टाइल गाइड
कोनराड रीच

16
@platzhirsch: कृपया दिशानिर्देश को पूरी तरह से पढ़ें और उद्धृत करें: Google स्पष्ट रूप से बताता है कि यह Python 2 कोड के लिए अपेक्षित के रूप में काम करने के लिए आवश्यक है और Py3 के साथ संगतता में सुधार करने के लिए अनुशंसित है। यहां हम Py3 कोड के बारे में बात कर रहे हैं। अतिरिक्त, विरासत टाइपिंग करने की कोई आवश्यकता नहीं है।
cfi

13
यह एक द्विआधारी पेड़ है, न कि सामान्य रूप से पूछा गया।
माइकल डॉर्नर

49

एक सामान्य पेड़ शून्य या अधिक बच्चों वाला, प्रत्येक एक उचित (पेड़) नोड है। यह बाइनरी ट्री के समान नहीं है, वे अलग-अलग डेटा संरचनाएं हैं, हालांकि दोनों कुछ शब्दावली साझा करते हैं।

पायथन में जेनेरिक पेड़ों के लिए कोई अंतर्निहित डेटा संरचना नहीं है, लेकिन इसे आसानी से कक्षाओं के साथ लागू किया जाता है।

class Tree(object):
    "Generic tree node."
    def __init__(self, name='root', children=None):
        self.name = name
        self.children = []
        if children is not None:
            for child in children:
                self.add_child(child)
    def __repr__(self):
        return self.name
    def add_child(self, node):
        assert isinstance(node, Tree)
        self.children.append(node)
#    *
#   /|\
#  1 2 +
#     / \
#    3   4
t = Tree('*', [Tree('1'),
               Tree('2'),
               Tree('+', [Tree('3'),
                          Tree('4')])])

कमाल है, यह आसानी से एक ग्राफ के रूप में भी इस्तेमाल किया जा सकता है! एकमात्र समस्या जो मैंने देखी वह है: मैं दाएं नोड से बाएं नोड को अलग कैसे कर सकता हूं?
20:ngelo Polotto

3
बच्चों द्वारा अनुक्रमणिका। वाम हमेशा उस स्थिति में बच्चे [0] होंगे।
Freund Allein

38

तुम कोशिश कर सकते हो:

from collections import defaultdict
def tree(): return defaultdict(tree)
users = tree()
users['harold']['username'] = 'hrldcpr'
users['handler']['username'] = 'matthandlersux'

जैसा कि यहाँ सुझाया गया है: https://gist.github.com/2012250


यदि आप स्तरों की एक मनमानी राशि का विस्तार करना चाहते हैं: stackoverflow.com/a/43237270/511809
natbusa

इस छाया में बनाया गया हैश हैश।
Tritium21

20
class Node:
    """
    Class Node
    """
    def __init__(self, value):
        self.left = None
        self.data = value
        self.right = None

class Tree:
    """
    Class tree will provide a tree as well as utility functions.
    """

    def createNode(self, data):
        """
        Utility function to create a node.
        """
        return Node(data)

    def insert(self, node , data):
        """
        Insert function will insert a node into tree.
        Duplicate keys are not allowed.
        """
        #if tree is empty , return a root node
        if node is None:
            return self.createNode(data)
        # if data is smaller than parent , insert it into left side
        if data < node.data:
            node.left = self.insert(node.left, data)
        elif data > node.data:
            node.right = self.insert(node.right, data)

        return node


    def search(self, node, data):
        """
        Search function will search a node into tree.
        """
        # if root is None or root is the search data.
        if node is None or node.data == data:
            return node

        if node.data < data:
            return self.search(node.right, data)
        else:
            return self.search(node.left, data)



    def deleteNode(self,node,data):
        """
        Delete function will delete a node into tree.
        Not complete , may need some more scenarion that we can handle
        Now it is handling only leaf.
        """

        # Check if tree is empty.
        if node is None:
            return None

        # searching key into BST.
        if data < node.data:
            node.left = self.deleteNode(node.left, data)
        elif data > node.data:
            node.right = self.deleteNode(node.right, data)
        else: # reach to the node that need to delete from BST.
            if node.left is None and node.right is None:
                del node
            if node.left == None:
                temp = node.right
                del node
                return  temp
            elif node.right == None:
                temp = node.left
                del node
                return temp

        return node






    def traverseInorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            self.traverseInorder(root.left)
            print root.data
            self.traverseInorder(root.right)

    def traversePreorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            print root.data
            self.traversePreorder(root.left)
            self.traversePreorder(root.right)

    def traversePostorder(self, root):
        """
        traverse function will print all the node in the tree.
        """
        if root is not None:
            self.traversePostorder(root.left)
            self.traversePostorder(root.right)
            print root.data


def main():
    root = None
    tree = Tree()
    root = tree.insert(root, 10)
    print root
    tree.insert(root, 20)
    tree.insert(root, 30)
    tree.insert(root, 40)
    tree.insert(root, 70)
    tree.insert(root, 60)
    tree.insert(root, 80)

    print "Traverse Inorder"
    tree.traverseInorder(root)

    print "Traverse Preorder"
    tree.traversePreorder(root)

    print "Traverse Postorder"
    tree.traversePostorder(root)


if __name__ == "__main__":
    main()

3
क्या आप अपने कोड और अपने कार्यान्वयन को लागू करने के लिए सिर्फ कुछ नोट जोड़ सकते हैं?
मिशेल डी'मिको

उपयोगिता कार्यों के साथ पूर्ण बाइनरी ट्री कार्यान्वयन के लिए धन्यवाद। चूंकि यह पायथन 2 है, इसलिए मैंने लोगों को पायथन 3 संस्करण की आवश्यकता के लिए बाइनरी ट्री कार्यान्वयन (Py3) के लिए एक जिस्ट बनाया ।
C --Z

16

वहाँ पेड़ नहीं बनाए गए हैं, लेकिन आप आसानी से सूची से एक नोड प्रकार को हटाकर और ट्रैवर्सल तरीके लिखकर निर्माण कर सकते हैं। यदि आप ऐसा करते हैं, तो मुझे बाइसेक्ट उपयोगी लगता है।

PyPi पर कई कार्यान्वयन भी हैं जिन्हें आप ब्राउज़ कर सकते हैं।

अगर मुझे सही तरीके से याद है, तो पायथन स्टैंडर्ड लिब में वृक्ष डेटा संरचनाओं को उसी कारण से शामिल नहीं किया जाता है जो .NET बेस क्लास लाइब्रेरी नहीं करता है: मेमोरी का स्थानीयकरण कम हो जाता है, जिसके परिणामस्वरूप अधिक कैश मिस हो जाता है। आधुनिक प्रोसेसर पर यह आमतौर पर कैश में मेमोरी का एक बड़ा हिस्सा लाने के लिए तेज़ होता है, और "पॉइंटर रिच" डेटा संरचनाएं लाभ को नकारती हैं।


2
FYI करें: इंटरव्यू बूस्ट के खिलाफ नफरत से भरे हुए हैं। जाहिर तौर पर इससे निपटने के लिए एक बड़ा दर्द होना चाहिए, खासकर जब से इसके लिए समर्थन बंद कर दिया गया है। तो मुझे लगता है कि से दूर रहने की सलाह देते हैं
inspectorG4dget

धन्यवाद। मुझे व्यक्तिगत रूप से कोई परेशानी नहीं हुई है, लेकिन मैं गुमराह नहीं करना चाहता, इसलिए मैंने वह संदर्भ हटा दिया है।
जस्टिन आर।

11

मैंने एक जड़ वाले पेड़ को एक शब्दकोश के रूप में लागू किया {child:parent}। उदाहरण के लिए रूट नोड के साथ 0, एक पेड़ ऐसा लग सकता है:

tree={1:0, 2:0, 3:1, 4:2, 5:3}

इस संरचना ने किसी भी नोड से रूट तक एक पथ के साथ ऊपर की ओर जाना काफी आसान बना दिया, जो उस समस्या के लिए प्रासंगिक था जिस पर मैं काम कर रहा था।


1
यह वह तरीका है जिसे मैं करने पर विचार कर रहा था, जब तक कि मैंने उत्तर नहीं देखा। यद्यपि एक पेड़ दो बच्चों के साथ एक माता-पिता है, और यदि आप नीचे जाना चाहते हैं, तो आप कर सकते हैं {parent:[leftchild,rightchild]}
JFA

1
एक और तरीका उन सूचियों की सूची का उपयोग करना है जहां सूची में पहला (या अधिक) तत्व नोड मूल्य है, और निम्नलिखित नेस्टेड दो सूचियां इसके बाएं और दाएं उपप्रकारों (या एन-आर्य ट्री के लिए अधिक) का प्रतिनिधित्व करती हैं।
पेज

9

ग्रेग हेगिल का जवाब बहुत अच्छा है लेकिन अगर आपको प्रति स्तर अधिक नोड्स की आवश्यकता है तो आप एक सूची का उपयोग कर सकते हैं। उन्हें बनाने के लिए शब्दकोश: और फिर उन्हें नाम या आदेश द्वारा उपयोग करने के लिए विधि का उपयोग करें (जैसे आईडी)

class node(object):
    def __init__(self):
        self.name=None
        self.node=[]
        self.otherInfo = None
        self.prev=None
    def nex(self,child):
        "Gets a node by number"
        return self.node[child]
    def prev(self):
        return self.prev
    def goto(self,data):
        "Gets the node by name"
        for child in range(0,len(self.node)):
            if(self.node[child].name==data):
                return self.node[child]
    def add(self):
        node1=node()
        self.node.append(node1)
        node1.prev=self
        return node1

अब बस एक रूट बनाएं और इसे बनाएँ: ex:

tree=node()  #create a node
tree.name="root" #name it root
tree.otherInfo="blue" #or what ever 
tree=tree.add() #add a node to the root
tree.name="node1" #name it

    root
   /
child1

tree=tree.add()
tree.name="grandchild1"

       root
      /
   child1
   /
grandchild1

tree=tree.prev()
tree=tree.add()
tree.name="gchild2"

          root
           /
        child1
        /    \
grandchild1 gchild2

tree=tree.prev()
tree=tree.prev()
tree=tree.add()
tree=tree.name="child2"

              root
             /   \
        child1  child2
       /     \
grandchild1 gchild2


tree=tree.prev()
tree=tree.goto("child1") or tree=tree.nex(0)
tree.name="changed"

              root
              /   \
         changed   child2
        /      \
  grandchild1  gchild2

आपको यह पता लगाने के लिए पर्याप्त होना चाहिए कि यह काम कैसे करना है


इस उत्तर में कुछ गायब है, मैं पिछले 2 दिनों से इस समाधान की कोशिश कर रहा था और मुझे लगता है कि आपके पास ऑब्जेक्ट जोड़ विधि में कुछ तार्किक प्रवाह है। मैं इस प्रश्न का उत्तर प्रस्तुत करूंगा, कृपया देखें कि क्या मैं मदद कर सकता हूं।
MAULIK MODI

8
class Tree(dict):
    """A tree implementation using python's autovivification feature."""
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

    #cast a (nested) dict to a (nested) Tree class
    def __init__(self, data={}):
        for k, data in data.items():
            if isinstance(data, dict):
                self[k] = type(self)(data)
            else:
                self[k] = data

एक शब्दकोश के रूप में काम करता है, लेकिन आप चाहते हैं के रूप में कई नेस्टेड dicts प्रदान करता है। निम्नलिखित प्रयास करें:

your_tree = Tree()

your_tree['a']['1']['x']  = '@'
your_tree['a']['1']['y']  = '#'
your_tree['a']['2']['x']  = '$'
your_tree['a']['3']       = '%'
your_tree['b']            = '*'

एक नेस्टेड तानाशाही वितरित करेगा ... जो वास्तव में एक पेड़ के रूप में काम करता है।

{'a': {'1': {'x': '@', 'y': '#'}, '2': {'x': '$'}, '3': '%'}, 'b': '*'}

... यदि आपके पास पहले से ही एक तानाशाही है, तो यह प्रत्येक स्तर को एक पेड़ पर डाल देगा:

d = {'foo': {'amy': {'what': 'runs'} } }
tree = Tree(d)

print(d['foo']['amy']['what']) # returns 'runs'
d['foo']['amy']['when'] = 'now' # add new branch

इस प्रकार, आप अपनी इच्छानुसार प्रत्येक ताना-बाना को संपादित / जोड़ / हटा सकते हैं। ट्रैवर्सल आदि के लिए सभी प्रमुख तरीके, अभी भी लागू होते हैं।


2
क्या कोई कारण है कि आपने dictइसके बजाय विस्तार करना क्यों चुना defaultdict? मेरे परीक्षणों से, हुकुम के defaultdictबजाय विस्तार करना और फिर self.default_factory = type(self)init के शीर्ष पर उसी तरह कार्य करना चाहिए।
रॉब रोज़

मैं शायद यहाँ कुछ याद कर रहा हूँ, आप इस संरचना को कैसे नेविगेट करते हैं? बच्चों से माता-पिता के लिए जाना बहुत मुश्किल लगता है, उदाहरण के लिए, या भाई
स्ट्रॉमसन

6

मैंने नेस्टेड डाइक का उपयोग करके पेड़ लगाए हैं। यह करना काफी आसान है, और इसने मेरे लिए बहुत बड़े डेटा सेट के साथ काम किया है। मैंने नीचे एक नमूना पोस्ट किया है, और आप Google कोड पर अधिक देख सकते हैं

  def addBallotToTree(self, tree, ballotIndex, ballot=""):
    """Add one ballot to the tree.

    The root of the tree is a dictionary that has as keys the indicies of all 
    continuing and winning candidates.  For each candidate, the value is also
    a dictionary, and the keys of that dictionary include "n" and "bi".
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.

    If candidate c is a winning candidate, then that portion of the tree is
    expanded to indicate the breakdown of the subsequently ranked candidates.
    In this situation, additional keys are added to the tree[c] dictionary
    corresponding to subsequently ranked candidates.
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
    tree[c][d]["n"] is the number of ballots that rank c first and d second.
    tree[c][d]["bi"] is a list of the corresponding ballot indices.

    Where the second ranked candidates is also a winner, then the tree is 
    expanded to the next level.  

    Losing candidates are ignored and treated as if they do not appear on the 
    ballots.  For example, tree[c][d]["n"] is the total number of ballots
    where candidate c is the first non-losing candidate, c is a winner, and
    d is the next non-losing candidate.  This will include the following
    ballots, where x represents a losing candidate:
    [c d]
    [x c d]
    [c x d]
    [x c x x d]

    During the count, the tree is dynamically updated as candidates change
    their status.  The parameter "tree" to this method may be the root of the
    tree or may be a sub-tree.
    """

    if ballot == "":
      # Add the complete ballot to the tree
      weight, ballot = self.b.getWeightedBallot(ballotIndex)
    else:
      # When ballot is not "", we are adding a truncated ballot to the tree,
      # because a higher-ranked candidate is a winner.
      weight = self.b.getWeight(ballotIndex)

    # Get the top choice among candidates still in the running
    # Note that we can't use Ballots.getTopChoiceFromWeightedBallot since
    # we are looking for the top choice over a truncated ballot.
    for c in ballot:
      if c in self.continuing | self.winners:
        break # c is the top choice so stop
    else:
      c = None # no candidates left on this ballot

    if c is None:
      # This will happen if the ballot contains only winning and losing
      # candidates.  The ballot index will not need to be transferred
      # again so it can be thrown away.
      return

    # Create space if necessary.
    if not tree.has_key(c):
      tree[c] = {}
      tree[c]["n"] = 0
      tree[c]["bi"] = []

    tree[c]["n"] += weight

    if c in self.winners:
      # Because candidate is a winner, a portion of the ballot goes to
      # the next candidate.  Pass on a truncated ballot so that the same
      # candidate doesn't get counted twice.
      i = ballot.index(c)
      ballot2 = ballot[i+1:]
      self.addBallotToTree(tree[c], ballotIndex, ballot2)
    else:
      # Candidate is in continuing so we stop here.
      tree[c]["bi"].append(ballotIndex)

5

मैंने अपनी साइट पर एक पायथन [3] वृक्ष कार्यान्वयन प्रकाशित किया है: http://www.quesucede.com/page/show/id/python_3_tree_implementation

आशा है कि यह उपयोग की है,

ठीक है, यहाँ कोड है:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name,
                                     self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name,
                                                 self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes
                if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

4

यदि किसी को इसे करने के लिए एक सरल तरीके की आवश्यकता होती है, तो एक पेड़ केवल एक पुनरावर्ती नेस्टेड सूची है (चूंकि सेट धोने योग्य नहीं है):

[root, [child_1, [[child_11, []], [child_12, []]], [child_2, []]]]

जहां प्रत्येक शाखा एक जोड़ी है: [ object, [children] ]
और प्रत्येक पत्ती एक जोड़ी है:[ object, [] ]

लेकिन अगर आपको विधियों के साथ एक वर्ग की आवश्यकता है, तो आप anytree का उपयोग कर सकते हैं।


1

आपको किन ऑपरेशनों की आवश्यकता है? पाइथन में अक्सर एक अच्छा समाधान होता है जो कि बाइसेक्ट मॉड्यूल के साथ एक तानाशाही या एक सूची का उपयोग करता है।

PyPI पर कई, कई पेड़ कार्यान्वयन हैं , और कई पेड़ प्रकार शुद्ध अजगर में खुद को लागू करने के लिए लगभग तुच्छ हैं। हालांकि, यह शायद ही कभी आवश्यक है।


0

एक और पेड़ कार्यान्वयन शिथिल के आधार पर ब्रूनो जवाब :

class Node:
    def __init__(self):
        self.name: str = ''
        self.children: List[Node] = []
        self.parent: Node = self

    def __getitem__(self, i: int) -> 'Node':
        return self.children[i]

    def add_child(self):
        child = Node()
        self.children.append(child)
        child.parent = self
        return child

    def __str__(self) -> str:
        def _get_character(x, left, right) -> str:
            if x < left:
                return '/'
            elif x >= right:
                return '\\'
            else:
                return '|'

        if len(self.children):
            children_lines: Sequence[List[str]] = list(map(lambda child: str(child).split('\n'), self.children))
            widths: Sequence[int] = list(map(lambda child_lines: len(child_lines[0]), children_lines))
            max_height: int = max(map(len, children_lines))
            total_width: int = sum(widths) + len(widths) - 1
            left: int = (total_width - len(self.name) + 1) // 2
            right: int = left + len(self.name)

            return '\n'.join((
                self.name.center(total_width),
                ' '.join(map(lambda width, position: _get_character(position - width // 2, left, right).center(width),
                             widths, accumulate(widths, add))),
                *map(
                    lambda row: ' '.join(map(
                        lambda child_lines: child_lines[row] if row < len(child_lines) else ' ' * len(child_lines[0]),
                        children_lines)),
                    range(max_height))))
        else:
            return self.name

और इसका उपयोग कैसे करें का एक उदाहरण:

tree = Node()
tree.name = 'Root node'
tree.add_child()
tree[0].name = 'Child node 0'
tree.add_child()
tree[1].name = 'Child node 1'
tree.add_child()
tree[2].name = 'Child node 2'
tree[1].add_child()
tree[1][0].name = 'Grandchild 1.0'
tree[2].add_child()
tree[2][0].name = 'Grandchild 2.0'
tree[2].add_child()
tree[2][1].name = 'Grandchild 2.1'
print(tree)

जो उत्पादन करना चाहिए:

                        रूट नोड                        
     / / \              
बाल नोड 0 बाल नोड 1 बाल नोड 2        
                   | / \ _       
             ग्रैंडचिल्ड 1.0 ग्रैंडचिल्ड 2.0 ग्रैंडचिल्ड 2.1

0

मैं नेटवर्कएक्स लाइब्रेरी का सुझाव देता हूं

NetworkX संरचना, गतिकी, और जटिल नेटवर्क के कार्यों के निर्माण, हेरफेर और अध्ययन के लिए एक पायथन पैकेज है।

एक पेड़ बनाने का एक उदाहरण:

import networkx as nx
G = nx.Graph()
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('B', 'D')
G.add_edge('A', 'E')
G.add_edge('E', 'F')

मुझे यकीन नहीं है कि आप " सामान्य वृक्ष" से क्या मतलब रखते हैं ,
लेकिन पुस्तकालय प्रत्येक नोड को किसी भी धुलाई योग्य वस्तु के लिए सक्षम बनाता है , और प्रत्येक नोड के बच्चों की संख्या पर कोई बाधा नहीं है।

पुस्तकालय पेड़ों और दृश्य क्षमताओं से संबंधित ग्राफ एल्गोरिदम भी प्रदान करता है।


-2

यदि आप एक ट्री डेटा स्ट्रक्चर बनाना चाहते हैं तो सबसे पहले आपको ट्रीइलमेंट ऑब्जेक्ट बनाना होगा। यदि आप ट्री-ऑब्जेक्ट ऑब्जेक्ट बनाते हैं, तो आप तय कर सकते हैं कि आपका पेड़ कैसे व्यवहार करता है।

निम्नलिखित करने के लिए ट्रीइलमेंट वर्ग है:

class TreeElement (object):

def __init__(self):
    self.elementName = None
    self.element = []
    self.previous = None
    self.elementScore = None
    self.elementParent = None
    self.elementPath = []
    self.treeLevel = 0

def goto(self, data):
    for child in range(0, len(self.element)):
        if (self.element[child].elementName == data):
            return self.element[child]

def add(self):

    single_element = TreeElement()
    single_element.elementName = self.elementName
    single_element.previous = self.elementParent
    single_element.elementScore = self.elementScore
    single_element.elementPath = self.elementPath
    single_element.treeLevel = self.treeLevel

    self.element.append(single_element)

    return single_element

अब, हमें इस तत्व का उपयोग पेड़ बनाने के लिए करना है, मैं इस उदाहरण में A * वृक्ष का उपयोग कर रहा हूं।

class AStarAgent(Agent):
# Initialization Function: Called one time when the game starts
def registerInitialState(self, state):
    return;

# GetAction Function: Called with every frame
def getAction(self, state):

    # Sorting function for the queue
    def sortByHeuristic(each_element):

        if each_element.elementScore:
            individual_score = each_element.elementScore[0][0] + each_element.treeLevel
        else:
            individual_score = admissibleHeuristic(each_element)

        return individual_score

    # check the game is over or not
    if state.isWin():
        print('Job is done')
        return Directions.STOP
    elif state.isLose():
        print('you lost')
        return Directions.STOP

    # Create empty list for the next states
    astar_queue = []
    astar_leaf_queue = []
    astar_tree_level = 0
    parent_tree_level = 0

    # Create Tree from the give node element
    astar_tree = TreeElement()
    astar_tree.elementName = state
    astar_tree.treeLevel = astar_tree_level
    astar_tree = astar_tree.add()

    # Add first element into the queue
    astar_queue.append(astar_tree)

    # Traverse all the elements of the queue
    while astar_queue:

        # Sort the element from the queue
        if len(astar_queue) > 1:
            astar_queue.sort(key=lambda x: sortByHeuristic(x))

        # Get the first node from the queue
        astar_child_object = astar_queue.pop(0)
        astar_child_state = astar_child_object.elementName

        # get all legal actions for the current node
        current_actions = astar_child_state.getLegalPacmanActions()

        if current_actions:

            # get all the successor state for these actions
            for action in current_actions:

                # Get the successor of the current node
                next_state = astar_child_state.generatePacmanSuccessor(action)

                if next_state:

                    # evaluate the successor states using scoreEvaluation heuristic
                    element_scored = [(admissibleHeuristic(next_state), action)]

                    # Increase the level for the child
                    parent_tree_level = astar_tree.goto(astar_child_state)
                    if parent_tree_level:
                        astar_tree_level = parent_tree_level.treeLevel + 1
                    else:
                        astar_tree_level += 1

                    # create tree for the finding the data
                    astar_tree.elementName = next_state
                    astar_tree.elementParent = astar_child_state
                    astar_tree.elementScore = element_scored
                    astar_tree.elementPath.append(astar_child_state)
                    astar_tree.treeLevel = astar_tree_level
                    astar_object = astar_tree.add()

                    # If the state exists then add that to the queue
                    astar_queue.append(astar_object)

                else:
                    # Update the value leaf into the queue
                    astar_leaf_state = astar_tree.goto(astar_child_state)
                    astar_leaf_queue.append(astar_leaf_state)

आप ऑब्जेक्ट से किसी भी तत्व को जोड़ / हटा सकते हैं, लेकिन संरचना को जटिल बना सकते हैं।


-4
def iterative_bfs(graph, start):
    '''iterative breadth first search from start'''
    bfs_tree = {start: {"parents":[], "children":[], "level":0}}
    q = [start]
    while q:
        current = q.pop(0)
        for v in graph[current]:
            if not v in bfs_tree:
                bfs_tree[v]={"parents":[current], "children":[], "level": bfs_tree[current]["level"] + 1}
                bfs_tree[current]["children"].append(v)
                q.append(v)
            else:
                if bfs_tree[v]["level"] > bfs_tree[current]["level"]:
                    bfs_tree[current]["children"].append(v)
                    bfs_tree[v]["parents"].append(current)

यह किसी भी पठनीय तरीके से प्रश्न का उत्तर देने के लिए प्रकट नहीं होता है।
अल्बल्यू
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.