41
7
You must evaluate a string written in Reverse Polish notation and output the result.
The program must accept an input and return the output. For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.
You are not allowed to use any kind of "eval" in the program.
Numbers and operators are separated by one or more spaces.
You must support at least the +, -, * and / operators.
You need to add support to negative numbers (for example, -4
is not the same thing as 0 4 -
) and floating point numbers.
You can assume the input is valid and follows the rules above
Test Cases
Input:
-4 5 +
Output:
1
Input:
5 2 /
Output:
2.5
Input:
5 2.5 /
Output:
2
Input:
5 1 2 + 4 * 3 - +
Output:
14
Input:
4 2 5 * + 1 3 2 * + /
Output:
2
1I saw this challenge, was really excited I could use my RProgN's 'do' command and be satisfied. Was disappointed when 'eval not allowed'. – ATaco – 2016-11-11T01:20:35.143
XKCD: Reverse Polish Sausage – sergiol – 2017-07-10T01:41:36.170
8It's a shame no eval is allowed, otherwise the GolfScript solution is 1 character:
~
. :-P – Chris Jester-Young – 2011-01-30T01:49:54.5135That's why it's not allowed :-P, this question on StackOverflow received a 4 chars answer with dc. – None – 2011-01-30T01:51:53.920
Can I use
eval
to parse numbers only? – Ming-Tang – 2011-01-30T04:18:39.9701@SHiNKiROU: Which language requires you to use
eval
to parse numbers? It sounds quite broken. (GolfScript is one such language, as far as I'm aware. I think it's broken too.) – Chris Jester-Young – 2011-01-30T05:08:23.7973How is -4 not the same as 0 4 - ? – Keith Randall – 2011-01-30T05:18:15.770
@Chris: Floating-point numbers are required as well, which rules out Golfscript too. And batch files. And Brainfuck. Unless you reimplement fp support in those which is probably not suitable for a golf task :-) – Joey – 2011-01-30T09:44:05.833
What happens when the stack isn't reduced to one element in the end? Still output only the first element? Output the whole stack? Undefined? – Joey – 2011-01-30T10:18:36.603
1I think eval should be ok if it were just to convert strings to numbers. eg. in python
eval(s)
is better thanfloat(s)
– gnibbler – 2011-01-30T10:56:35.710Can we assume the input is fully evaluable? So it won't, for example, be "5 3 8 +" - would result in 5 and 11 in stack, but no operator to apply. – Aurel Bílý – 2011-01-30T15:16:09.250
Added some information about the input on the question, it will always be valid. Eval is not allowed in any case, except if you language REALLY doesn't have ANY other way to convert strings to number. – None – 2011-01-30T15:45:30.563