Search code examples
pythoninfix-notation

Convert Infix expression to list


I want to convert infix expression to list such that double digits or character are considered a single operand i.e 28*35/(21-13) should result in ['28', '*', '35', '/', '(', '21', '-', '13', ')']

This is the code I've written and it works fine but I was wondering if there was a smarter way to do it like with list comprehension or something

expression = "28*35/(21-13)"
expression.replace(' ', '') # replace spaces if any
expressionList = []
operand = ""
for char in expression:
    if char in "+-*/()":
        if operand != '':
            expressionList.append(operand)
            operand = ''
        expressionList.append(char)
    else:
        operand += char

Solution

  • You canno't use a list-comprehension as need to know previous element to split the content. The easier solution I see, is to use a regex

    Here (\d+|[-+()/*]) means

    • \d+ any suite of digits, or (the pipe is OR |)
    • any char in -+()/*
    import re
    
    expression = "28*35/(21-13)"
    values = re.findall(r"(\d+|[-+()/*])", expression) 
    print(values) # ['28', '*', '35', '/', '(', '21', '-', '13', ')']
    

    Add letters : "([A-Z]+|\d+|[-+()/*])"