Reverse Polish notation

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

user11

Posted 2011-01-30T01:39:22.293

Reputation:

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.513

5That'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.970

1@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.797

3How 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 than float(s) – gnibbler – 2011-01-30T10:56:35.710

Can 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

Answers

15

Ruby - 95 77 characters

a=[]
gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))}
p a[0]

Takes input on stdin.

Testing code

[
  "-4 5 +",
  "5 2 /",
  "5 2.5 /",
  "5 1 2 + 4 * 3 - +",
  "4 2 5 * + 1 3 2 * + /",
  "12 8 3 * 6 / - 2 + -20.5 "
].each do |test|
  puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}"
end

gives

[-4 5 +] gives 1.0
[5 2 /] gives 2.5
[5 2.5 /] gives 2.0
[5 1 2 + 4 * 3 - +] gives 14.0
[4 2 5 * + 1 3 2 * + /] gives 2.0
[12 8 3 * 6 / - 2 + -20.5 ] gives 10.0

Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems.

Nemo157

Posted 2011-01-30T01:39:22.293

Reputation: 1 891

1You could shave off a character by using map instead of each – addison – 2015-06-21T02:31:55.150

10

Scheme, 162 chars

(Line breaks added for clarity—all are optional.)

(let l((s'()))(let((t(read)))(cond((number? t)(l`(,t,@s)))((assq t
`((+,+)(-,-)(*,*)(/,/)))=>(lambda(a)(l`(,((cadr a)(cadr s)(car s))
,@(cddr s)))))(else(car s)))))

Fully-formatted (ungolfed) version:

(let loop ((stack '()))
  (let ((token (read)))
    (cond ((number? token) (loop `(,token ,@stack)))
          ((assq token `((+ ,+) (- ,-) (* ,*) (/ ,/)))
           => (lambda (ass) (loop `(,((cadr ass) (cadr stack) (car stack))
                                    ,@(cddr stack)))))
          (else (car stack)))))

Selected commentary

`(,foo ,@bar) is the same as (cons foo bar) (i.e., it (effectively) returns a new list with foo prepended to bar), except it's one character shorter if you compress all the spaces out.

Thus, you can read the iteration clauses as (loop (cons token stack)) and (loop (cons ((cadr ass) (cadr stack) (car stack)) (cddr stack))) if that's easier on your eyes.

`((+ ,+) (- ,-) (* ,*) (/ ,/)) creates an association list with the symbol + paired with the procedure +, and likewise with the other operators. Thus it's a simple symbol lookup table (bare words are (read) in as symbols, which is why no further processing on token is necessary). Association lists have O(n) lookup, and thus are only suitable for short lists, as is the case here. :-P

† This is not technically accurate, but, for non-Lisp programmers, it gets a right-enough idea across.

Chris Jester-Young

Posted 2011-01-30T01:39:22.293

Reputation: 4 464

2lambda (ass) +1 for variable name choice :P – Downgoat – 2016-04-24T02:50:26.973

7I like the four smileys in the golfed version. – tomsmeding – 2013-10-28T07:34:39.640

Can you read that? Seriously? – None – 2011-01-30T03:14:16.860

1@M28: The ungolfed version, yes. I program in Scheme on a semi-regular basis (for real, serious programs). – Chris Jester-Young – 2011-01-30T03:16:51.040

Unfortunately, Scheme is a verbose language and notoriously difficult to golf well. So I wouldn't be surprised to see some Perl submission beat this one. – Chris Jester-Young – 2011-01-30T03:18:43.050

10

Python - 124 chars

s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s[:2]=[[a+b],[a-b],[a*b],[a/b],[i,b,a]]["+-*/".find(i)]
print s[0]

Python - 133 chars

s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s={'+':[a+b],'-':[a-b],'*':[a*b],'/':[a/b]}.get(i,[i,b,a])+s[2:]
print s[0]

gnibbler

Posted 2011-01-30T01:39:22.293

Reputation: 14 170

2[a/b] should be replaced with b and[a/b] so that you can have 0 as second operand. – flornquake – 2013-04-14T21:44:21.370

1I like the stack manipulation. – Alexandru – 2011-01-30T12:55:55.387

2You can't have 0 as second operand... – JBernardo – 2011-12-22T08:36:19.147

7

c -- 424 necessary character

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define O(X) g=o();g=o() X g;u(g);break;
char*p=NULL,*b;size_t a,n=0;float g,s[99];float o(){return s[--n];};
void u(float v){s[n++]=v;};int main(){getdelim(&p,&a,EOF,stdin);for(;;){
b=strsep(&p," \n\t");if(3>p-b){if(*b>='0'&&*b<='9')goto n;switch(*b){case 0:
case EOF:printf("%f\n",o());return 0;case'+':O(+)case'-':O(-)case'*':O(*)
case'/':O(/)}}else n:u(atof(b));}}

Assumes that you have a new enough libc to include getdelim in stdio.h. The approach is straight ahead, the whole input is read into a buffer, then we tokenize with strsep and use length and initial character to determine the class of each. There is no protection against bad input. Feed it "+ - * / + - ...", and it will happily pop stuff off the memory "below" the stack until it seg faults. All non-operators are interpreted as floats by atof which means zero value if they don't look like numbers.

Readable and commented:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *p=NULL,*b;
size_t a,n=0;
float g,s[99];
float o(){        /* pOp */
  //printf("\tpoping '%f'\n",s[n-1]);
  return s[--n];
};
void u(float v){  /* pUsh */
  //printf("\tpushing '%f'\n",v);
  s[n++]=v;
};
int main(){
  getdelim(&p,&a,EOF,stdin); /* get all the input */
  for(;;){
    b=strsep(&p," \n\t"); /* now *b though *(p-1) is a token and p
                 points at the rest of the input */
    if(3>p-b){
      if (*b>='0'&&*b<='9') goto n;
      //printf("Got 1 char token '%c'\n",*b);
      switch (*b) {
      case 0:
      case EOF: printf("%f\n",o()); return 0;
      case '+': g=o(); g=o()+g; u(g); break;
      case '-': g=o(); g=o()-g; u(g); break;
      case '*': g=o(); g=o()*g; u(g); break;
      case '/': g=o(); g=o()/g; u(g); break;
    /* all other cases viciously ignored */
      } 
    } else { n:
      //printf("Got token '%s' (%f)\n",b,atof(b));
      u(atof(b));
    }
  }
}

Validation:

 $ gcc -c99 rpn_golf.c 
 $ wc rpn_golf.c
  9  34 433 rpn_golf.c
 $ echo -4 5 + | ./a.out
1.000000
 $ echo 5 2 / | ./a.out
2.500000
 $ echo 5 2.5 / | ./a.out
2.000000

Heh! Gotta quote anything with * in it...

 $ echo "5 1 2 + 4 * 3 - +" | ./a.out
14.000000
 $ echo "4 2 5 * + 1 3 2 * + /" | ./a.out
2.000000

and my own test case

 $ echo "12 8 3 * 6 / - 2 + -20.5 " | ./a.out
-20.500000

dmckee --- ex-moderator kitten

Posted 2011-01-30T01:39:22.293

Reputation: 2 726

You can safe some characters by replacing case with a makro. – FUZxxl – 2011-01-30T14:24:49.477

7

Haskell (155)

f#(a:b:c)=b`f`a:c
(s:_)![]=print s
s!("+":v)=(+)#s!v
s!("-":v)=(-)#s!v
s!("*":v)=(*)#s!v
s!("/":v)=(/)#s!v
s!(n:v)=(read n:s)!v
main=getLine>>=([]!).words

marinus

Posted 2011-01-30T01:39:22.293

Reputation: 30 224

You can get remove 9 characters by changing "(s:)![]=s" to "(s:)![]=print s" and "main=getLine>>=putStrLn.show.([]!).words" to "main=getLine>>=([]!).words" – Fors – 2013-04-19T16:25:50.007

And then further remove a few other characters by using a one-line case-statement. – Fors – 2013-04-19T18:29:12.620

s!(n:v)=case n of{"+"->(+)#s;"-"->(-)#s;"*"->(*)#s;"/"->(/)#s;_->(read n:s)}!v would save 14 characters. – Fors – 2013-04-20T12:38:22.193

7

MATLAB – 158, 147

C=strsplit(input('','s'));D=str2double(C);q=[];for i=1:numel(D),if isnan(D(i)),f=str2func(C{i});q=[f(q(2),q(1)) q(3:end)];else q=[D(i) q];end,end,q

(input is read from user input, output printed out).


Below is the code prettified and commented, it pretty much implements the postfix algorithm described (with the assumption that expressions are valid):

C = strsplit(input('','s'));         % prompt user for input and split string by spaces
D = str2double(C);                   % convert to numbers, non-numeric are set to NaN
q = [];                              % initialize stack (array)
for i=1:numel(D)                     % for each value
    if isnan(D(i))                   % if it is an operator
        f = str2func(C{i});          % convert op to a function
        q = [f(q(2),q(1)) q(3:end)]; % pop top two values, apply op and push result
    else
        q = [D(i) q];                % else push value on stack
    end
end
q                                    % show result

Bonus:

In the code above, we assume operators are always binary (+, -, *, /). We can generalize it by using nargin(f) to determine the number of arguments the operand/function requires, and pop the right amount of values from the stack accordingly, as in:

f = str2func(C{i});
n = nargin(f);
args = num2cell(q(n:-1:1));
q = [f(args{:}) q(n+1:end)];

That way we can evaluate expressions like:

str = '6 5 1 2 mean_of_three 1 + 4 * +'

where mean_of_three is a user-defined function with three inputs:

function d = mean_of_three(a,b,c)
    d = (a+b+c)/3;
end

Amro

Posted 2011-01-30T01:39:22.293

Reputation: 171

6

Perl (134)

@a=split/\s/,<>;/\d/?push@s,$_:($x=pop@s,$y=pop@s,push@s,('+'eq$_?$x+$y:'-'eq$_?$y-$x:'*'eq$_?$x*$y:'/'eq$_?$y/$x:0))for@a;print pop@s

Next time, I'm going to use the recursive regexp thing.

Ungolfed:

@a = split /\s/, <>;
for (@a) {
    /\d/
  ? (push @s, $_)
  : ( $x = pop @s,
      $y = pop @s,
      push @s , ( '+' eq $_ ? $x + $y
                : '-' eq $_ ? $y - $x
                : '*' eq $_ ? $x * $y
                : '/' eq $_ ? $y / $x
                : 0 )
      )
}
print(pop @s);

I though F# is my only dream programming language...

Ming-Tang

Posted 2011-01-30T01:39:22.293

Reputation: 5 383

I have a shorter Perl 5 implementation. – dolmen – 2019-01-03T00:48:11.017

6

Windows PowerShell, 152 181 192

In readable form, because by now it's only two lines with no chance of breaking them up:

$s=@()
switch -r(-split$input){
  '\+'        {$s[1]+=$s[0]}
  '-'         {$s[1]-=$s[0]}
  '\*'        {$s[1]*=$s[0]}
  '/'         {$s[1]/=$s[0]}
  '-?[\d.]+'  {$s=0,+$_+$s}
  '.'         {$s=$s[1..($s.count)]}}
$s

2010-01-30 11:07 (192) – First attempt.

2010-01-30 11:09 (170) – Turning the function into a scriptblock solves the scope issues. Just makes each invocation two bytes longer.

2010-01-30 11:19 (188) – Didn't solve the scope issue, the test case just masked it. Removed the index from the final output and removed a superfluous line break, though. And changed double to float.

2010-01-30 11:19 (181) – Can't even remember my own advice. Casting to a numeric type can be done in a single char.

2010-01-30 11:39 (152) – Greatly reduced by using regex matching in the switch. Completely solves the previous scope issues with accessing the stack to pop it.

Joey

Posted 2011-01-30T01:39:22.293

Reputation: 12 260

5

Racket 131:

(let l((s 0))(define t(read))(cond[(real? t)
(l`(,t,@s))][(memq t'(+ - * /))(l`(,((eval t)(cadr s)
(car s)),@(cddr s)))][0(car s)]))

Line breaks optional.

Based on Chris Jester-Young's solution for Scheme.

Sam Tobin-Hochstadt

Posted 2011-01-30T01:39:22.293

Reputation: 151

4

Python 3, 119 bytes

s=[]
for x in input().split():
 try:s+=float(x),
 except:o='-*+'.find(x);*s,a,b=s;s+=(a+b*~-o,a*b**o)[o%2],
print(s[0])

Input: 5 1 1 - -7 0 * + - 2 /

Output: 2.5

(You can find a 128-character Python 2 version in the edit history.)

flornquake

Posted 2011-01-30T01:39:22.293

Reputation: 1 467

Pretty clever :) I like how you don't need / in the string. – Daniel Lubarov – 2013-10-20T19:12:31.440

114 bytes – Erik the Outgolfer – 2017-10-26T18:46:12.840

@EriktheOutgolfer that breaks with a ZeroDivisionError when the second operand is 0 (e.g. 5 0 +). – flornquake – 2017-11-01T16:54:14.790

You can save 1 character by using the ord(x) - 42 method. – frederick99 – 2019-05-26T04:54:36.277

@frederick99 I don't see how. – flornquake – 2019-07-22T21:07:32.970

@flornquake *s,a,b=s;s+=[a*b,a+b,0,a-b,b and a/b][ord(t)-42], but i love the current solution better. – frederick99 – 2019-07-24T14:12:02.070

@frederick99 Thank you! In that variant, it would need an extra two characters 0,, no? s+=[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42], – flornquake – 2019-07-25T21:55:27.743

@flornquake no. have you tried running it? – frederick99 – 2019-07-27T11:48:22.213

@frederick99 Yes (tio )

– flornquake – 2019-07-27T13:28:17.447

@flornquake mb, none of my test cases had division :l – frederick99 – 2019-07-28T18:21:25.207

4

Python, 166 characters

import os,operator as o
S=[]
for i in os.read(0,99).split():
 try:S=[float(i)]+S
 except:S=[{'+':o.add,'-':o.sub,'/':o.div,'*':o.mul}[i](S[1],S[0])]+S[2:]
print S[0]

Keith Randall

Posted 2011-01-30T01:39:22.293

Reputation: 19 865

Use raw_input() code isn't split over multiple lines. – JPvdMerwe – 2011-01-30T06:23:53.367

Then you could try: from operator import* and replace o.div with div. – JPvdMerwe – 2011-01-30T10:37:27.510

3

JavaScript (157)

This code assumes there are these two functions: readLine and print

a=readLine().split(/ +/g);s=[];for(i in a){v=a[i];if(isNaN(+v)){f=s.pop();p=s.pop();s.push([p+f,p-f,p*f,p/f]['+-*/'.indexOf(v)])}else{s.push(+v)}}print(s[0])

user11

Posted 2011-01-30T01:39:22.293

Reputation:

Shorter if you use prompt() instead of readLine() (and perhaps alert() instead of print() to match prompt()). – nyuszika7h – 2014-08-21T19:00:00.890

3

Perl, 128

This isn't really competitive next to the other Perl answer, but explores a different (suboptimal) path.

perl -plE '@_=split" ";$_=$_[$i],/\d||
do{($a,$b)=splice@_,$i-=2,2;$_[$i--]=
"+"eq$_?$a+$b:"-"eq$_?$a-$b:"*"eq$_?
$a*$b:$a/$b;}while++$i<@_'

Characters counted as diff to a simple perl -e '' invocation.

J B

Posted 2011-01-30T01:39:22.293

Reputation: 9 638

2

flex - 157

%{
float b[100],*s=b;
#define O(o) s--;*(s-1)=*(s-1)o*s;
%}
%%
-?[0-9.]+ *s++=strtof(yytext,0);
\+ O(+)
- O(-)
\* O(*)
\/ O(/)
\n printf("%g\n",*--s);
.
%%

If you aren't familiar, compile with flex rpn.l && gcc -lfl lex.yy.c

Geoff Reedy

Posted 2011-01-30T01:39:22.293

Reputation: 2 828

2

Python, 130 characters

Would be 124 characters if we dropped b and (which some of the Python answers are missing). And it incorporates 42!

s=[]
for x in raw_input().split():
 try:s=[float(x)]+s
 except:b,a=s[:2];s[:2]=[[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42]]
print s[0]

Daniel Lubarov

Posted 2011-01-30T01:39:22.293

Reputation: 301

Really nice answer. But I count 130 characters. ;) – flornquake – 2014-09-15T10:02:43.683

@flornquake you're right, thanks for the correction. – Daniel Lubarov – 2014-09-15T19:44:36.630

2

PHP, 439 265 263 262 244 240 characters

<? $c=fgets(STDIN);$a=array_values(array_filter(explode(" ",$c)));$s[]=0;foreach($a as$b){if(floatval($b)){$s[]=$b;continue;}$d=array_pop($s);$e=array_pop($s);$s[]=$b=="+"?$e+$d:($b=="-"?$e-$d:($b=="*"?$e*$d:($b=="/"?$e/$d:"")));}echo$s[1];

This code should work with stdin, though it is not tested with stdin.

It has been tested on all of the cases, the output (and code) for the last one is here:
http://codepad.viper-7.com/fGbnv6

Ungolfed, 314 330 326 characters

<?php
$c = fgets(STDIN);
$a = array_values(array_filter(explode(" ", $c)));
$s[] = 0;
foreach($a as $b){
    if(floatval($b)){
        $s[] = $b;
        continue;
    }
    $d = array_pop($s);
    $e = array_pop($s);
    $s[] = $b == "+" ? $e + $d : ($b == "-" ? $e - $d : ($b == "*" ? $e * $d : ($b == "/" ? $e / $d :"")));
}
echo $s[1];

Kevin Brown

Posted 2011-01-30T01:39:22.293

Reputation: 5 756

Quote from the task description: »For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.« – demonstrably PHP has functions to do so, therefore the assumption is incorrect. – Joey – 2011-01-30T10:11:39.253

Updated it to use stdin and golfed it a little more. – Kevin Brown – 2011-01-30T19:21:55.350

2

Python, 161 characters:

from operator import*;s=[];i=raw_input().split(' ')
q="*+-/";o=[mul,add,0,sub,0,div]
for c in i:
 if c in q:s=[o[ord(c)-42](*s[1::-1])]+s 
 else:s=[float(c)]+s
print(s[0])

Thomas O

Posted 2011-01-30T01:39:22.293

Reputation: 3 044

2

Python 3, 126 132 chars

s=[2,2]
for c in input().split():
    a,b=s[:2]
    try:s[:2]=[[a+b,b-a,a*b,a and b/a]["+-*/".index(c)]]
    except:s=[float(c)]+s
print(s[0])

There have been better solutions already, but now that I had written it (without having read the prior submissions, of course - even though I have to admit that my code looks as if I had copypasted them together), I wanted to share it, too.

cemper93

Posted 2011-01-30T01:39:22.293

Reputation: 670

@flornquake Fixed it for him. – mbomb007 – 2015-07-28T20:17:24.773

b/a should be replaced with a and b/a, otherwise this solution won't work if the second operand is 0 (e.g. 4 0 -). – flornquake – 2013-04-20T10:51:03.207

2

JavaScript ES7, 119 bytes

I'm getting a bug with array comprehensions so I've used .map

(s,t=[])=>(s.split` `.map(i=>+i?t.unshift(+i):t.unshift((r=t.pop(),o=t.pop(),[r+o,r-o,r*o,r/o]['+-*/'.indexOf(i)]))),t)

Try it online at ESFiddle

Downgoat

Posted 2011-01-30T01:39:22.293

Reputation: 27 116

Is there an ES7 interpreter available? – Conor O'Brien – 2015-12-03T18:12:06.137

@CᴏɴᴏʀO'Bʀɪᴇɴ this should work on Firefox. You could try http://babeljs.io/repl

– Downgoat – 2015-12-03T18:28:50.660

Oh, I see. ^_^ Thanks! – Conor O'Brien – 2015-12-03T18:36:59.797

2

C 178

Sometime a program can be made a bit shorter with more golfing and sometimes you just take completely the wrong route and the much better version is found by someone else.

Thanks to @ceilingcat for finding a much better (and shorter) version

#import<stdlib.h>
float s[99],*p=s;t,z;main(c,v)char**v;{for(;--c;t=z?z-2?~z?z-4?p+=2,atof(*v):*p/p[1]:*p*p[1]:*p-p[1]:*p+p[1],*p=t)z=1[*++v]?-11:**v-43,p--;printf("%f\n",s[1]);}

Try it online!

My original version:

#include <stdlib.h>
#define O(x):--d;s[d]=s[d]x s[d+1];break;
float s[99];main(c,v)char**v;{for(int i=1,d=0;i<c;i++)switch(!v[i][1]?*v[i]:' '){case'+'O(+)case'-'O(-)case'*'O(*)case'/'O(/)default:s[++d]=atof(v[i]);}printf("%f\n",s[1]);}

If you are compiling it with mingw32 you need to turn off globbing (see https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html) by compiling like this:

gcc -std=c99 x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o

If you don't * is automatically expanded by the mingw32 CRT into filenames.

Jerry Jeremiah

Posted 2011-01-30T01:39:22.293

Reputation: 1 217

@ceilingcat Your version is very different to mine (and a lot more impressive) - it is more like a whole new answer than a gold of mine. Are you sure you don't want to post it as a completely different answer? – Jerry Jeremiah – 2020-02-06T21:01:19.613

@ceilingcat Thanks for all the golfs - I have actually learned a lot of tricks from your updates. – Jerry Jeremiah – 2020-02-07T00:23:18.727

2

C, 232 229 bytes

Fun with recursion.

#include <stdlib.h>
#define b *p>47|*(p+1)>47
char*p;float a(float m){float n=strtof(p,&p);b?n=a(n):0;for(;*++p==32;);m=*p%43?*p%45?*p%42?m/n:m*n:m-n:m+n;return*++p&&b?a(m):m;}main(c,v)char**v;{printf("%f\n",a(strtof(v[1],&p)));}

Ungolfed:

#include <stdlib.h>

/* Detect if next char in buffer is a number */
#define b *p > 47 | *(p+1) > 47

char*p; /* the buffer */

float a(float m)
{
    float n = strtof(p, &p); /* parse the next number */

    /* if the next thing is another number, recursively evaluate */
    b ? n = a(n) : 0;

    for(;*++p==32;); /* skip spaces */

    /* Perform the arithmetic operation */
    m = *p%'+' ? *p%'-' ? *p%'*' ? m/n : m*n : m-n : m+n;

    /* If there's more stuff, recursively parse that, otherwise return the current computed value */
    return *++p && b ? a(m) : m;
}

int main(int c, char **v)
{
    printf("%f\n", a(strtof(v[1], &p)));
}

Test Cases:

$ ./a.out "-4 5 +"
1.000000
$ ./a.out "5 2 /"
2.500000
$ ./a.out "5 2.5 /"
2.000000
$ ./a.out "5 1 2 + 4 * 3 - +"
14.000000
$ ./a.out "4 2 5 * + 1 3 2 * + /"
2.000000

Cole Cameron

Posted 2011-01-30T01:39:22.293

Reputation: 1 013

1

Python 2

I've tried out some different approaches to the ones published so far. None of these is quite as short as the best Python solutions, but they might still be interesting to some of you.

Using recursion, 146

def f(s):
 try:x=s.pop();r=float(x)
 except:b,s=f(s);a,s=f(s);r=[a+b,a-b,a*b,b and a/b]['+-*'.find(x)]
 return r,s
print f(raw_input().split())[0]

Using list manipulation, 149

s=raw_input().split()
i=0
while s[1:]:
 o='+-*/'.find(s[i])
 if~o:i-=2;a,b=map(float,s[i:i+2]);s[i:i+3]=[[a+b,a-b,a*b,b and a/b][o]]
 i+=1
print s[0]

Using reduce(), 145

print reduce(lambda s,x:x in'+-*/'and[(lambda b,a:[a+b,a-b,a*b,b and a/b])(*s[:2])['+-*'.find(x)]]+s[2:]or[float(x)]+s,raw_input().split(),[])[0]

flornquake

Posted 2011-01-30T01:39:22.293

Reputation: 1 467

1

Python - 206

import sys;i=sys.argv[1].split();s=[];a=s.append;b=s.pop
for t in i:
 if t=="+":a(b()+b())
 elif t=="-":m=b();a(b()-m)
 elif t=="*":a(b()*b())
 elif t=="/":m=b();a(b()/m)
 else:a(float(t))
print(b())

Ungolfed version:

# RPN

import sys

input = sys.argv[1].split()
stack = []

# Eval postfix notation
for tkn in input:
    if tkn == "+":
        stack.append(stack.pop() + stack.pop())
    elif tkn == "-":
        tmp = stack.pop()
        stack.append(stack.pop() - tmp)
    elif tkn == "*":
        stack.append(stack.pop() * stack.pop())
    elif tkn == "/":
        tmp = stack.pop()
        stack.append(stack.pop()/tmp)
    else:
        stack.append(float(tkn))

print(stack.pop())

Input from command-line argument; output on standard output.

golfer9338

Posted 2011-01-30T01:39:22.293

Reputation: 411

1

R, 132 105 96 bytes

for(i in scan(,""))F="if"(grepl("[0-9]",i),c(as.double(i),F),c(get(i)(F[2],F[1]),F[-1:-2]));F[1]

Try it online!

Port of Amro's Matlab answer. I never realized the two languages had so much in common. Saved 27 bytes thanks to Giuseppe ! See edit history for test cases.

JayCe

Posted 2011-01-30T01:39:22.293

Reputation: 2 655

128 bytes – Giuseppe – 2018-08-01T16:53:57.263

using scan(,"") to split the input string (and changing to a full program) is probably a good golf; it would take input as 1 3 + instead of "1 3 +" – Giuseppe – 2018-08-01T16:55:24.473

@Giuseppe it is a good golf indeed! – JayCe – 2018-08-01T16:59:57.867

1

Runic Enchantments, 118 bytes

?!/rRlril1-{=
R:0q}"+0"{:}≠?\"-0"{:}≠?\"*0"{:}≠?\"/0"{≠?\R}l1=?!@
\r\ /<?6+{{~{~/?7-S{{~{~/?8 *{{~{~/?7,S{{~/\

Try it online!

Runic already operates in Reverse Polish Notation, so its just a matter of reading the input and converting from char-based symbols to actual operators.

Due to the near-perfect space usage on the lower line, ≠?\ works out to the same number of bytes as =?!\, but is easier to read.

Explanation

    /<                                                Entry
?!\rRlril1-{=                                         Read all inputs
/r/                                                   Reverse the stack (we need to parse from front to back, not back to front; mirrors flipped to preserve visual flow direction within the explanation)
R                                                     Initial parsing loop entry
 :                                                    Duplicate
  0q}                                                 Concat TOS with a 0 on the end
     "+0"                                             Construct string +0 (checking for addition)
         {:}                                          RoL, Dup, RoR (this allows the same i0 string concatenation to be reused)
            ≠?\                                       Compare, if not equal, continue
               "-0"{:}≠?\"*0"{:}≠?\"/0"{≠?\           Do the same for -, *, and /
                                           R          Bottom-of-loop entry
                                            }         Rotate numerical value to bottom of stack
                                             l1=?!@   If stack is only 1 object, print and terminate
           ~{~/                                       If equal, pop no-longer-needed i0 concatenations and the original input char
        +{{                                           Add most recent 2 values
      ?6                                              Skip to bottom-of-loop
               ?7-S{{~{~/?8 *{{~{~/?7,S{{~/           Similar chunks for -, *, and /
                                           \          Mirror up to bottom of main loop (after-math skips wind up here)
                                     ,S{{~            Note that division does not need to pop no-longer-needed concatenated string, as we used up the last one in the comparison

Invalid input characters will be treated as their decimal equivalents because chars implicitly convert to ints. Strings will crash.

Operators must be compared with their string equivalents, again, because chars implicitly convert to ints. A numerical 43 is identical to the character +. 0q is the shortest method of generating a unique string representation of the stack object that can be compared with known expected strings. Additionally a string may not be the ToS when constructing a new string or the two strings are automatically concatenated.

Draco18s no longer trusts SE

Posted 2011-01-30T01:39:22.293

Reputation: 3 053

1

Scala 412 376 349 335 312:

object P extends App{
def p(t:List[String],u:List[Double]):Double={
def a=u drop 2
t match{
case Nil=>u.head
case x::y=>x match{
case"+"=>p(y,u(1)+u(0)::a)
case"-"=>p(y,u(1)-u(0)::a)
case"*"=>p(y,u(1)*u(0)::a)
case"/"=>p(y,u(1)/u(0)::a)
case d=>p(y,d.toDouble::u)}}}
println(p((readLine()split " ").toList,Nil))}

user unknown

Posted 2011-01-30T01:39:22.293

Reputation: 4 210

1

PHP - 259 characters

$n=explode(" ",$_POST["i"]);$s=array();for($i=0;$i<count($n);$s=$d-->0?array_merge($s,!$p?array($b,$a,$c):array($p)):$s){if($c=$n[$i++]){$d=1;$a=array_pop($s);$b=array_pop($s);$p=$c=="+"?$b+$a:($c=="-"?$b-$a:($c=="*"?$b*$a:($c=="/"?$b/$a:false)));}}echo$s[2];

Assuming input in POST variable i.

Aurel Bílý

Posted 2011-01-30T01:39:22.293

Reputation: 1 083

2Quoted from the original description »For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.« PHP has a way to get stdin through streams. – Kevin Brown – 2011-01-30T19:02:51.230

1

ECMAScript 6 (131)

Just typed together in a few seconds, so it can probably be golfed further or maybe even approached better. I might revisit it tomorrow:

f=s=>(p=[],s.split(/\s+/).forEach(t=>+t==t?p.push(t):(b=+p.pop(),a=+p.pop(),p.push(t=='+'?a+b:t=='-'?a-b:t=='*'?a*b:a/b))),p.pop())

Ingo Bürk

Posted 2011-01-30T01:39:22.293

Reputation: 2 674

1

C# - 323 284 241

class P{static void Main(string[] i){int x=0;var a=new float[i.Length];foreach(var s in i){var o="+-*/".IndexOf(s);if(o>-1){float y=a[--x],z=a[--x];a[x++]=o>3?z/y:o>2?z*y:o>1?z-y:y+z;}else a[x++]=float.Parse(s);}System.Console.Write(a[0]);}}

Edit: Replacing the Stack with an Array is way shorter

Edit2: Replaced the ifs with a ternary expression

kev

Posted 2011-01-30T01:39:22.293

Reputation: 191

string[] i=>string[]i. – Zacharý – 2017-07-27T18:06:56.903

1

Perl, 159

sub c{pop@s}sub z{push@s,$_[0]}while(<>){($_,$a)=/(\S*) ?(.*)/;z$_ if/\d/;z(('-'eq$_?- c:c)+c)if/[+-]/;z(('/'eq$_?1/c:c)*c)if/[*\/]/;redo if$_=$a;print c."\n"}

And here's the ungolfed version:

#!/usr/bin/perl

sub c{pop @stack}
sub z{push @stack,$_[0]}
while (<>) {
    ($_, $a) = /(\S*) ?(.*)/;
    z$_ if /\d/;
    z(('-'eq$_?- c:c)+c) if /[+-]/;
    z(('/'eq$_?1/c:c)*c) if /[*\/]/;
    redo if $_=$a;
    print c . "\n"
}

Not really much to look at, but I'm pretty happy with it. I managed to at least beat the Scheme version :)

Catherine

Posted 2011-01-30T01:39:22.293

Reputation: 31

1

Matlab, 228

F='+-/*';f={@plus,@minus,@rdivide,@times};t=strsplit(input('','s'),' ');i=str2double(t);j=~isnan(i);t(j)=num2cell(i(j));while numel(t)>1
n=find(cellfun(@(x)isstr(x),t),1);t{n}=bsxfun(f{t{n}==F},t{n-2:n-1});t(n-2:n-1)=[];end
t{1}

Ungolfed:

F = '+-/*'; %// possible operators
f = {@plus,@minus,@rdivide,@times}; %// to be used with bsxfun
t = strsplit(input('','s'),' '); %// input string and split by one or multiple spaces
i = str2double(t); %// convert each split string to number
j =~ isnan(i); %// these were operators, not numbers ...
t(j) = num2cell(i(j)); %// ... so restore them
while numel(t)>1
    n = find(cellfun(@(x)isstr(x),t),1); %// find left-most operator
    t{n} = bsxfun(f{t{n}==F}, t{n-2:n-1}); %// apply it to preceding numbers and replace
    t(n-2:n-1)=[]; %// remove used numbers
end
t{1} %// display result

Luis Mendo

Posted 2011-01-30T01:39:22.293

Reputation: 87 464

You can save 2 more bytes by putting everything onto one line (or use a text editor which only uses one character for newline) – Hoki – 2015-07-29T13:28:19.723

@Hoki I'm only using new lines when not breaking the line would require a ;. So I think the byte count is the same – Luis Mendo – 2015-07-29T13:50:06.223

not exactly, most window text editors use cr+lf for a newline, which is 2 characters. My notepad++ counted 230 characters in your 3 lines version, but only 128 if I stick everything in one line (removed 2*2=4 characters from the 2 newlines, and added two ;). Try it yourself ;) – Hoki – 2015-07-29T14:06:16.277

@Hoki You are right. In fact, if I paste the three-line version on https://mothereff.in/byte-counter (which is what I used for counting text bytes), it gives 228. And of course that's also what I get from putting it all in a single line. I don't know where I got the number 230 from. Thanks! Corrected

– Luis Mendo – 2015-07-29T14:29:54.633

1

K5, 70 bytes

`0:*{$[-9=@*x;((*(+;-;*;%)@"+-*/"?y).-2#x;x,.y)@47<y;(.x;.y)]}/" "\0:`

I'm not sure when K5 was released, so this might not count. Still awesome!

kirbyfan64sos

Posted 2011-01-30T01:39:22.293

Reputation: 8 730

1

C# - 392 characters

namespace System.Collections.Generic{class P{static void Main(){var i=Console.ReadLine().Split(' ');var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}

However, if arguments can be used instead of standard input, we can bring it down to

C# - 366 characters

namespace System.Collections.Generic{class P{static void Main(string[] i){var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}

MiffTheFox

Posted 2011-01-30T01:39:22.293

Reputation: 631

You can save 23 characters with a little optimization: 1. remove the namespace trick, explicitly qualify the two types that need it. You save the "namespace" keyword and corresponding brackets. 2. Remove spaces between string[] and i, case keywords and labels, switch and its parens. 3. Get rid of float o and simply use math to get the right results (ie. -k.Pop()+k.Pop() for minus, and 1/k.Pop()*k.Pop() for divide. – MikeP – 2011-05-05T03:33:42.713

1

C++, 265 bytes

Worse than first thought, looking for improvements.

#include<iostream>
#include<string>
#include<stack>
#define G s.top();s.pop()
using namespace std;int main(){string t; stack<float>s;while(cin>>t)if(47<t.back()&t.back()<58)s.push(stof(t));else{float a,b=G;a=G;s.push(t=="+"?a+b:t=="-"?a-b:t=="*"?a*b:a/b);}cout<<G;}

Usage

Run -> input -> enter -> Ctrl+Z -> enter  (windows)
                      -> Ctrl+D           (unix)

Ungolfed

#include <iostream>
#include <string>
#include <stack>
#define G s.top(); s.pop()
using namespace std;

int main()
{
    string t;
    stack<float> s;
    while (cin >> t)
    {
        if (47 < t.back() & t.back() < 58)
            s.push(stof(t));
        else
        {
            float a, b = G;
            a = G;
            s.push(t=="+" ? a+b : t=="-" ? a-b : t=="*" ? a*b : a/b);
        }
    }
    cout << G;
}

Zereges

Posted 2011-01-30T01:39:22.293

Reputation: 1 165

1

Mathetmatica, 143 bytes

Last@Flatten[#~ImportString~"CSV"&/@StringSplit@#]//.{{a___,b_,c_,o_String,d___}:>{a,o[b,c],d},"+"->Plus,"*"->Times,"/"->Divide,"-"->Subtract}&

Anonymous function, takes a string as input (StringSplit[#]), splits at whitespace, ImportString[#,"CSV"] acts on each element separately (it's like a soft form of eval), converting number-like strings to numbers, however operators remain as strings.

//. - repeatedly apply replacement rule: go through the input list, until you hit an operator character, e.g. {1, 4, 2, / *} becomes {1 /[4,2] *}, then {*[1, /[4,2]]}.

String-forms of operators are replaced with the names of the actual Mathematica functions which do the required thing. Output is a number.

LLlAMnYP

Posted 2011-01-30T01:39:22.293

Reputation: 361

I'm disappointed Mathematica doesn't have a builtin ... – wastl – 2018-08-01T12:44:42.000

Last must be applied to the whole expression, not just the input: Last[Flatten[#~ImportString~"CSV" & /@ StringSplit@#] //. {{a___, b_, c_, o_String, d___} :> {a, o[b, c], d}, "+" -> Plus, "*" -> Times, "/" -> Divide, "-" -> Subtract}] &. 142 bytes – Roman – 2019-08-31T16:47:52.127

0

05AB1E, 32 30 bytes

#vyDd_iD'+Qi\+ëD'-Qi\-ë'*Qi*ë/

Try it online or verify all test cases.

Explanation:

#                  # Split the (implicit) input on spaces
 vy                # Loop `y` over each item:
   D               #  Duplicate `y` so its now twice on the stack
    d_i            #  If it's not a digit:
       D'+Qi       #   If it's a '+':
            \      #    Remove the duplicated '+' that's still on the stack
             +     #    Add the top two numbers together
       ëD'-Qi      #   Else-if it's a '-':
             \     #    Remove the duplicated '-' that's still on the stack
              -    #    Subtract the top two numbers from each other
       ë'*Qi       #   Else-if it's a '*':
            *      #    Multiply the top two numbers together
       ë           #   Else (it's a '/'):
        /          #    Divide the top two numbers
                   # (Implicitly output the result)

If eval would have been allowed, it's 14 bytes instead:

TF'-N+N'(+:}.V

Try it online or verify all test cases.

Explanation:

                # Take the string input (implicit)
TF         }    # Loop `N` in the range [0, 10):
  '-N+    :     #  Replace "-N" (where N is the current number of the loop) with:
      N'(+      #   "N(" (where N is again the current number of the loop)
.V              # Eval the string as 05AB1E code (and implicitly output the result)

Negative numbers are indicated with a trailing ( instead of leading - in 05AB1E. Apart from that the calculations are also done in Reverse Polish Notation style.

Kevin Cruijssen

Posted 2011-01-30T01:39:22.293

Reputation: 67 575

0

Kotlin, 175 bytes

{var s=List(0){0f}
for(t in it.split(" ")){try{s=s+t.toFloat()}catch(e:Exception){val(a,b)=s.takeLast(2)
s=s.dropLast(2)+listOf(a+b,a-b,a*b,a/b)["+-*/".indexOf(t)]}}
s.last()}

Try it online!

snail_

Posted 2011-01-30T01:39:22.293

Reputation: 1 982

0

Dart, 196 bytes

F(l,n)=>l.removeAt(l.length-1-n);G(a,b,c)=>c=='+'?a+b:c=='-'?a-b:c=='*'?a*b:a/b;f(s){var l=[];s.split(' ').forEach((a){l.add('+-*/'.contains(a)?G(F(l,1),F(l,0),a):double.parse(a));});return l[0];}

Try it online!

Elcan

Posted 2011-01-30T01:39:22.293

Reputation: 913

0

Perl 5.10+: 95 bytes

perl '-anEmy@a;push@a,/\d/?$_:do{$j=pop@a;$i=pop@a;($i*$j,$i+$j,0,$i-$j,0,$i/$j)[-42+ord]}for@F;say$a[0]'

Size 95 bytes (diff with perl -e '' which is 10 bytes).

Ungolfed, expanding command line flags (thanks to perl -MO=Deparse '-anE...) and slightly edited:

use feature 'say';
while (defined($_ = readline)) {
    our @F = split(' ', $_, 0);
    my @a;
    push @a, /\d/ ? $_ : do {
        $j = pop @a;
        $i = pop @a;
        ($i * $j, $i + $j, 0, $i - $j, 0, $i / $j)[-42 + ord($_)]
    } foreach (@F);
    say $a[0];
}

Notes:

  • See documentation of perl command line switches about -a, -n and -E
  • ASCII values of the following chars are useful to understand the expression involving ord:
    * 42
    + 43
    - 45
    / 47
    

An alternate implementation using regexp matching and replacement: 100 bytes

perl '-pEwhile(s!\b([-0-9.]+)\s+([-0-9.]+)\s+([-+*/])!" ".($1*$2,$1+$2,0,$1-$2,0,$1/$2)[-42+ord$3]!e){}y/ //d'

Ungolfed:

use feature 'say';

while (defined($_ = readline ARGV)) {
    while (s[\b([-0-9.]+)\s+([-0-9.]+)\s+([-+*/])][' ' . ($1 * $2, $1 + $2, 0, $1 - $2, 0, $1 / $2)[-42 + ord($3)];]e) {
        ();
    }
    y/ //d;
} continue {
    die "-p destination: $!\n" unless print $_;
}

dolmen

Posted 2011-01-30T01:39:22.293

Reputation: 111

You can just say perl 5 – ASCII-only – 2019-01-03T01:44:21.773

@ASCII-only say and -E appeared only with Perl v5.10. Sorry if I'm an old-schooler and pedant. – dolmen – 2019-01-25T13:33:02.550

hmm. "-a implicitly sets -n". also... what do you need -E for then – ASCII-only – 2019-01-26T00:00:54.193

0

Javascript, 112 bytes

r=c=>(s=[],f=(a,b,o)=>eval(`${b}${o}${a}`),c.split(' ').forEach(e=>s.push(!+e?f(s.pop(),s.pop(),e):+e)),s.pop())

Zero error checking, uses the eval function, but it works with all valid RPN expressions.

r is a function (eg. r('2 3 +') returns 4)

ruler23

Posted 2011-01-30T01:39:22.293

Reputation: 51

Quote from the OP: You are not allowed to use any kind of "eval" in the program. – mickmackusa – 2019-09-01T05:46:58.977

0

PHP, 172 bytes (Demo)

<?foreach(preg_split('~ +~',fgets(STDIN))as$v)if(floatval($v))$s[]=$v;else{[$e,$d]=array_splice($s,-2);$s[]=$v=="+"?$e+$d:($v=="-"?$e-$d:($v=="*"?$e*$d:$e/$d));}echo $s[0];

Previously entertained techniques:

<?do{$_GET[a]=preg_replace_callback('~(-?[\d.]+) +(-?[\d.]+) +([*/+-])~',fn($m)=>($m[3]=='+'?$m[1]+$m[2]:($m[3]=='-'?$m[1]-$m[2]:($m[3]=='*'?$m[1]*$m[2]:$m[1]/$m[2]))),$_GET[a],1,$c);}while($c);echo $_GET[a]; // 208

<?$v=$_GET[a];do{$v=preg_replace_callback('~(-?[\d.]+) +(-?[\d.]+) +([*/+-])~',fn($m)=>($m[3]=='+'?$m[1]+$m[2]:($m[3]=='-'?$m[1]-$m[2]:($m[3]=='*'?$m[1]*$m[2]:$m[1]/$m[2]))),$v,1,$c);}while($c);echo $v; // 202

<?while(preg_match('~(.*?)(-?[\d.]+) (-?[\d.]+) ([*/+-])(.*)~',$_GET[a],$m))$_GET[a]=$m[1].($m[4]=='+'?$m[2]+$m[3]:($m[4]=='-'?$m[2]-$m[3]:($m[4]=='*'?$m[2]*$m[3]:$m[2]/$m[3]))).$m[5];echo $_GET[a]; // 198

<?$v=$_GET[a];while(preg_match('~(.*?)(-?[\d.]+) +(-?[\d.]+) +([*/+-])(.*)~',$v,$m))$v=$m[1].($m[4]=='+'?$m[2]+$m[3]:($m[4]=='-'?$m[2]-$m[3]:($m[4]=='*'?$m[2]*$m[3]:$m[2]/$m[3]))).$m[5];echo $v;  // 194

mickmackusa

Posted 2011-01-30T01:39:22.293

Reputation: 121

0

Python 2.7 (205 bytes)

Edit: Version 2. After consideration I was able to shave off a lot by using the operator module:

from operator import *
f={'*':mul,'/':div,'+':add,'-':sub}
def e(r):
    l=[]
    for i in r:
        try:i=float(i);l.append(i)
        except:l.append(f[i](*l[-2:]));del l[-3:-1]
    return l
print e(raw_input().split())[0]

MB6

Posted 2011-01-30T01:39:22.293

Reputation: 9

0

Java 243

Input comes from the command line. Element 0 in the Float[ ] isn't actually used for storing the inputs, however it is needed for the first assignment of the temp value. The Float constructor takes care of parsing for negative values and values with a decimal place.

interface R{static void main(String[]a){Float t,f[]=new Float[a.length];int i=0;for(String s:a){t=f[i];switch(s){case"-":t=-t;case"+":f[--i]+=t;break;case"/":t=1/t;case"*":f[--i]*=t;break;default:f[++i]=new Float(s);}}System.out.print(f[i]);}}

Ungolfed:

interface ReversePolishNotation{
    static void main(String[]arg){
        Float temp, fVals[]=new Float[arg.length];
        int i=0;
        for(String str:arg){
            temp=fVals[i];
            switch(str){
                case"-":
                    temp=-temp;
                case"+":
                    fVals[--i]+=temp; break;
                case"/":
                    temp=1/temp;
                case"*":
                    fVals[--i]*=temp; break;
                default:
                    fVals[++i]=new Float(str);
            }
        }
        System.out.print(fVals[i]);
    }
}

Jack Ammo

Posted 2011-01-30T01:39:22.293

Reputation: 430

@RikerW how do you mean? If it's a style issue, I don't see the harm in leaving it the way it is. – Jack Ammo – 2016-01-28T02:36:52.320

Oh NVM. :P I was thinking about the ungolfed version. Oops, sorry. – Rɪᴋᴇʀ – 2016-01-28T02:51:41.777