Huzaifa Imran
Huzaifa Imran

Reputation: 139

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

Upvotes: 1

Views: 148

Answers (1)

azro
azro

Reputation: 54168

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+|[-+()/*])"

Upvotes: 3

Related Questions