Implements the binary tree as a class

Assignment Help Python Programming
Reference no: EM131258353

Python Assignment

Problem Description

The project so far supports calculations on numeric values, but most computational statements (and even most calculators) are not limited to numeric literal values. They usually also include variables.

So this assignment will add the ability to assign to variables, and then to later use their values in further computations. This will require a data structure that will associate variables with values, and to do that efficiently, will use a binary search tree.

Parsing and Interpretation

There will be one additional operator for this homework -- the sasignment operator ('='). We will support the C++ meaning of this operator, that not only assigns to a variable, but 'computes' the assigned value. The assignment operator has the lowest precedence (be aware of what that means for the order of calling functions when parsing.

Here are a few examples:

x = 1 + (y = 4) # assign 4 to y and 5 to x
x = y = z = 4 # assign 4 to z, then y, then x
x = y = z + 4 # add 4 to z, then assign sum to y and x
x = 1 + y = 4 # invalid input: cannot assign 4 to (1+y)

Special Note:

It may be tempting to make the function for assignment operator to be just like the ones for sum and product. That would not be correct, because it would do the operations from left to right. HOWEVER: it can be fixed just by changing the name of one function call within the new while loop. Furthermore, if you do so correctly, the while loop would only repeat 0 or 1 times, so the word 'while' could optionally be replaced with a different word.

The postfix forms for the legal expression would be similar to the other operators:

x 1 y 4 = + = # assign 4 to y, add 1 to it, then assign 5 to x
x y z 4 = = = # assign 4 to z, then y, then x
x y z 4 + = = # add 4 to z, then assign sum to y and x

A binary search tree will be used when evaluating the postfix expression. If a variable is the left operand of an assignment, the variable will receive the value. If a variable appears at any other time, its value is retrieved for a computation.

That means that the postfix evaluation function's stack of 'values' will now have a mixture of values and variable names, and will need to be able to know the difference and use the information appropriately.

HINT: The instructor discovered that if value = '0.3', value.isdigit() is False. It is safer to check value[0].isdigit(). That will let you more reliably identify whether the stack element is a variable or a number.

Defining a Binary Tree

There is no need for any self-balancing features in this assignment -- just the a simple binary tree supporting the ability to store new variables, to associate values with those variables, and to retrieve the value of a variable.

For consistency, call your file vartree.py

Required Features in Implementation

Nested Node class definition

for binary tree node

  with __slots__

to save list memory

  and __init__

a constructor

__init__()

a constructor for an empty tree

_search(here, var)

recursively search tree rooted 'here' for variable 'var' 
returning correct Node, or None if not found

_insert(here, var, value)

return a search tree with variable inserted or updated 
this should be a recursive implementation for immutable behavior

assign(var, value)

public method to assign to a variable

lookup(var)

public method retrieve value of variableif the variable does not yet exist, assign it zero

Good functions for Completeness / Practice

is_empty()

Identify whether tree is empty

__len__()

returns number of elements in list

__iter__()

inorder iterator generator(with yield statements)

__str__()

represents entire tree as a string 
For full credit, this must be no worse than log-linear time and not quadratic

Assignment Specifications

One new file and three modified files are to appear in the solution to this assignment:

vartree.py

Implements the binary tree above as a class

newsplit.py

divides into tokens, generating an iterator, with added support for variable names

infixtoiter.py

given an iterator to an infix expression, produces an iterator generator for a postfix expression, with added support for variables and =

evalpostfix.py

evaluates a postfix expression, given an iterator, with added support for variables

That module will have its own variable to hold all of those variables

You are also encouraged to insert your own unit testing into each file, but that will not be itself graded.

Testing and Evaluation

Here are a few lines of code from the instructor's solution and test at this time of writing:

(in the test program)

from infixtoiter import to_postfix
from evalpostfix import eval_postfix

def test(expr):
print (expr, ':', eval_postfix( to_postfix( expr )) )

test("b=6") # b=6 : 6
test("b * 9") # b * 9 : 54

You may assume that all expressions are legal C expressions with binary operators, but you may NOT assume that:

• All numbers are single digits -- this assumption was not permitted before either
• All variables are single letters -- they may include multiple letters (and maye digits)
• All variables are assigned before use -- if not yet assigned, assign zero.

Reference no: EM131258353

Questions Cloud

What other factors influence the office location decision : Which coordinates represent a good central location for this office? What other factors might influence the office location decision? Where would you place this office? Explain
Benefits measuring the health status of individuals : What are the benefits measuring the health status of individuals aged fifteen to sixty four years in a particular community or an entire population? What effect do these benefits have on the health status of the community or the entire population?
Demonstrates cultural sensitivity in communication : NUR 502 - Theoretical Foundations for Nursing Roles and Practice - Write a paper of 1,000-1,250 words on a specific cultural group and select one article from a nursing journal focused on a cultural group.
Major forms of workforce diversity : 1. What are the two major forms of workforce diversity? 2. What are stereotypes and how do they function in organizational settings? 3. What are the key biographical characteristics and how are they relevant to OB?
Implements the binary tree as a class : Implements the binary tree above as a class. Divides into tokens, generating an iterator, with added support for variable names. Evaluates a postfix expression, given an iterator, with added support for variables.
Detect a negative cycle using the predecessor indices : Suppose that the Floyd-Warshall algorithm terminates after detecting the presence of a negative cycle. At this time, how would you detect a negative cycle using the predecessor indices?
Differences between individualism and collectivism : 1) How do the differences between individualism and collectivism affect the working relationships between the Japanese and the Americans? 2) How do the Japanese and the Americans in the movie differ in terms of high and low context styles?
What are the coordinates of the central location : What are the coordinates of the central location? - What other factors should be considered before building a school?
Tort of intentional infliction of emotional distress : i. As the store manager, it is up to you to explain Contracts 101 to the brothers. What arguments can you make for why your store should not have to sell them a $2,250.00 TV for $22.50? Explain. ii. Could Best Buy be liable when the brothers sue ..

Reviews

Write a Review

Python Programming Questions & Answers

  Write a program in python to draw a simplified face

Write a program in Python to draw a blue triangle in a drawing window. Write a program in Python that moves the triangle in an animated movement. Write a program in Python to draw a simplified face.

  Calculate the area of a rectangle and displays it

Write a python program that calculates the area of a rectangle and displays it - Display the variables length, width and area on screen using the print function

  The program should use a boolean= valued function

Write a program that accepts a word as input and determines wehther or not it has three consecutive letters in the alphabet. The program should use a Boolean= valued function named isTripleConsecutive that accepts an entire word as input.

  Code a console-based program in python

CP1404/CP5632 2016 SP2/22/52 Assignment 1 - Shopping List 1.0. You are to plan and then code a console-based program in Python 3, as described in the following information and sample output. This assignment will help you build skills using selectio..

  Write program that read a text file and prints only odd line

Write a program that reads a text file and prints out only odd lines to the screen. Thus, lines 1, 3, 5,... only printed. Update your odd lines program (Q1) to write odd lines to the screen and write then lines to another file.

  Write a program that obtains integer numbers from user

Emphasize standard approaches that verify you have successfully mastered the concepts of structured design - selects a menu item, program should perform calculation, display the result to the user, and return to the main menu.

  Modify your code to ask the user for the id of a restaurant

Copy check1.py to check2.py and continue to work on check2.py. Modify your code to ask the user for the id of a restaurant between 1 and 155 (humans don't need to know about list ids starting at 0).

  Write a program that accepts as input a sentence

Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by space and only the first word start..

  Displays the charges for a patients hospital stay

Write a program that computes and displays the charges for a patient's hospital stay. First, the program should ask patient name and if the patient was admitted as an in-patient or an out-patient.

  Implement the sieve of eratosthenes

Implement the Sieve of Eratosthenes and use it to find all prime numbers less than or equal to one million. Use the result to prove Goldbach's Conjecture for all even integers between four and one million, inclusive.

  Segment that prompts the user for an arithmetic operator

The variables x and y refer to numbers. Write a code segment that prompts the user for an arithmetic operator and prints the value abtained by appying that operator to x and y.

  Function should return a dictionary

Write a function numOccur(s), where s is a string; the function should return a dictionary whose keys are the 26 ascii letters abcdefghijklmnopqrstuvwxyz

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd