Your task is to implement a simplified prefix calculator in Python. An expressio
ID: 3793725 • Letter: Y
Question
Your task is to implement a simplified prefix calculator in Python.
An expression is written in prefix notation when the operator is written before the operands.
Your calculator will accept and evaluate expressions that contain a single operator followed by an arbitrary number of operands. Operands may be integers or floating point numbers, separated by an arbitrary number of space characters.
The operators are: + (for addition), - (for subtraction), * (for multiplication) and / (for division).
Your calculator must also accept and ignore input that starts with # (comments).
The program must exit when the user enters 'q'.
The starter file provided includes support for addition and simple error handling. Your task is to add support for -, *, / and #.
For example:
+ 5 3 2 1 is (5 + 3 + 2 + 1)
* 3 4 2 is (3 * 4 * 2)
/ 100 5 4 2 is (((100 / 5) / 4) / 2)
- 1 10 2 3 is (((1 - 10) -2) - 3)
Here is a sample run:
CS 152 >>>+ 10 20
30
CS 152 >>>+ 5 3 2 1
11
CS 152 >>>* 2 3.1
6.2
CS 152 >>>* 3 4 2
24
CS 152 >>>* 1 2 3 4 5 6
720
CS 152 >>>- 10 2.5
7.5
CS 152 >>>- 1 10 2 3
-14
CS 152 >>>/ 100 5
20.0
CS 152 >>>/ 100 5 4
5.0
CS 152 >>># this is just a comment
CS 152 >>>
CS 152 >>>89
Error: expected # or * or + or - or /, got 89
Please enter a valid expression in prefix notation or q to quit
CS 152 >>>& 3 4 5
Error: expected # or * or + or - or /, got &
Please enter a valid expression in prefix notation or q to quit
CS 152 >>>9 + 2
Error: expected # or * or + or - or /, got 9
Please enter a valid expression in prefix notation or q to quit
CS 152 >>>
CS 152 >>>+
0
CS 152 >>>-
0
CS 152 >>>/
0
CS 152 >>>*
0
CS 152 >>>#
CS 152 >>>+ 7
7
CS 152 >>>- 9
9
CS 152 >>>* 4
4
CS 152 >>>/ 8
8
CS 152 >>>/ 8 0
Error: expected non zero operand, got 0
Please enter a valid expression in prefix notation or q to quit
CS 152 >>>/ 8 4 0 2
Error: expected non zero operand, got 0
Please enter a valid expression in prefix notation or q to quit
CS 152 >>>q
Exiting the CS 152 Calculator
Calculator.py:
def subtract():
def divide():
def multiply():
Explanation / Answer
def add(operands):
result = 0
for each_operand in operands:
each_value = get_value(each_operand)
if each_value is not None:
result += each_value
else:
return 0
return result # Return the sum.
def subtract(operands):
if(len(operands) == 0):
result = 0
else:
result = get_value(operands[0])
for each_operand in operands[1:]:
each_value = get_value(each_operand)
if each_value is not None:
result -= each_value
else:
return
return result
def divide(operands):
if(len(operands) == 0):
result = 0
else:
result = get_value(operands[0])
for each_operand in operands[1:]:
each_value = get_value(each_operand)
if each_value is not None:
try:
result /= each_value
except ZeroDivisionError:
error1()
return
else:
return
return result
def multiply(operands):
if(len(operands) == 0):
result = 0
else:
result = 1
for each_operand in operands:
each_value = get_value(each_operand)
if each_value is not None:
result *= each_value
else:
return 0
return result
SUPPORTED_OPERATORS = {'+': add, '-': subtract, '/':divide, '*':multiply}
SUPPORTED_SYMBOLS = sorted(SUPPORTED_OPERATORS.keys())
def evaluate(expression):
operands = []
if not expression:
return
result = None
tokens = expression.split()
operator = tokens[0]
operands = tokens[1:]
if operator in SUPPORTED_OPERATORS:
function_name = SUPPORTED_OPERATORS[operator]
result = function_name(operands)
else:
expected_operators = ' or '.join(SUPPORTED_SYMBOLS)
error(expected_operators, operator)
if result is not None:
print(result)
def get_value(a_string):
try:
value = int(a_string)
except ValueError:
try:
value = float(a_string)
except ValueError:
error('number', a_string)
return
return value
def error(expected, error):
print("Error: expected {}, got {}".format(expected, error))
print('Please enter a valid expression in prefix notation or q to quit')
def error1():
print('Error: expected non zero operand, got 0')
print('Please enter a valid expression in prefix notation or q to quit')
def main():
more_input = True
while more_input:
expression = input("CS 152 >>>")
if expression == 'q':
more_input = False
print('Exiting the CS 152 Calculator')
elif '#' in expression:
more_input = True
else:
evaluate(expression)
if __name__ == '__main__':
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.