gpt4 book ai didi

ruby - Reverse Polish Notation (RPN) 或 Postfix Notation 的重构反馈

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:17 24 4
gpt4 key购买 nike

Dev Bootcamp 的作业前练习之一是 RPN 计算器。我成功了,但想要重构反馈。非常感谢任何有助于使此代码更清晰的帮助。

class RPNCalculator
def evaluate(rpn)
a = rpn.split(' ')
array = a.inject([]) do |array, i|
if i =~ /\d+/
array << i.to_i
else
b = array.pop(2)
case
when i == "+" then array << b[0] + b[1]
when i == '-' then array << b[0] - b[1]
when i == '*' then array << b[0] * b[1]
when i == '/' then array << b[0] / b[1]
end
end
end
p array.pop
end
end

calc = RPNCalculator.new
calc.evaluate('1 2 +') # => 3
calc.evaluate('2 5 *') # => 10
calc.evaluate('50 20 -') # => 30
calc.evaluate('70 10 4 + 5 * -') # => 0

最佳答案

class RPNCalculator
def evaluate rpn
array = rpn.split(" ").inject([]) do |array, i|
if i =~ /\d+/
array << i.to_i
else
b = array.pop(2)
array << b[0].send(i, b[1])
end
end
p array.pop
end
end

关于ruby - Reverse Polish Notation (RPN) 或 Postfix Notation 的重构反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com