RSS

Python: function to Calculate the sum a math expression as strings inside a list

28 Dec

This function is to evaluate the stuff inside a list. In my case the specific situation was that I had a list like this mylist=[“10″,”+”,”20″,”-“,”20″,”+”,”20″,”-“,”20”] and I want to get a return 10. ie., ((((10+20)-20)+20)-20)=10

def sum_of_all_values(list):
    value_in_mem=0
    iter_i=0#current iteration
    for i in list:
        iter_i+=1
        index_of_i=iter_i-1
        check_value=i.isnumeric()
        if check_value:
            if i == list[0]:
                value_in_mem=int(i)
        elif i== list[-1]:
            value_in_mem=value_in_mem
        else:
            if i == "+":
                x=int(list[index_of_i-1])
                y=int(list[index_of_i+1])
                if x == list[0]:
                    value_in_mem=x+y
                else:
                    value_in_mem=value_in_mem+y
            if i == "-":
                x=int(list[index_of_i-1])
                y=int(list[index_of_i+1])
                if x == list[0]:
                    value_in_mem=x-y
                else:
                    value_in_mem=value_in_mem-y
            if i == "*":
                x=int(list[index_of_i-1])
                y=int(list[index_of_i+1])
                if x == list[0]:
                    value_in_mem=x*y
                else:
                    value_in_mem=value_in_mem*y
            if i == "/":
                x=int(list[index_of_i-1])
                y=int(list[index_of_i+1])
                if x == list[0]:
                    value_in_mem=x/y
                else:
                    value_in_mem=value_in_mem/y
    return value_in_mem

the above function takes in a list and return the calculated value.

example:

print(sum_of_all_values(mylist))
 
Leave a comment

Posted by on December 28, 2020 in Python

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: