Domanda

Ho provato a fare un piccolo script per valutare le espressioni post-fix in 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
  1. non so un modo migliore per verificare se il carattere nell'espressione è un numero intero senza l'utilizzo di questo metodo di greggio o di espressioni regolari. Voi ragazzi avete qualche suggerimento?
  2. C'è un modo per astratte dei casi. C'è un eval ( "num1 num2 ch") la funzione in Ruby?
È stato utile?

Soluzione

se si desidera controllare se una stringa è un numero intero, Integer () è un elegante modo per farlo, perché rende sicuro che la tua definizione di un intero corrisponde Ruby. Se si preferisce non utilizzare tale perché genera un'eccezione, le espressioni regolari funzionano bene - perché evitarli? Si noti inoltre che nel caso intero, si può semplicemente spingere y sul tuo stack, non ch, e non ha bisogno delle chiamate to_i quando popping. Per quanto riguarda l'altra domanda, rubino ha davvero un 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  

Altri suggerimenti

Non so rubino così io non rispondere alle vostre domande. C'è un problema algoritmico lì, però. Per aggiungere, moltiplicare l'ordine degli operandi non importa, ma per la sottrazione e divisione, si dovrebbe sottrarre e dividere il primo operando per il secondo. Il primo è quello più profondo pila. Di conseguenza, si dovrebbe scambiare queste due righe:

num1 = my_stack.pop.to_i
num2 = my_stack.pop.to_i
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top