PYTHON:
Please help me fix my code. It was supposed to ask the user to input an inorder traversal and let them choose whether to enter postorder or preorder, then identify the order of the missing traversal, just like the image below. However, my code can only identify the POSTORDER traversal but not the PREORDER. There is something wrong with my def function on def PreOrderT(). Please help me fix it. Thank you.
# Main program
inorder_list = []
preorder_list = []
postorder_list = []
n = int(input("How many nodes want to enter? "))
# Methods
def searchR(arr, x, n): # CHANGED THE NAME OF FUNCTION AS THERE ARE TWO FUNCTION WITH SAME NAME
for i in range(n):
if (arr[i] == x):
return i
return -1
def PostOrderT(Ino, preo, n):
root = searchR(Ino, preo[0], n)
if (root != 0):
PostOrderT(Ino, preo[1:n], root)
if (root != n - 1):
PostOrderT(Ino[root + 1:n], preo[root + 1:n], n - root - 1)
print(preo[0], end=" ")
# Make new node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Construct binary tree
def MakeTree(Ino, posto, inoStrt, inoEnd, p_Index):
if (inoStrt > inoEnd):
return None
node = newNode(posto[p_Index[0]])
p_Index[0] -= 1
if (inoStrt == inoEnd):
return node
iIndex = search(Ino, inoStrt, inoEnd, node.data)
node.right = MakeTree(Ino, posto, iIndex + 1, inoEnd, p_Index)
node.left = MakeTree(Ino, posto, inoStrt, iIndex - 1, p_Index)
return node
def bTree(Ino, posto, n):
p_Index = [n - 1]
return MakeTree(Ino, posto, 0, n - 1, p_Index)
def search(arr, astrt, aend, value):
i = 0
for i in range(astrt, aend + 1):
if (arr[i] == value):
break
return i
def PreOrderT(node):
if node == None:
return
print(node.data, end=" ")
PreOrderT(node.left)
PreOrderT(node.right)
print("Enter INORDER:")
for i in range(0, n):
ele = input().split()
if len(ele) == n:
for i in ele:
inorder_list.append(i) # adding the element
break
elif len(ele) > n:
print("You have entered more nodes")
break
else:
print("You have entered less nodes")
break
print(inorder_list)
print("\nWould you like to use Preorder or Postorder?")
choice = int(input("Press [1] for PREORDER and Press [2] for POSTORDER>> "))
if choice == 1:
print("Enter PREORDER: ")
for i in range(0, n):
ele = input().split()
if len(ele) == n:
for i in ele:
preorder_list.append(i) # adding the element
break
elif len(ele) > n:
print("You have entered more nodes")
break
else:
print("You have entered less nodes")
break
print(preorder_list)
print("\nMissing Traversal Identified!")
print("POSTORDER traversal: ")
bTree(inorder_list, preorder_list, n) # NEED TO BUILD THE TREE FIRST
PostOrderT(inorder_list, preorder_list, n) # CALLING CORRECT FUNCTION
elif choice == 2:
print("Enter POSTORDER: ")
for i in range(0, n):
ele = input().split()
if len(ele) == n:
for i in ele:
postorder_list.append(i) # adding the element
break
elif len(ele) > n:
print("You have entered more nodes")
break
else:
print("You have entered less nodes")
break
print(postorder_list)
print("\nMissing Traversal Identified!")
print("PREORDER traversal: ")
PostOrderT(inorder_list, preorder_list, n)
else:
print("Invalid choice")
Step by stepSolved in 3 steps with 1 images
- In c++arrow_forwardWrite a program named stars.py that has two functions for generating star polygons. One function should be implemented using an iteration (a for loop), and another function should be a recursion. It is optional to fill in your shapes. The functions for generating stars should be named star (size, n, d=2) and star_recursive (size, n, level, d=2), where size is the size of the polygon side (edge), n is the number of sides (or angles), d is a density or winding number that should be set to default value 2, and level is the level of recursion initially equal to n.arrow_forwardIn Python, with use of function and input parsing/ Make a method is_anagram_of(a,b) that tests if a is an anagram of b. A string a is an anagram of a string b, if it uses exactly the same letters, but the order can be different. Spaces are ignored, as well as capitalization. Examples of anagrams: "eleven plus two" - "twelve plus one" "William Shakespeare" - "I am a weakish speller" "Tom Marvolo Riddle" - "I am Lord Voldemort" "Anagrams" - "Ars manga" "television ads" - "enslave idiots" Counter examples: "bla" - "aalb" "cat" - "tact" Hint: Make a dictionary that holds how often a letter occurs in a word.arrow_forward
- Python 3.0arrow_forwardCan you answer the following questions in python using matplot.pyplot as pltarrow_forwardHello! I need some help with my Java homework. Please use Eclipse Please add comments to the to program so I can understand what the code is doing and learn Create a new Eclipse project named so as to include your name (eg smith15 or jones15). In this project, create a new package with the same name as the project. In this package, write a solution to the exercise noted below. Implement the following method that returns the maximum element in an array: public static <E extends Comparable<E>> E max(E[] list) Write a test program that generates 10 random integers, invokes this method to find the max, and then displays the random integers sorted smallest to largest and then prints the value returned from the method. Max sure the the last sorted and returned value as the same!arrow_forward
- Regex, APIs, BeautifulSoup: python import requests, refrom pprint import pprintfrom bs4 import BeautifulSoup complete the missing bodies of the functions below: def mathmatic(target):"""Question 1You are doing fun math problems. Given a string of combination of '{}', '[]','()', you are required to return the substring included by the outermost '{}'.You need to write your code in one line.Args:target (str): the string to search inReturns:str>>> mathmatic('{[[[[]()]]]}')'[[[[]()]]]'>>> mathmatic('[(){([{}])}]')'([{}])'"""pass test code: # print(mathmatic('{[[[[]()]]]}'))# print(mathmatic('[(){([{}])}]'))arrow_forwardplease write in python languag and by end include the output to make sure it works. thanks Template: # imports def draw_bounds(size, center=(0, 0)): """This function shall draw a square with the given dimension (i.e. size parameter) around a given starting point (i.e. center parameter). NOTE: The turtle must return to the starting point/center position and its initial orientation after drawing the square""" def step(step_size=20): """This function shall implement a single step in the random walk. The turtle moves by the given step_size in a randomly chosen direction i.e. North, South, East or West""" def walk(limits=(-200, 200)): """This function shall iteratively invoke the step function to implement the random walk until the turtle reaches a boundary (i.e. defined by the given limits). Additionally, this function must return the number of steps taken.""" if __name__ == '__main__': ...arrow_forwardThe following requirments that weren't mentioned for solving the following Python Code below: The provided code for alphabet, test_dups, test_miss, and histogram. Your implementation of the has_duplicates function. A loop that outputs duplicate information for each string in test_dups. Your implementation of the missing_letters function. A loop that outputs missing letters for each string in test_miss. Write a function called missing_letters that takes a string parameter and returns a new string with all the letters of the alphabet that are not in the argument string. The letters in the returned string should be in alphabetical order. Your implementation should use a histogram from the histogram function. It should also use the global variable alphabet. It should use this global variable directly, not through an argument or a local copy. It should loop over the letters in alphabet to determine which are missing from the input parameter. The function missing_letters should…arrow_forward
- Can this python code be done without using the isdigit() function. Please try to change the following code in the picture so it doesn't use isdigit().arrow_forwardComplete the rotate_text() function that takes 2 parameters, a string data and an integer n. If n is positive, then the function will shift all the characters in data forward by n positions, with characters at the end of the string being moved to the start of the string. If n is 0 then the text remains the same. For example: rotate_text('abcde', rotate_text('abcde', rotate_text('abcde', 1) would return the string 'eabcd' 3) would return the string 'cdeab' 5) would return the string 'abcde' rotate_text('abcde', 6) would return the string 'eabcd' ... and so on. If n is negative, then the function will shift the characters in data backward by n positions, with characters at the start of the string being moved to the end of the string. For example: rotate text('abcde', -1) would return the string 'bcdea'arrow_forwardPython Turtle: How do I fix the code to make it generate lakes as bigger random dots, and mountains as a separate color (gray) from the grass area? (Big error: lake generates as entire circle inside land, want it generating like mountains).AKA: How do I separate each of the values to generate on its own without conflicting eachother. import turtleocean = "#000066"sand = "#ffff66"grass = "#00cc00"lake = "#0066ff"mountain = [[-60, 115], [-65, 200], [-10, 145], [-30, 70], [50, 115], [100, 150], [70, 200], [30, 70], [10, 180], [-10, 220]]def draw_circle(radius, line_color, fill_color): my_turtle.color(line_color) my_turtle.fillcolor(fill_color) my_turtle.begin_fill() my_turtle.circle(radius) my_turtle.end_fill()def move_turtle(x, y): my_turtle.penup() my_turtle.goto(x, y) my_turtle.pendown()num_cuts = int(input("How many rivers do you want on your Island? ")) screen = turtle.Screen()screen.bgcolor(ocean)screen.title("Island Generator")my_turtle =…arrow_forward
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY