Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splitting a string which contains mathematical operators in python

world!, I ran into a problem earlier today… I am trying to split operations apart from digits and variables. it’ll split +,-,/,* apart from the digits or the variable (ex: 10+11+10 goes in the code and a list comes out with ["10","+","11","+","10"])

My code:

x = "100+20+a"

operators = ["*","/","+","-"]

def get_index_of(OP,txt):
  return [v for v,i in enumerate(txt+"+") if i == OP]

l = []
for i in operators:
  l.append(get_index_of(i,x))

spliting = sum(l,[])

out = []
for j in spliting:
  out.append(x)
  x = x[:j]

print(out)

The output I get:

['100+20+a', '100', '100']

The output I want:

["100","+","20","+","a"]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using stack

def parse(expression, operators = ["*","/","+","-"]):
    stack = ['']               # start with empty string on stack
    for c in expression:
        if c in operators:
            stack.append(c)    # place operator as new element on stack
            stack.append('')
        elif c != " ":         # not a space
            stack[-1] += c     # append to last element on stack
            
    return stack

Example

print(parse("100+20+a"))
# Output: ['100', '+', '20', '+', 'a']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading