Advertisement
KoBeWi

ONP

Jan 15th, 2019
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.80 KB | None | 0 0
  1. def priority(oper)
  2.   case oper
  3.     when '*','/'
  4.     2
  5.     when '^'
  6.     3
  7.     when '('
  8.     0
  9.     when nil
  10.     -1
  11.   else
  12.     1
  13.   end
  14. end
  15.  
  16. def onpize(input)
  17.   input = input.split(//)
  18.   out = ''
  19.   stack = []
  20.  
  21.   while !input.empty?
  22.     elem = input.shift
  23.    
  24.     if 'abcdef0123456789'.include? elem
  25.       out << elem
  26.     elsif '+-*/^'.include? elem
  27.       while priority(stack.last) >= priority(elem)
  28.         puts [priority(elem), priority(stack.last)].join
  29.         out << stack.pop
  30.       end
  31.      
  32.       stack.push(elem)
  33.     elsif elem == '('
  34.       stack.push(elem)
  35.     elsif elem == ')'
  36.       while (elem2 = stack.pop) != '('
  37.         out << elem2
  38.       end
  39.     end
  40.   end
  41.  
  42.   while !stack.empty?
  43.     out << stack.pop
  44.   end
  45.  
  46.   puts
  47.   out
  48. end
  49.  
  50. puts onpize(gets.chomp)
  51. gets
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement