Question: I had to a make a python function to be a single line calculator and we have to add exponents in along with a stack
I had to a make a python function to be a single line calculator and we have to add exponents in along with a stack to do other operations like parentheses and negatives. Refer to pdfs for full assignment.This is due this Friday, July 13, 2018.





class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__ = __str__
class Stack:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def __str__(self):
temp = self.head
out = ''
while temp:
out += str(temp.value)+ ' '
temp = temp.next
return ('Head:{} Tail:{} List:{}'.format(self.head,self.tail,out))
__repr__=__str__
def add(self, value):
addN = Node(value)
if self.head is None:
self.head = addN
self.tail = addN
self.count += 1
return
elif self.head.value >= addN.value:
addN.next = self.head
self.head = addN
else:
cur = self.head
while(cur.next is not None and
cur.next.value
cur = cur.next
addN.next = cur.next
cur.next = addN
self.count += 1
temp = self.head
while(temp.next is not None):
temp = temp.next
self.tail = temp
def pop(self):
value_P = ''
if self.isEmpty():
return 'List is Empty'
if self.head.next == None:
value_P = self.head.value
self.head = None
self.tail = None
self.count -= 1
return value_P
temp1 = self.head
temp2 = None
while temp1.next is not None:
temp2 = temp1
temp1 = temp1.next
value_P = temp1.value
self.count -= 1
temp2.next = None
self.tail = temp2
return value_P
def isEmpty(self):
if self.head == None:
return True
else:
return False
def size(self):
count = 0
Cnode = self.head
while Cnode is not None:
count = count + 1
Cnode = Cnode.next
return count
def findNextOpr(txt):
if len(txt)
print("type mimatch error: findNextOpr")
return -1
elif txt.find("+") != -1 or txt.find("-") != -1 or txt.find("*") != -1 or txt.find("/") != -1 or txt.find("^") != -1:
for i in range(len(txt)):
index_val = txt[i]
if(index_val == "+" or index_val == "-" or index_val == "*" or index_val == "/" or index_val == "^"):
return i
break
else:
return -1
def isNumber(txt):
if len(txt) == 0 or not isinstance(txt, str):
print("type mismatch error: isNumber")
return False
else:
if txt[0] == "-":
txt = txt[1:]
try:
float(txt)
return True
except ValueError:
return False
def getNextNumber(expr, pos):
if len(expr) == 0 or not isinstance(expr, str) or pos len(expr) or not isinstance(pos, int):
return None, None, "type mismatch error: getNextNumber"
else:
next_num = None
next_opr = None
nex_opr_pos = None
nex_opr_pos = findNextOpr(expr[pos:])
if nex_opr_pos > 0:
nex_opr_pos += pos
next_opr = expr[nex_opr_pos]
if isNumber(expr[pos:nex_opr_pos]):
next_num = float(expr[pos:nex_opr_pos])
else:
next_opr = None
if isNumber(expr[pos:]):
next_num = float(expr[pos:])
return next_num, next_opr, nex_opr_pos
def exeOpr(num1, opr, num2):
#This funtion is just an utility function. It is skipping type check
if opr=="+":
return num1+num2
elif opr=="-":
return num1-num2
elif opr=="*":
return num1*num2
elif opr=="/":
if num2==0:
print("Zero division error")
return "Zero division error"
else:
return num1um2
elif opr=="^":
return num1 ** num2
else:
print("error in exeOpr")
return "error in exeOpr"
def _calculator(expr):
pos = 0
posi = 1
next_opr = 0
result = 0
mode_change = None
addlastOpr = None
mullastOpr = None
explastOpr = None
if not isinstance(expr,str) or len(expr)
return "argument error: line A in eval_expr"
expr = expr.strip()
if expr[0]!="-":
newNumber, newOpr, oprPos = getNextNumber(expr, 0)
else:
newNumber, newOpr, oprPos = getNextNumber(expr, 1)
newNumber *= -1
if newNumber is None:
return "input formula error: line B in eval_expr"
elif newOpr is None:
return newNumber
elif newOpr == "+" or newOpr == "-":
mode = "add"
addResult = newNumber
mulResult = 1
expResult = 0
addlastOpr=newOpr
elif newOpr == "*" or newOpr == "/":
mode = "mul"
addResult = 0
mulResult = newNumber
expResult = 0
mullastOpr = newOpr
elif newOpr=="^":
mode="exp"
addResult=0
mulResult=1
addLastOpr="+"
mulLastOpr="*"
expNumber=newNumber
while True:
newNumber, newOpr, oprPos = getNextNumber(expr, oprPos + 1)
if newNumber is None:
return "input formula error: line B in eval_expr"
elif newOpr is None and mode=="add":
return exeOpr(addResult, addlastOpr, newNumber)
elif newOpr is None and mode =="mul":
mulResult=exeOpr(mulResult,mullastOpr,newNumber)
return exeOpr(addResult, addlastOpr, mulResult)
elif newOpr is None and mode=="exp":
expResult = exeOpr(expNumber, explastOpr, newNumber)
mulResult = exeOpr(mulResult, mulLastOpr, expResult)
return exeOpr(addResult, addLastOpr, mulResult)
elif (newOpr=="+" or newOpr=="-") and mode=="exp":
expResult = exeOpr(expNumber, newOpr, newNumber)
mulResult = exeOpr(mulResult, mulLastOpr, expResult)
addResult = exeOpr(addResult, addLastOpr, mulResult)
mode="add"
elif (newOpr=="*" or newOpr=="/") and mode=="exp":
expResult = exeOpr(expNumber, newOpr, newNumber)
mulResult = exeOpr(mulResult, mulLastOpr, expResult)
mode = "mul"
elif (newOpr == "+" or newOpr =="-") and mode == "add":
addResult=exeOpr(addResult, addlastOpr, newNumber)
addlastOpr=newOpr
mode = "add"
elif (newOpr == "*" or newOpr == "/") and mode == "add":
mulResult=newNumber
mullastOpr = newOpr
mode="mul"
elif newOpr=="^" and mode=="add":
addLastOpr = newOpr
mulResult = 1
mulLastOpr = "*"
expNumber= newNumber
mode = "exp"
elif (newOpr == "+" or newOpr == "-") and mode == "mul":
mulResult=exeOpr(mulResult,mullastOpr, newNumber)
if addlastOpr is None:
addResult= mulResult
else:
addResult=exeOpr(addResult, addlastOpr, mulResult)
addlastOpr=newOpr
mode="add"
elif (newOpr == "*" or newOpr=="/") and mode == "mul":
mulResult=exeOpr(mulResult, newOpr, newNumber)
mode="mul"
mullastOpr=newOpr
elif (newOpr == "^") and mode == "mul":
mode = "exp"
expResult=newNumber
explastOpr = newOpr
def calculator(expr):
# Required: calculator must create and use a Stack for parenthesis matching
# Call _calculator to compute the inside parentheses
if len(expr)
print("argument error: calculator")
return "argument error: calculator"
expr = expr.strip()
s = Stack() # You must use the Stack s
pos = expr.find("(")
while True:
#--- function code starts here -----#
#--- function code ends here-----#
CNMPSC-122: Intermediate Programming Summer 2018 Homework 2 Due Date: 06/22/2018, 11:59PMEST 100 pts Instructions: The work in this assignment st be completed alone. The file name nust be HW2.py (incorrect name files will get a -10 point deduction) When any function returns an error, it nust be a string containing "error" Do not include test code outside any function in the upload. Remove all your testing code before uploading your file. That inchudes user-defined inputO Goal Modify the function calculator(expr) so that t supports exponentiation This operation will be represented in the string as ^unlike Python's **. In this assignment, more than one consecutive exponentiation is not supported. An example ofa valid expression is -5 60/3A3 * 4 2* 42" Notes This is a straightforward upgrade of HW1 and there is no starter code You will also have to modify findNextOpr and exeOpr to include (which is* in Python) In your submission include all functions in your HW2 py script (calculator, findNextOpr isNumber, getNextNumber and exeOpr) Function requirements: The function must return the computed value if expr is a correct formula, otherwise it must retun an error message When any function returns a numeric value, it ust be float Do not use exec or eval function, You will not receive credit if All five functions from HW1 nust work Grading Notes: your program uses any of the two functions anyw here The grading script will feed 5 randomly chosen test inputs, each for 20 points. One of them will be an input that should cause an error such as "4 * / 2 + 5 ^, whose expected returned value is an error message. Example: calculator("-5 + 60 / 3"3 4-2 * 4"2") >>> calculator ("42/22") >>> calculator ("-4 /22") error Deliverables: Include all the functions in your script named HW2 py. Submit it to the HW2 CANVAS assignment before the due date
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
