From: Ken Bloom Date: 2007-12-03T23:05:01+09:00 Subject: Re: [QUIZ] Postfix to Infix (#148) On Sun, 02 Dec 2007 22:23:23 -0500, Eric Mahurin wrote: > Note: parts of this message were removed by the gateway to make it a > legal Usenet post. > > On Nov 30, 2007 7:28 AM, Ruby Quiz wrote: > >> For an added bonus, try to keep the parentheses added to infix >> expressions to >> the minimum of what is needed. >> >> > My solution does the above, plus a few more things: > > * maintains an OO data structure (to do everything below) * further > reduce parentheses (and post-fix stack depth) by using some > associativity > * evaluates the result > * gives stack-reduced post-fix form > > The basic idea of the solution is to have an object for each expression > (possibly with sub-expressions as operands) and have methods for > applying another operation in either direction (i.e. have both #add and > #radd - reverse add). This allows independent decisions on what each > type of expression should do when it is in either operand of another > operation. > > Here are a few examples (result shows internal postfix, infix, and > result): > >>ruby quiz148.rb "2 3 5 + *" > 2 3 5 + * => 2*(3 + 5) => 16 >>ruby quiz148.rb "56 34 213.7 + * 678 -" > 56 34 213.7 + * 678 - => 56*(34 + 213.7) - 678 => 13193.2 >>ruby quiz148.rb "1 56 35 + 16 9 - / +" > 1 56 35 + 16 9 - / + => 1 + (56 + 35)*(16 - 9) => 14 >>ruby quiz148.rb "1 2 3 4 5 + + + +" > 1 2 + 3 + 4 + 5 + => 1 + 2 + 3 + 4 + 5 => 15 >>ruby quiz148.rb "1 2 3 4 5 - - - -" > 1 2 - 3 + 4 - 5 + => 1 - 2 + 3 - 4 + 5 => 3 This doesn't look right. 3 5 * 5 8 * / => 3*5*(5*8) => 0 --Ken -- Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/