calculate(self) A property method that evaluates the infix expression saved in self.__expr. First convert the expression to postfix, then use a stack to evaluate the output postfix expression. You must use the Stack defined in section 1 in this method, otherwise your code will not receive credit. Input (excluding self) str txt

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter18: Stacks And Queues
Section: Chapter Questions
Problem 1TF
icon
Related questions
Question
100%

In python please - all sections (there are 3 in total) except the last 3 pages included in the images, last section included in text below, thank you. Do not change the function names or given starter code in your script. Each class has different requirements, read them carefully and ask so I can comment to clarify. Do not use the exec or eval functions, nor are you allowed to use regular expressions. This includes multiple methods interacting with each other over the course of execution. All methods that output a string must return the string, not print it. If you are unable to complete a method, use the pass statement to avoid syntax errors. 

 

 

Last 3 pages continued -  

 

calculate(self) A property method that evaluates the infix expression saved in self.__expr. First convert the expression to postfix, then use a stack to evaluate the output postfix expression. You must use the Stack defined in section 1 in this method, otherwise your code will not receive credit. Input (excluding self)
str
txt
The string to check if it represents a number Output
float
The result of the expression
None
None is returned if the input is an invalid expression or if expression can’t be computed

 

Section 3: The AdvancedCalculator class
The AdvancedCalculator class represents a calculator that supports multiple expressions over many lines, as well as the use of variables. Lines will be split by semicolons (;), and every token will be separated by a single space. Each line will start with a variable name, then an ‘=’ character, then a mathematical expression. The last line will ask to return a mathematical expression too.
You can assume that an expression will not reference variables that have not been defined yet.
You can assume that variable names will be consistent and case sensitive. A valid variable name is a non-empty string of alphanumeric characters, the first of which must be a letter.
You must use a Calculator to evaluate each expression in this class, otherwise, no credit will be given.
Attributes Type Name Description
str
expressions
The expressions this calculator will evaluate
dict
states
A dictionary mapping variable names to their float values
Methods Type Name Description
bool
_isVariable(self, word)
Returns True if word is a valid variable name
str
_replaceVariables(self, expr)
Replaces all variables in an expression with values
dict
calculateExpressions(self)
Calculates all expressions and shows state at each step
>>> C = AdvancedCalculator()
>>> C.setExpression('A = 1;B = A + 9;C = A + B;A = 20;D = A + B + C;return D + 2 * B')
>>> C.states
{}
>>> C.calculateExpressions() # spacing added for readability
{'A = 1': {'A': 1.0},
'B = A + 9': {'A': 1.0, 'B': 10.0},
'C = A + B': {'A': 1.0, 'B': 10.0, 'C': 11.0},
'A = 20': {'A': 20.0, 'B': 10.0, 'C': 11.0},
'D = A + B + C': {'A': 20.0, 'B': 10.0, 'C': 11.0, 'D': 41.0},
'_return_': 61.0}
>>> C.states
{'A': 20.0, 'B': 10.0, 'C': 11.0, 'D': 41.0}

_isVariable(self, word) Determines if the input is a valid variable name (see above for rules for names). The string methods str.isalpha() and str.isalnum() could be helpful here. Input (excluding self)
str
word
The string to check if it is a valid variable name Output
bool
True if word is a variable name, False otherwise
_replaceVariables(self, expr) Replaces all variables in the input expression with the current value of those variables saved in self.states. Input (excluding self)
str
expr
The input expression that may contain variables Output
str
The expression with all variables replaced with their values
None
Nothing is returned if expression has invalid variables or uses a variable that has not been defined
calculateExpressions(self) Evaluates each expression saved in self.expressions. For each line, replace all variables in the expression with their values, then use a Calculator object to evaluate the expression and update self.states. This method returns a dictionary that shows the progression of the calculations, with the key being the line evaluated and the value being the current state of self.states after that line is evaluated. The dictionary must include a key named ‘_return_’ with the return value as its value. Hint: the str.split(sep) method can be helpful for separating lines, as well as separating the variable from the expression (for the lines that are formatted as var = expr). The str.strip() method removes the white space before and after a string. Don’t forget dictionaries are mutable objects! >>> 'hi;there'.split(';') ['hi', 'there'] >>> 'hi=there'.split('=') ['hi', 'there'] >>> ' hi there '.strip() ' hi there' Output
dict
The different states of self.states as the calculation progresses.
None
Nothing is returned if there was an error replacing variables

Section 2: The Calculator class
Section 2: The Calculator class
setExpr(self, new_expr)
Sets the expression for the calculator to evaluate. This method is already implemented for you.
Implement a class that calculates mathematic expressions. The input passed to this Calculator is in
infix notation, which gets converted to postfix internally, then the postfix expression is evaluated
Input (excluding self)
str new_expr The new expression (in infix) for the calculator to evaluate
(we evaluate in postfix instead of infix because of how much simpler it is). More details about
infix to postfix conversion can be found in the video lectures.
This calculator should support numeric values, five arithmetic operators (+, - *, /, ^), and
parenthesis. Follow the PEMDAS order of operations (you can define precedence of operators
with a dictionary or a helper method). Note that exponentiation is ** in Python.
getExpr(self)
Property method for getting the expression in the calculator. This method is already implemented
for you.
Output
You can assume that expressions will have tokens (operators, operands) separated by a single space.
For the case of negative numbers, you can assume the negative sign will be prefixed to the number.
The str.split) method can be helpful to isolate tokens. Expressions are considered invalid if they
str
The value stored in_expr
meet any of the following criteria:
• Contains unsupported operators
• Contains consecutive operators
• Has missing operands
• Has missing operators
• Has unbalanced parenthesis
• Tries to do implied multiplication
• Includes a space before a negative number
4 $ 5
isNumber(self, txt)
4 * + 5
Returns True if txt is a string that can be converted to a float, False otherwise. Note that the type
conversion float('4.56') returns 4.56 but float('4 56') raises an exception. A try/except
block could be useful here.
4 +
4 5
) 4 + 5 ( or ( 4 + 5 ) )
3(5) instead of 3 * (5 )
4 * - 5 instead of 4 * -5
Input (excluding self)
txt The string to check if it represents a number
str
Output
bool True if txt can be successfully casted to a float, False otherwise
Make sure to have proper encapsulation of your code by using proper variable scopes and writing
other helper methods to generalize your code for processes such as string processing and input
validation. Do not forget to document your code.
As a suggestion, start by implementing your methods assuming the expressions are always valid,
that way you have the logic implemented and you only need to work on validating the expressions.
_getPostfix(self, expr)
Converts an expression from infix to postfix. All numbers in the output must be represented as a
float. You must use the Stack defined in section 1 in this method, otherwise your code will not
receive credit. (Stack applications video lecture can be helpful here).
Input (excluding self)
expr The expression in infix form
Attributes
Туре
Description
The expression this calculator will evaluate
Name
str
str
expr
Output
The expression in postfix form
None None is
Methods
str
Name
setExpr(self, new_expr) Sets the expression for the calculator to evaluate
getExpr(self)
isNumber(self, aSring) Returns True if aSring can be converted to a float
_getPostfix(self, expr)
calculate(self)
|Туре
None
Description
returned if the input is an invalid expression
str
Getter method for the private expression attribute
bool
str
Converts an expression from infix to postfix
float
Calculates the expression stored in this calculator
Transcribed Image Text:Section 2: The Calculator class Section 2: The Calculator class setExpr(self, new_expr) Sets the expression for the calculator to evaluate. This method is already implemented for you. Implement a class that calculates mathematic expressions. The input passed to this Calculator is in infix notation, which gets converted to postfix internally, then the postfix expression is evaluated Input (excluding self) str new_expr The new expression (in infix) for the calculator to evaluate (we evaluate in postfix instead of infix because of how much simpler it is). More details about infix to postfix conversion can be found in the video lectures. This calculator should support numeric values, five arithmetic operators (+, - *, /, ^), and parenthesis. Follow the PEMDAS order of operations (you can define precedence of operators with a dictionary or a helper method). Note that exponentiation is ** in Python. getExpr(self) Property method for getting the expression in the calculator. This method is already implemented for you. Output You can assume that expressions will have tokens (operators, operands) separated by a single space. For the case of negative numbers, you can assume the negative sign will be prefixed to the number. The str.split) method can be helpful to isolate tokens. Expressions are considered invalid if they str The value stored in_expr meet any of the following criteria: • Contains unsupported operators • Contains consecutive operators • Has missing operands • Has missing operators • Has unbalanced parenthesis • Tries to do implied multiplication • Includes a space before a negative number 4 $ 5 isNumber(self, txt) 4 * + 5 Returns True if txt is a string that can be converted to a float, False otherwise. Note that the type conversion float('4.56') returns 4.56 but float('4 56') raises an exception. A try/except block could be useful here. 4 + 4 5 ) 4 + 5 ( or ( 4 + 5 ) ) 3(5) instead of 3 * (5 ) 4 * - 5 instead of 4 * -5 Input (excluding self) txt The string to check if it represents a number str Output bool True if txt can be successfully casted to a float, False otherwise Make sure to have proper encapsulation of your code by using proper variable scopes and writing other helper methods to generalize your code for processes such as string processing and input validation. Do not forget to document your code. As a suggestion, start by implementing your methods assuming the expressions are always valid, that way you have the logic implemented and you only need to work on validating the expressions. _getPostfix(self, expr) Converts an expression from infix to postfix. All numbers in the output must be represented as a float. You must use the Stack defined in section 1 in this method, otherwise your code will not receive credit. (Stack applications video lecture can be helpful here). Input (excluding self) expr The expression in infix form Attributes Туре Description The expression this calculator will evaluate Name str str expr Output The expression in postfix form None None is Methods str Name setExpr(self, new_expr) Sets the expression for the calculator to evaluate getExpr(self) isNumber(self, aSring) Returns True if aSring can be converted to a float _getPostfix(self, expr) calculate(self) |Туре None Description returned if the input is an invalid expression str Getter method for the private expression attribute bool str Converts an expression from infix to postfix float Calculates the expression stored in this calculator
Section 1: The Stack class
Section 1: The Stack class
This class represents the stack data structure discussed in this module. Use the implementation of
push(self, item)
Adds a new node with value=item to the top of the stack. Nothing is retuned by this method.
the Node class to implement a stack that supports the following operations.
Input (excluding self)
(any) item The value to store in a node
Make sure to update the top pointer accordingly as the stack grows and shrinks. You are not
allowed to use any other data structures for the purposes of manipulating elements, nor may you
use the built-in stack tool from Python. Your stack must be implemented as a Linked List, not a
Python list
pop(self)
Removes the top node from the stack and retums that node's value (not the Node object).
Attributes
Description
A pointer to the top of the stack
Output
(any) Value held in the topmost node of the stack
None Nothing is returned if the stack is empty
Туре
Name
Node
top
Methods
Description
Туре
None
|(any)
(any)
bool
Name
push(self, item) Adds a new node with value=item to the top of the stack
pop(self)
peek(self)
isEmpty(self)
Removes the top node and returns its value
Returns the value of the top node without modifying the stack
Returns True if the stack is empty, False otherwise
peek(self)
Returns the value (not the Node object) of the topmost node of the stack, but it is not removed.
Output
(any) Value held in the topmost node of the stack
None Nothing is returned if the stack is empty
Special methods
|Туре
Name
Description
isEmpty(self)
Returns the string representation of this stack
_repr_(self) Returns the same string representation as
str
_len_(self) Returns the length of this stack (number of nodes)
str
_str_(self)
Tests to see whether this stack is empty or not.
str
Output
bool True if this stack is empty, False otherwise
int
The Node class has already been implemented for you in the starter code and is described below.
_len_(self)
Do not modify the Node class.
Returns the number of elements in this stack.
Output
Attributes
int
The number of elements in this stack
| Туре Name
(any)
Node
Description
value
The value that this node holds
next
A pointer to the next node in the data structure
_str_(self), _rерг_(self)
Two special methos that return the string representation of the stack. This has already been
implemented for you, so do not modify it. If the class is implemented correctly,_str_ and
Туре
Name
Description
Returns the string representation of this node
_str_(self)
repr (self) Returns the same string representation as
str
repr_ display the contents of the stack in the format shown in the doctest.
str
str
Output
str
The string representation of this stack
Transcribed Image Text:Section 1: The Stack class Section 1: The Stack class This class represents the stack data structure discussed in this module. Use the implementation of push(self, item) Adds a new node with value=item to the top of the stack. Nothing is retuned by this method. the Node class to implement a stack that supports the following operations. Input (excluding self) (any) item The value to store in a node Make sure to update the top pointer accordingly as the stack grows and shrinks. You are not allowed to use any other data structures for the purposes of manipulating elements, nor may you use the built-in stack tool from Python. Your stack must be implemented as a Linked List, not a Python list pop(self) Removes the top node from the stack and retums that node's value (not the Node object). Attributes Description A pointer to the top of the stack Output (any) Value held in the topmost node of the stack None Nothing is returned if the stack is empty Туре Name Node top Methods Description Туре None |(any) (any) bool Name push(self, item) Adds a new node with value=item to the top of the stack pop(self) peek(self) isEmpty(self) Removes the top node and returns its value Returns the value of the top node without modifying the stack Returns True if the stack is empty, False otherwise peek(self) Returns the value (not the Node object) of the topmost node of the stack, but it is not removed. Output (any) Value held in the topmost node of the stack None Nothing is returned if the stack is empty Special methods |Туре Name Description isEmpty(self) Returns the string representation of this stack _repr_(self) Returns the same string representation as str _len_(self) Returns the length of this stack (number of nodes) str _str_(self) Tests to see whether this stack is empty or not. str Output bool True if this stack is empty, False otherwise int The Node class has already been implemented for you in the starter code and is described below. _len_(self) Do not modify the Node class. Returns the number of elements in this stack. Output Attributes int The number of elements in this stack | Туре Name (any) Node Description value The value that this node holds next A pointer to the next node in the data structure _str_(self), _rерг_(self) Two special methos that return the string representation of the stack. This has already been implemented for you, so do not modify it. If the class is implemented correctly,_str_ and Туре Name Description Returns the string representation of this node _str_(self) repr (self) Returns the same string representation as str repr_ display the contents of the stack in the format shown in the doctest. str str Output str The string representation of this stack
Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps

Blurred answer
Knowledge Booster
Stack operations
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning