0

Below is my code:

def interpret(value, commands, args):
    ans = 0
    valid = ['+','-','*']
    if set(commands).issubset(valid):
        for ope,arg in zip(commands,args):
            ans = eval(r'value ope arg')
            value = ans
        return print (ans)
    else :
        return print('-1')

def main():
    interpret(1, ['+'], [1])

if __name__ == '__main__':
    main()

Have tried eval(value+ope+arg) but got error

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Have also looked for other solutions like to use regular expression and then evaluating it but not able to evaluate the expression

Expected answer = 2

  • 3
    what do you think `eval(r'value ope arg')` is doing? BTW `eval` using eval is _dangerous_! You should probably try another way... – Julien Oct 04 '18 at 23:54

1 Answers1

0

Unlike some other languages, Python does not automatically convert numbers to strings when using the + operator to concatenate strings. You have to do this conversion explicitly.

ans = eval(str(value)+ope+str(arg))

Note, however, that using eval is generally a bad idea.

dan04
  • 87,747
  • 23
  • 163
  • 198