Open In App

Python | Solve given list containing numbers and arithmetic operators

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list containing numbers and arithmetic operators, the task is to solve the list. 
Example: 

Input: lst =  [2, '+', 22, '+', 55, '+', 4]
Output: 83

Input: lst =  [12, '+', 8, '-', 5]
Output: 15

Below are some ways to achieve the above tasks. 
Method #1: Using Iteration We can use iteration as the simplest approach to solve the list with importing different operators. 

Python3




# Python code to solve the list
# containing numbers and arithmetic operators
 
# Importing
from operator import add, sub
 
# Function to solve list
def find(Input):
    ans = 0
    options = {'+': add, '-': sub}
    option = add
    for item in Input:
        if item in options:
            option = options[item]
        else:
            number = float(item)
            ans = option(ans, number)
    return ans
 
# Input Initialization
lst = [91, '+', 132, '-', 156, '+', 4]
 
# Calling function
Output = find(lst)
 
# Printing output
print("Initial list", lst)
print("Answer after solving list is:", Output)


Output:

Initial list [91, '+', 132, '-', 156, '+', 4]
Answer after solving list is: 71.0

Method #2: Using eval and join 

Python3




# Python code to solve the list
# containing numbers and arithmetic operators
 
# Input list initialization
lst =  [2, '+', 22, '+', 55, '+', 4]
 
# Using eval and join
Output = eval(' '.join(str(x) for x in lst))
 
# Printing output
print("Initial list", lst)
print("Answer after solving list is:", Output)


Output:

Initial list [2, '+', 22, '+', 55, '+', 4]
Answer after solving list is: 83

Approach#3: Using loop

This approach defines a function that takes a list containing numbers and arithmetic operators and evaluates the expression. It initializes the result to the first number in the list and iterates through the remaining items in pairs. Depending on the operator in the current pair, it performs addition, subtraction, multiplication, or division on the result and the next number in the list. The final result is returned.

Algorithm

1. Initialize a variable result to the first element of the list.
2. Traverse the list from index 1 to n-1.
3. If the current element is an operator, apply it on the result and the next element.
4. If the current element is a number, ignore it.
5. Return the final result.

Python3




def evaluate_expression(lst):
    result = lst[0]
    for i in range(1, len(lst)-1, 2):
        if lst[i] == '+':
            result += lst[i+1]
        elif lst[i] == '-':
            result -= lst[i+1]
        elif lst[i] == '*':
            result *= lst[i+1]
        elif lst[i] == '/':
            result /= lst[i+1]
    return result
 
lst = [2, '+', 22, '+', 55, '+', 4]
print(evaluate_expression(lst))  # 83
 
lst = [12, '+', 8, '-', 5]
print(evaluate_expression(lst))  # 15


Output

83
15

Time Complexity: O(n), where n is the length of the list.
Space Complexity: O(1)



Similar Reads

NumPy - Arithmetic operations with array containing string elements
Numpy is a library of Python for array processing written in C and Python. Computations in numpy are much faster than that of traditional data structures in Python like lists, tuples, dictionaries etc. due to vectorized universal functions. Sometimes while dealing with data, we need to perform arithmetic operations but we are unable to do so becaus
2 min read
Python Arithmetic Operators
The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), d
3 min read
Python - Create nested list containing values as the count of list items
Given a list, the task is to write a Python program to create a nested list where the values are the count of list items. Examples: Input: [1, 2, 3] Output: [[1], [2, 2], [3, 3, 3]] Input: [4, 5] Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]] Method 1: Using nested list comprehension The list will contain the count of the list items for each element e in
2 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Count the sublists containing given element in a list
Given a list of lists, write a Python program to count the number of sublists containing the given element x. Examples: Input : lst = [1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]] x = 1 Output : 3 Input : lst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a' Output : 2 Approach #1 : Naive Approach Count the number of lists containing x. Initialize count to 0,
4 min read
Python | Remove element from given list containing specific digits
Given a list, the task is to remove all those elements from list which contains the specific digits. Examples: Input: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 13, 15, 16] no_delete = ['2', '3', '4', '0'] Output: [1, 5, 6, 7, 8, 9, 11, 15, 16] Explanation: Numbers 2, 3, 4, 10, 12, 13, 14 contains digits from no_delete, therefore remove them
9 min read
Python | Remove List elements containing given String character
Sometimes, while working with Python lists, we can have problem in which we need to perform the task of removing all the elements of list which contain at least one character of String. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force way in w
7 min read
Python | Counting sign change in list containing Positive and Negative Integers
Given a list containing Positive and Negative integers, We have to find number of times the sign(Positive or Negative) changes in the list. Input: [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] Output:9 Explanation : Sign change from -1 to 2, ans = 1 Sign change from 3 to -4, ans = 2 Sign change from -4 to 5, ans = 3 Sign change from 5 to -6, ans = 4
5 min read
Python | Sort list containing alphanumeric values
Given a list containing both alphanumeric values, write a Python program to sort the given list in such a way that the alphabetical values always comes after numeric values. Examples: Input : ['k', 5, 'e', 3, 'g', 7, 0, 't'] Output : [0, 3, 5, 7, 'e', 'g', 'k', 't'] Input : [1, 'c', 3, 2, 'a', 'b'] Output : [1, 2, 3, 'a', 'b', 'c'] Approach 1 : Usi
4 min read
Python | Remove tuple from list of tuples if not containing any character
Given a list of tuples, the task is to remove all those tuples which do not contain any character value. Example: Input: [(', ', 12), ('...', 55), ('-Geek', 115), ('Geeksfor', 115),] Output: [('-Geek', 115), ('Geeksfor', 115)] Method #1 : Using list comprehension C/C++ Code # Python code to remove all those # elements from list of tuple # which doe
4 min read
Practice Tags :
three90RightbarBannerImg