Click here to Skip to main content
14,843,569 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a project in python. It is a prefix calculator that takes in multiple operands and multiple operators. I have been able to solve the project for a single operator and two operands. This is quite difficult. Need help:
Note that for the operator must be inputed first before the operands, hence the name prefix calculator. Thanks

What I have tried:

<pre>def prefix(input):
    op, num1, num2 = input.split(" ")
    num1 = int(num1)
    num2 = int(num2)
    if op == "+":
        return num1 + num2
    elif op == "*":
        return num1 * num2
    elif op == "-":
        return num1 - num2
    elif op == "/":
        return num1 * num2
    else:
        return 0

def repeat():
    x = input("Enter calculation in prefix notation: ")
    y = prefix(x)
    print(y)
    if y == "x":
        print("Goodbye")
    else:
        repeat()
        
repeat()
Posted
Updated 31-Oct-20 13:53pm

Look at your code: prefix returns 0 if the operator is not found, and will never return "x" - you compare the result to x and expect it to match!

I'd suggest adding "x" as an operator that returns "exit" and check for that instead.
   
Quote:
I am making a project in python. It is a prefix calculator that takes in multiple operands and multiple operators.

No matter the details, evaluating a mathematical expression involve a recursive approach in a fashion or another.
The expression is made of an arbitrary number of elements and evaluating it consist of repeatedly find a triplet (operator, number, number) and replace it by its result until there is no more triplet. You duty is to design the code accordingly.
+ 1 + 2 4 => + 1 6 => 7
+ + 1 2 4 => + 3 4 => 7


This code is recursive when a simple loop is enough:
Python
def repeat():
    x = input("Enter calculation in prefix notation: ")
    y = prefix(x)
    print(y)
    if y == "x":
        print("Goodbye")
    else:
        repeat()
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900