Home > Software design >  python make an operation out of a list without eval or exec
python make an operation out of a list without eval or exec

Time:12-15

I have a list like this:

list = ["6", " ", "8"]

and I want to make the operation: 6 8 and store the result in the variable "result". What I thought was that I could use the int() method to turn into int the strings, but I don't know what to do with the operators. And I don't get how I can make it works whatever the amount of operators and numbers are stored in the array.

I think it's possible to do something like "for each take previous and next item in list and add them together" but it doesn't solve the problem of how to turn the operator in the string into real operator. Thanks for reading, have a nice day :)

CodePudding user response:

To access operators programmatically, you can just use the operator module.

For example:

import operator


def op2fn(text):
    if text == " ":
        return operator.add
    elif text == "-":
        return operator.sub


l = ["6", " ", "8"]
result = op2fn(l[1])(int(l[0]), int(l[2]))
print(result)
# 14

Alternatively, you can use your own function, e.g.:

def add(x, y):
    return x   y

Note that this answer only address the issue of mapping " " to the operator.add function. If you want to write a parser, this is only the simplest part of it.

CodePudding user response:

Code:-

x = ['1',' ','2','-','3']
check=0
for i in x:
    if i in [" ","-","*","/"]:
        check =1
for i in range(len(x) check-1): #Assuming The sign ( ,-) where present has previous and forward numbers 
    if x[i]==" ":
        temp1=int(x[i-1]) int(x[i 1])
        x.insert(i 2,str(temp1))
    if x[i]=="-":
        temp2=int(x[i-1])-int(x[i 1])
        x.insert(i 2,str(temp2))
    if x[i]=="*":
        temp3=int(x[i-1])*int(x[i 1])
        x.insert(i 2,str(temp3))
    if x[i]=="/":
        temp4=int(x[i-1])//int(x[i 1])
        x.insert(i 2,str(temp4))
#print(x)   #values how store in the list
print(x[-1])
  • Related