2

I'm learning python, and I have encountered a problem.

for i in input:
    operator = i.split()[0]
    number1 = i.split()[1]
    number2 = i.split()[2]
    equation = (number1 + ' ' +  operator + ' ' + number2)

This code is supposed to calculate a randomly generated input, for example:

+ 9 16 this one wants me to print the result of 9 + 16

so I made code which converts the input into an equation but i have no idea how do tell the code to calculate it.

Could anybody help me?

JajasPer
  • 81
  • 9
NilT_PL
  • 21
  • 1

4 Answers4

0

You don't need a loop:

a = input()
operator = a.split()[0]
number1 = a.split()[1]
number2 = a.split()[2]
equation = (number1 + ' ' +  operator + ' ' + number2)
print(equation)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You don't need a loop to get the whole sentence. Just an input would work since split() works for splitting a string by the given parameter. Just use an a = input().

Onur
  • 164
  • 1
  • 18
0
x = '+ 9 16'
operator, number1, number2 = x.split()
result  = eval(number1 + ' ' +  operator + ' ' + number2) #ugly
print(result)

In your case your can try

print(eval(equation)) #ugly
herveRilos
  • 106
  • 1
  • 5
0

The expression is a prefix expression, where the operator is the first followed by operands. + 9 16 is a simple expression because here you have just one operator i.e. + and two operands 9 and 16.

def evaluate(num1, num2, operator):
    # returns the result after evaluating the expression
    if operator == '+': 
        return(num1 + num2) 

    elif operator == '-': 
        return(num1 - num2) 

    elif operator == '*': 
        return(num1 * num2) 

    elif operator == '/': 
        return(num1 / num2)


a = str(input())
# a = "+ 9 16"

temp = None
operator = ""

for i in a.split():
    # a.split() is a list
    if i.isdigit():
        # isdigit() returns true if i is a number
        if not temp:
            # this is our first operand
            temp = int(i) 
        else:
            # this is our second operand
            print(evaluate(temp, int(i), operator))
    else:
        # this is our operator
        operator = i

To evaluate a more complex prefix expression, we generally use a stack. To learn more about evaluating a complex prefix expression refer this.

Divx
  • 39
  • 11