1

So I need to modify the following code so that the methods PostfixEval() and infixToPostfix() can take floats, as well as integers with more than one digit. I've tried isinstance(token,float) == True. Maybe I'm not using it correctly.

def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or isinstance(token,int) == True :
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

and

def postfixEval(postfixExpr):  # also fix this to do floats
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if isinstance(token,int) == True:
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
RonNotJohn
  • 11
  • 2
  • 1
    Have you tried the type() built-in? – reticentroot Jun 12 '15 at 02:35
  • @msanti No I haven't, and being so new to python I can't say I know how to use it haha. Thank you for your feedback! – RonNotJohn Jun 12 '15 at 02:53
  • The type() method returns the type that some variable is. For example, type(3.14) would return a float. So I could test whether something was a float or any data type by doing if type(somevariable) == float: do something – reticentroot Jun 12 '15 at 02:56

1 Answers1

2

tokenList = infixexpr.split() creates a list of strings of which none could be a float. You could make a function to cast to float returning True if you could cast to float.

def is_float(s):
    try:
        float(s)
        return True
    except ValueError:
        return  False

Then:

lett_set = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
if token in lett_set or isfloat(token)

You can also return the float and use it in your other function:

def is_float(s):
    try:
         return float(s)
    except ValueError:
         return  None

for token in tokenList:
     test = is_float(token)
     if test is not None: # catch potential 0
        operandStack.push(test)

You can use the second version in both functions. You mention float in your title so I presume you can have floats which would fail trying to cast to int.

On a side note isinstance(token,int) == True etc.. can simpy be written isinstance(token,int), that will be True or False so any if isinstance(token,int) will be evaluated correctly

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • @alexmcf, it is just as easy try to cast especially as the OP wants an int/float in the second function. – Padraic Cunningham Jun 12 '15 at 02:42
  • The case where you use the float value as the return might behave unexpectedly if the value of the float is 0 – Eric Renouf Jun 12 '15 at 02:45
  • @EricRenouf, yes but the OP mentioned numbers with more than one digit with would have to be values greater than 0 in python but I will mention it – Padraic Cunningham Jun 12 '15 at 02:48
  • Thank you for the input. I've tried your suggestions, as well as trying the type() builtin but it's not passing the tests. I'd provide the entire code, but I just can't seem to paste it correctly haha. – RonNotJohn Jun 12 '15 at 03:14
  • @RonNotJohn, if you are passing any string that can be parsed to a float then the code will work, you have to have strings as you cannot split floats so there is no way issinstance or type would work – Padraic Cunningham Jun 12 '15 at 03:17