Python | Solve given list containing numbers and arithmetic operators
Last Updated :
11 Apr, 2023
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
from operator import add, sub
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
lst = [ 91 , '+' , 132 , '-' , 156 , '+' , 4 ]
Output = find(lst)
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
lst = [ 2 , '+' , 22 , '+' , 55 , '+' , 4 ]
Output = eval ( ' ' .join( str (x) for x in lst))
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))
lst = [ 12 , '+' , 8 , '-' , 5 ]
print (evaluate_expression(lst))
|
Time Complexity: O(n), where n is the length of the list.
Space Complexity: O(1)
Please Login to comment...