Search code examples
pythonstringintegerprimitive

Unstring an equation that consist of integers and primitives


Input:

1st integer given: 3, 
2nd integer given: 2, 
Primitives given in a STRING: '+'

Expected output:

5

Since 3+2=5

My approach:

str(3)+ '+' + str(2)  --> '3+2'
int('3+2') --> Wishfully thinking: 5

As expected, I will get ValueError: invalid literal for int() with base 10: '3+2'.

Any idea how can I approach this? I must use all the input given, meaning I must use the primitives in the string ('+')

Thanks!!


Solution

  • Use eval:

    first = raw_input('1st integer given: ')
    second = raw_input('2nd integer given: ')
    primitives = raw_input('Primitives given in a STRING: ')
    
    equation = first+primitives+second
    answer = eval(equation)
    print answer
    

    Runs as:

    1st integer given: 3
    2nd integer given: 2
    Primitives given in a STRING: +
    5
    

    Or:

    1st integer given: 99
    2nd integer given: 9
    Primitives given in a STRING: /
    11