Path: g2news1.google.com!news1.google.com!border1.nntp.dca.giganews.com!nntp.giganews.com!nx01.iad01.newshosting.com!newshosting.com!newsfeed.icl.net!newsfeed.fjserv.net!oleane.net!oleane!ciril.fr!news.ecp.fr!talisker.lacave.net!lacave.net!not-for-mail From: Harry Kakueki Newsgroups: comp.lang.ruby Subject: Re: [QUIZ] Postfix to Infix (#148) Date: Sun, 2 Dec 2007 10:09:23 -0500 Organization: Service de news de lacave.net Lines: 43 Message-ID: <79621bdb0712020709t46ba44fco7e2e6c7f9b65f39f@mail.gmail.com> References: <20071130132821.ZZSN2903.eastrmmtao105.cox.net@eastrmimpo01.cox.net> NNTP-Posting-Host: bristol.highgroove.com Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Trace: talisker.lacave.net 1196608202 5893 65.111.164.187 (2 Dec 2007 15:10:02 GMT) X-Complaints-To: abuse@lacave.net NNTP-Posting-Date: Sun, 2 Dec 2007 15:10:02 +0000 (UTC) In-Reply-To: <20071130132821.ZZSN2903.eastrmmtao105.cox.net@eastrmimpo01.cox.net> X-Received-From: This message has been automatically forwarded from the ruby-talk mailing list by a gateway at comp.lang.ruby. If it is SPAM, it did not originate at comp.lang.ruby. Please report the original sender, and not us. Thanks! For more details about this gateway, please visit: http://blog.grayproductions.net/categories/the_gateway X-Mail-Count: 281708 X-Ml-Name: ruby-talk X-Rubymirror: Yes X-Ruby-Talk: <79621bdb0712020709t46ba44fco7e2e6c7f9b65f...@mail.gmail.com> > > This week's quiz is to write a script that translates postfix expressions into > the equivalent infix expression. In the simplest form, your script should > function as such: > > $ ruby postfix_to_infix.rb '2 3 +' > 2 + 3 > > At minimum, try to support the four basic math operators: +, -, *, and /. Feel > free to add others though. For numbers, remember to accept decimal values. > # Here is my solution. # It solves the minimum requirements with minimal error checking. # Removes some parentheses. #str = "1 56 35 + 16 9 - / +" str = "1 2 - 3 4 - - 2 * 7.4 + 3.14 * 2 / 1.2 + 3 4 - -" ops = %w[+ - * /] arr = str.split(/\s+/) err = arr.select {|c| c =~ /^\d+\.?\d?/ || ops.include?(c)} the_stack = [] if arr.length == err.length arr.each_with_index do |x,y| the_stack << x unless ops.include?(x) if ops.include?(x) && the_stack.length > 1 b = the_stack.pop a = the_stack.pop the_stack << "(#{a} #{x} #{b})" if (x == "+" || x == "-") && (y < (arr.length - 1)) the_stack << "#{a} #{x} #{b}" if x == "*" || x == "/" || y == (arr.length - 1) end end puts the_stack[0] end # Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html