Editorial for Equation Solver


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Strings! We needed to replace + and - in order to block the one-liner Python solution of print eval(input()). Read in the entire equation into an array, and iterate through each term and operation. Keep the current operation and the running total. For each element in your array, if the element is P, set the current operation to 1. If the element is M, set the current operation to -1. Otherwise, just add (current operation)*(integer of the element) into your total. Alternatively, just replace all P and M with + and - and then use python eval -_-.

seq = raw_input()[:-2].split()
tot = 0
op = 1
for i in seq:
    if i != 'P' and i!='M':
        tot += op*int(i)
    elif i == 'P':
        op = 1
    else:
        op = -1
print tot

Comments

There are no comments at the moment.