How to check if token is a float?

1.4k views Asked by At

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()
1

There are 1 answers

5
Padraic Cunningham On

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