ポーランド記法の問題。
何度かtryしましたが、scoreが100にならないです(85-95)。なんかケース漏れがありそうだけど、どういうケースでNGになっているのかcodeeval上ではわからないのが残念。
些細なミスのような気がしますが、一旦諦めました。
CHALLENGE DESCRIPTION:
You are given a prefix expression. Write a program which evaluates it.
INPUT SAMPLE:
Your program should accept a file as its first argument. The file contains one prefix expression per line.
For example:
* + 2 3 4
Your program should read this file and insert it into any data structure you like. Traverse this data structure and evaluate the prefix expression. Each token is delimited by a whitespace. You may assume that sum ‘+’, multiplication ‘*’ and division ‘/’ are the only valid operators appearing in the test data.
OUTPUT SAMPLE:
Print to stdout the output of the prefix expression, one per line.
20
CONSTRAINTS:
- The evaluation result will always be an integer ≥ 0.
- The number of the test cases is ≤ 40.
My Code
stackを使った解き方。
def prefix_expression(exps) stack = [] exps.reverse.each do |exp| if exp.match(/\d+/) stack << exp else x = stack.pop y = stack.pop stack << (x.to_i.send(exp, y.to_i)) end end stack[0] end ARGF.each_line do |line| puts prefix_expression(line.chomp.split) end
もう1個。正規表現を使った計算例。
CALC_PATTERN = %r{([+*/]) (\d+) (\d+)} def prefix_expression(str) match = str.match(CALC_PATTERN) return str unless match ope, x, y = match.captures result = eval("#{x} #{ope} #{y}") str = match.pre_match + result.to_s + match.post_match prefix_expression(str) end ARGF.each_line do |line| puts prefix_expression(line.chomp) end