2009-05-19 14 views
0

Rubyで修正後の式を評価する小さなスクリプトを作ろうとしました。Rubyの "Postfix Expressions"プログラムの評価

def evaluate_post(expression) 

    my_stack = Stack.new 

    expression.each_char do |ch|   
    begin  
     # Get individual characters and try to convert it to integer 
     y = Integer(ch) 

     # If its an integer push it to the stack 
     my_stack.push(ch) 

    rescue  
     # If its not a number then it must be an operation 
     # Pop the last two numbers 
     num2 = my_stack.pop.to_i    
     num1 = my_stack.pop.to_i 


     case ch 
     when "+" 
      answer = num1 + num2   
     when "*"  
      answer = num1* num2  
     when "-"   
      answer = num1- num2  
     when "/"   
      answer = num1/ num2  
     end 

     # If the operation was other than + - */then answer is nil 
     if answer== nil 
     my_stack.push(num2) 
     my_stack.push(num1) 
     else 
     my_stack.push(answer) 
     answer = nil 
     end 
    end 
    end 

    return my_stack.pop 
end 
  1. Iは、式の中の文字は、この粗製の方法や正規表現を使用せずに整数であるかどうかを確認するためのより良い方法を知りません。皆さんには何か提案がありますか?
  2. ケースを抽象化する方法はありますか? Rubyにeval( "num1 ch num2")関数がありますか?

答えて

2

:結果として、あなたはこれらの2行を入れ替える必要がありますルビーのものと一致します。例外をスローするためにそれを使用したくない場合は、正規表現はうまく動作します - なぜ避けてください?また、整数の場合は、chではなくyをスタックにプッシュするだけで、ポップ時にはto_i呼び出しは不要です。他の質問と同様に、ルビーは確かに評価を持っています。

y = Integer(ch) rescue nil 
if y 
    stack.push(y) 
else 
    num2, num1 = stack.pop(2) 
    a = eval "#{num2} #{ch} #{num1}" # see mehrdad's comment for why not num1 ch num2 
    stack.push(a) 
end 
2

私はあなたの質問に答えることはできません。しかし、そこにはアルゴリズム上の問題があります。加算の場合は、オペランドの順序は重要ではありませんが、減算と除算の場合は、最初のオペランドを減算して2番目のオペランドを除算する必要があります。最初はスタックの深い方です。あなたは、文字列が整数であるかどうかを確認したい場合には、整数の確認、あなたの定義を行っているため、整数()、それを行うためのエレガントな方法である

num1 = my_stack.pop.to_i 
num2 = my_stack.pop.to_i 
+0

ありがとう。私はそれを行います。 – unj2

関連する問題