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 ==...
Python 3.7: Give the following sample code, write the following programs: • An iterator class called...
Python 3.7: Give the following sample code, write the following programs: • An iterator class called Iteratefirstn that implements __iter__() and __next__() methods where next method should raise an exception for the cur index if it is passed the last element otherwise set cur index to the next index and advance the index by one, i.e. cur, num = num, num+1. Instantiate the class to calculate the sum of 1000000 elements similar to the example. • Instead of implementing the...
Copy the following Python fuction discussed in class into your file: from random import * def...
Copy the following Python fuction discussed in class into your file: from random import * def makeRandomList(size, bound): a = [] for i in range(size): a.append(randint(0, bound)) return a a. Add another function that receives a list as a parameter and computes the sum of the elements of the list. The header of the function should be def sumList(a): The function should return the result and not print it. If the list is empty, the function should return 0. Use...
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.             
IN PYTHON create a python program that accepts input from the user in the following sequence:...
IN PYTHON create a python program that accepts input from the user in the following sequence: 1. Planet Name 2. Planet Gravitational Force(g) for data, use the planets of our solar system. The data input is to be written in 2 separate lists, the names of which are: 1. planetName 2. planet GravitationalForce(g) A third list is required that will store the weight of a person with mass of 100kg, the formula of which is: W=mg(where m is mass of...
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...
Create a python program that prints the series from 5 to 500.
Create a python program that prints the series from 5 to 500.
Python class LinkedNode: # DO NOT MODIFY THIS CLASS # __slots__ = 'value', 'next' def __init__(self,...
Python class LinkedNode: # DO NOT MODIFY THIS CLASS # __slots__ = 'value', 'next' def __init__(self, value, next=None): """ DO NOT EDIT Initialize a node :param value: value of the node :param next: pointer to the next node in the LinkedList, default is None """ self.value = value # element at the node self.next = next # reference to next node in the LinkedList def __repr__(self): """ DO NOT EDIT String representation of a node :return: string of value """...
Python program please no def, main, functions Given a list of negative integers, write a Python...
Python program please no def, main, functions Given a list of negative integers, write a Python program to display each integer in the list that is evenly divisible by either 5 or 7. Also, print how many of those integers were found. Sample input/output: Enter a negative integer (0 or positive to end): 5 Number of integers evenly divisible by either 5 or 7: 0 Sample input/output: Enter a negative integer (0 or positive to end): -5 -5 is evenly...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT