Ruby의“Postfix Expressions 평가”프로그램
-
23-08-2019 - |
문제
루비의 포스트 수정 표현을 평가하기 위해 작은 대본을 만들려고했습니다.
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") 함수가 있습니까?
해결책
문자열이 정수인지 확인하려면 Integer ()는 정수의 정의가 루비와 일치하기 때문에 우아한 방법입니다. 예외가 발생하기 때문에 사용하지 않으려면 정규 표현이 잘 작동합니다. 왜 피하십시오. 또한 정수 케이스의 경우 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
다른 팁
나는 루비를 모르기 때문에 당신의 질문에 대답하지 않습니다. 그래도 알고리즘 문제가 있습니다. ADD의 경우, 피연산자의 순서는 중요하지 않지만 뺄셈과 나누기의 경우 첫 번째 피연산자를 두 번째 피연산자로 차감하고 나누어야합니다. 첫 번째는 더 깊은 스택입니다. 결과적 으로이 두 줄을 교환해야합니다.
num1 = my_stack.pop.to_i
num2 = my_stack.pop.to_i
제휴하지 않습니다 StackOverflow