Postfix to Infix (#148)

  • Thread starter íÉÈÁÉÌ çÏÒÂÕÎÏ×
  • Start date
Í

íÉÈÁÉÌ çÏÒÂÕÎÏ×

Note: parts of this message were removed by the gateway to make it a legal Usenet post.

Sorry, in previous post I forgot about parenthess in case of - and /.

# this program understands simple operations and also sin, cos, tg and ctg
# to use, provide string in RPN as argument
# example: ruby postf2inf '3 5 + sin 5 3 cos + /'
# result in "sin(3 + 5) / (5 + cos(3))"

str_postf=ARGV[0]
str_inf=[]
prior = {'+'=>1,'-'=>1,'*'=>3,'/'=>3}
stack = str_postf.split(' ')

0.upto stack.size-1 do |l|
if ['+','-','*','/'].include?(stack[l])
arg1 = str_inf.pop
arg2 = str_inf.pop
arg1[1]='('+arg1[1]+')' if arg1[0]<prior[stack[l]]
arg1[1]='('+arg1[1]+')' if ['-','/'].include?(stack[l]) and
arg1[0]==prior[stack[l]]
arg2[1]='('+arg2[1]+')' if arg2[0]<prior[stack[l]]
str_inf.push([prior[stack[l]] , arg2[1]+" #{stack[l]} "+arg1[1]])
elsif ['sin','cos','tg','ctg'].include?(stack[l])
str_inf.push([5 , "#{stack[l]}(#{str_inf.pop[1]})"])
else
str_inf.push([5,stack[l]])
end
end

p str_inf.pop[1]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top