質問
Ruby で後置式を評価するための小さなスクリプトを作成してみました。
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
- この粗雑な方法や正規表現を使用せずに、式内の文字が整数であるかどうかを確認するより良い方法がわかりません。何か提案はありますか?
- ケースを抽象化する方法はありますか。Rubyにeval("num1 ch num2")関数はありますか?
解決
それは、整数のあなたの定義は、ルビーの一致して確認しますので、
あなたは、文字列が整数、整数(あるかどうかを確認したい場合は)、それを行うためのエレガントな方法です。それらを避ける理由 - あなたはむしろそれが例外をスローするので、正規表現がうまく動作することを使用していないでしょうか?また、整数の場合には、あなたは、単にではない、あなたのスタックにYを押してチャネル、および飛び出るto_i呼び出しを必要としないことに注意してください。他の質問については、ルビーは確かにevalを持っていない。
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
他のヒント
Rubyについては詳しくないので質問には答えられません。ただし、そこにはアルゴリズムの問題があります。加算の場合、オペランドの乗算の順序は関係ありませんが、減算と除算の場合は、最初のオペランドを 2 番目のオペランドで減算して除算する必要があります。1 つ目はスタックのより深いものです。そのため、次の 2 行を入れ替える必要があります。
num1 = my_stack.pop.to_i
num2 = my_stack.pop.to_i
所属していません StackOverflow