Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepython
# rpncalc3.py
operands = []

def isOperand(token):
    try:
        float(token)
        return True
    except ValueError:
        return False

def printOperands():
    print(operands)

def popOperands(n):
    size = len(operands)
    if size >= n:
        result = operands[size - n : size]
        global operands
        operands = operands[0 : size - n]
        return result
    else:
        return None

def pushOperand(operand):
    operands.append(operand)

def plus():
    ops = popOperands(2)
    if not (ops is None):
        pushOperand(ops[0] + ops[1])

def minus():
    ops = popOperands(2)
    if not (ops is None):
        pushOperand(ops[0] - ops[1])

# the functions above handles all access to the operand stack
# the code below has no references to the operand stack, only to the functions above

def main():
    while (True):
        printOperands()
        token = raw_input(" > ")
        if isOperand(token):
            operand = float(token)
            pushOperand(operand)
        elif token == "exit":
            break
        elif token == "+":
            plus()
        elif token == "-":
            minus()
        else:
            print("Unsupported operator: " + token)
    print("program exited")

main()