Question

In: Computer Science

Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...

Create a preorder iterator for the class binarytree from the Python program below.
class Binarytree:

    def __init__(self, DataObject):
        self.data = DataObject
        self.parents = None
        self.left_child = None
        self.right_child = None

    @property
    def left_child(self):
        return self.__left_child

    @left_child.setter
    def left_child(self, node):
        self.__left_child = node
        if node is not None:
            node.parents = self

    @property
    def right_child(self):
        return self.__right_child

    @right_child.setter
    def right_child(self, node):
        self.__right_child = node
        if node is not None:
            node.parents = self

    def is_leafNode(self):
        if self.left_child is None and self.right_child is None:
            return True
        return False

    def rekursive_preorder_print(self, nivaa=0):
        for i in range(nivaa):
            print("\t", end="")
        print(self.data)
        if self.left_child is not None:
            self.left_child.rekursive_preorder_print(nivaa+1)
        if self.right_child is not None:
            self.right_child.rekursive_preorder_print(nivaa+1)

    def rekursive_preorder_calculation(self):
        if self.is_leafNode():
            return float(self.data)
        left_value = self.left_child.rekursive_preorder_calculation()
        right_value = self.right_child.rekursive_preorder_calculation()
        if self.data == "+":
            return left_value + right_value
        if self.data == "*":
            return left_value * right_value
        if self.data == "**":
            return left_value ** right_value
        if self.data == "-":
            return left_value + right_value
        if self.data == "/":
            return left_value / right_value
        raise ValueError(f"Ukjent operator: {self.data}")

    def rekursiv_inorder_formulaprint(self):
        if self.is_leafNode():
            print(self.data, end="")
        else:
            print("(", end="")
            self.left_child.rekursiv_inorder_formulaprint()
            print(f" {self.data} ", end="")
            self.right_child.rekursiv_inorder_formulaprint()
            print(")", end="")

    def __iter__(self):
        return BinarytreePostorderIterator(self)

class BinarytreePostorderIterator:
    def __init__(self, tree):
        self.tree = tree
        self.stabel = []
        self.stabel.append((tree, 0))

    def __next__(self):
        while len(self.stabel) > 0:
            element = self.stabel.pop()
            if element[0].is_leafNode():
                return element[0].data
            if element[1] == 0:
                self.stabel.append((element[0], 1))
                if element[0].left_child is not None:
                    self.stabel.append((element[0].left_child, 0))
            if element[1] == 1:
                self.stabel.append((element[0], 2))
                if element[0].right_child is not None:
                    self.stabel.append((element[0].right_child, 0))
            if element[1] == 2:
                return element[0].data
        raise StopIteration

    def __iter__(self):
        return self


if __name__ == "__main__":
    rot = Binarytree("+")
    v_barn_1 = Binarytree("**")
    rot.left_child = v_barn_1
    v_v_barn = Binarytree("5")
    v_h_barn = Binarytree("2")
    v_barn_1.left_child = v_v_barn
    v_barn_1.right_child = v_h_barn
    h_barn_1 = Binarytree("+")
    rot.right_child = h_barn_1
    h_v_barn = Binarytree("*")
    h_v_barn.left_child = Binarytree("2")
    h_v_barn.right_child = Binarytree("3")
    h_barn_1.left_child = h_v_barn
    h_h_barn = Binarytree("*")
    h_barn_1.right_child = h_h_barn
    h_h_barn.left_child = Binarytree("7")
    h_h_h_barn = Binarytree("+")
    h_h_barn.right_child = h_h_h_barn
    h_h_h_barn.left_child = Binarytree("9")
    h_h_h_barn.right_child = Binarytree("5")
    rot.rekursive_preorder_print()
    print(rot.rekursive_preorder_calculation())
    rot.rekursiv_inorder_formulaprint()
    print()
    print("\n Iterativ iteratortest")
    for element in rot:
        print(element)

Solutions

Expert Solution

Preorder Traversal in any binary tree means that we'll go in the order Root -> Left -> right

It generally means that we'll go first at the root node, then the left child and finally to the right child.

Since we've been asked to make preorder iterator so we can make the same with the help of the class which is

BinaryTreePreOrderIterator.

class BinarytreePreorderIterator:

    def __init__(self, tree):

        self.tree = tree

        self.stabel = []

        self.stabel.append((tree, 0))

    def __next__(self):

        while len(self.stabel) > 0:

            element = self.stabel.pop()

            if element[0].is_leafNode():

                return element[0].data

            if element[1] == 0:

                return element[0].data

            if element[1] == 1:

                self.stabel.append((element[0], 1))

                if element[0].right_child is not None:

                    self.stabel.append((element[0].right_child, 0))

            if element[1] == 2:

                self.stabel.append((element[0], 2))

                if element[0].left_child is not None:

                    self.stabel.append((element[0].left_child, 0))

        raise StopIteration

    def __iter__(self):

        return self

This is our solution for the given problem as in postOrder the order is Left child -> right Child -> root and in preOrder it is Root -> Left child -> Right Child.

Please comment and let me know if you have any doubts.

Thank you.

Have a good day.


Related Solutions

In Python, create a program with 2 classes that do the following. HashCreate class, this class...
In Python, create a program with 2 classes that do the following. HashCreate class, this class will accept a directory and hash each file in the directory and store the results in a dictionary. The dictionary will contain the hash value and file name. HashVerify, the second class will accept the dictionary as input and save that in an instance attribute. This class must also contain a method for lookups that require a file path as input. The lookup method...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value): pass    def pop(self): return None    def peek(self): pass    def is_empty(self): pass def stack(self): pass    def exch(self): pass    def index(self): pass    def clear(self): pass    def dup(self): pass    def equal(self): pass    def depth(self): pass    stack = PostScript() def decode(command_list): for object in command_list: if object == '=': stack.equal() elif object == 'count': stack.depth() elif object ==...
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)        &nb
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)               style = color                return    def plane(self,oil)              liquid = self.oil + self.truck(color) For the plane method, I am getting an error that the class does not define __add__ inside init so I cannot use the + operator. How do I go about this.             
Create a python program that prints the series from 5 to 500.
Create a python program that prints the series from 5 to 500.
Create a method on the Iterator class called forEach, which appropriate behavior. This method should use...
Create a method on the Iterator class called forEach, which appropriate behavior. This method should use next(), and should not use this._array.forEach! Take note of what should happen if you call forEach twice on the same Iterator instance. The estimated output is commented below In javascript please class Iterator { constructor(arr){ this[Symbol.iterator] = () => this this._array = arr this.index = 0 } next(){ const done = this.index >= this._array.length const value = this._array[this.index++] return {done, value} } //YOUR WORK...
In Python Find the errors, debug the program, and then execute to show the output. def...
In Python Find the errors, debug the program, and then execute to show the output. def main():     Calories1 = input( "How many calories are in the first food?")     Calories2 = input( "How many calories are in the first food?")     showCalories(calories1, calories2)    def showCalories():     print('The total calories you ate today', format(calories1 + calories2,'.2f'))
Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
This is using Python, it is utilizing code from a Fraction class to create a Binary...
This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this. Instruction for Binary Class: Exercise 6.18: Design an immutable class BinaryNumber, in the style of our Fraction class. Internally, your only instance variable should be a text string that represents the binary value, of the form '1110100'. Implement a constructor that takes a string parameter that specifies the original binary value....
Write a python program using the following requirements: Create a class called Sentence which has a...
Write a python program using the following requirements: Create a class called Sentence which has a constructor that takes a sentence string as input. The default value for the constructor should be an empty string The sentence must be a private attribute in the class contains the following class methods: get_all_words — Returns all the words in the sentence as a list get_word — Returns only the word at a particular index in the sentence Arguments: index set_word — Changes...
Create a Python script in IDLE or Kali Python3 CLI to create the following Python Program:...
Create a Python script in IDLE or Kali Python3 CLI to create the following Python Program: Your program will create a username of your choice using a Kali Linux command "useradd -m mark", then set the password for that user using the Kali Linux Command "echo "mark:10101111" | chpasswd". Then you create a dictionary file using the Kali Linux command "crunch 8 8 01 > mylist.txt" Your python script should crack the password for that user and display on the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT