Created
July 25, 2012 15:21
-
-
Save kejadlen/3176758 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
str = ARGV[0].split(/\s+/).join('_') | |
while str.include?('_') | |
str.sub!(/([^_]+)_([^_]+)_([+\-*\/])/, '(\1 \3 \2)') | |
end | |
puts str |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
def postfix_to_infix(str) | |
str = str.split(/[^.\d+\-*\/]/).join(' ') | |
while str !~ /^\(.*\)$/ | |
str.sub!(/([^ ]+) ([^ ]+) ([+\-*\/])/, '(\1\3\2)') | |
end | |
str.gsub(/([+\-*\/])/, ' \1 ').sub(/^\((.*)\)$/, '\1') | |
end | |
class PostfixToInfixTest < Test::Unit::TestCase | |
def test_postfix_to_infix | |
assert_equal '2 + 3', postfix_to_infix('2 3 +') | |
assert_equal '12 + 34', postfix_to_infix('12 34 +') | |
assert_equal '1.2 + 3.4', postfix_to_infix('1.2 3.4 +') | |
assert_equal '(1 - 2) - (3 + 4)', postfix_to_infix('1 2 - 3 4 + -') | |
assert_equal '(56 * (34 + 213.7)) - 678', postfix_to_infix('56 34 213.7 + * 678 -') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment