2014-05-16 2 views
0

아래 답변을 이해할 수있는 사람이 있습니까? 나는 다음의 rspec 테스트를 통과하는 것이 올바른 대답이라는 것을 알고있다. 또한 이것을 구현하는 다른/간단한 방법이 있습니까? 나는 그것이 그것을 어떻게하는지 이해하지 못하기 때문에.루비 RPN 계산기 - rspec 테스트

def tokens(string) 
    string.split.map{|s| s[/\d/] ? s.to_i : s.to_sym} 
end 

def evaluate(pol) 
     order = [] 
     opps = {:+ => plus, :- => minus, :/ => divide, :* => times } 
     tokens(pol).reverse.chunk{|n| n.is_a?(Integer)}.each{|e,a| e == true ? a.reverse.each{|a| push(a) } : a.each {|a| order.push(a) }} 
     order.reverse.each {|o| (opps[o]) } end 

RSpec에 시험이 시험 루비, RSpec에 시험과 사투를 벌인 사람들을 위해

# extra credit 
    it "tokenizes a string" do 
    calculator.tokens("1 2 3 * + 4 5 - /").should == 
     [1, 2, 3, :*, :+, 4, 5, :-, :/] 
    end 

    # extra credit 
    it "evaluates a string" do 
    calculator.evaluate("1 2 3 * +").should == 
     ((2 * 3) + 1) 

    calculator.evaluate("4 5 -").should == 
     (4 - 5) 

    calculator.evaluate("2 3 /").should == 
     (2.0/3.0) 

    calculator.evaluate("1 2 3 * + 4 5 - /").should == 
     (1.0 + (2 * 3))/(4 - 5) 
    end 

답변

0

, 나는 방법 위의 고장 관리했습니다 아래와 같이 이해 :

1 단계

1. Define operators as procs 

2 단계

,369 1,363,210
2. Utilize Token method to generate the following token = [1, 2, 3, :*, :+] 

3 단계

3. Check if integer and chunk accordingly 

4 단계

4. Check result after chunking, and value of @stack 
    # ==> [true, [1,2,3]]/@stack = [1, 2, 3] 
    # ==> [false, [:*, *+]] @stack = [1, 2, 3 * +] 

5 단계

5. When reaching an operator, the appropriate method is called 
    # Calls times -> @stack.push(@stack.pop * @stack.pop) 
    # (3 * 2) 
    # Calls plus -> @stack.push(@stack.pop + @stack.pop) 

RSpec에 테스트 지금

(3 * 2) + 1

통과해야 0

편집 후의 방법

def evaluate(pol) 
    @stack = [] 

    opps = { 
     :+ => Proc.new {plus}, 
     :- => Proc.new{minus}, 
     :/ => Proc.new{divide}, 
     :* => Proc.new{times} 
     } 

    tokens(pol).chunk{|n| n.is_a?(Integer)}.each do |condition, chunk| 
     if condition == true 
      chunk.each{|a| push(a) } 
     else 
      chunk.each {|o| (opps[o].call)} 
     end 
    end 
    @stack[0] 
end