Created
April 24, 2012 18:29
-
-
Save avdgaag/2482383 to your computer and use it in GitHub Desktop.
Kata: Roman Numerals
This file contains 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
import unittest | |
def toRoman(n): | |
""" | |
Convert an integer to Roman numerals. Returns an empty string for 0. | |
""" | |
if n == 0: | |
return '' | |
map = { 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C' } | |
key = max(k for k, v in map.iteritems() if k <= n) | |
times = n / key | |
remainder = n % key | |
return map[key] * times + toRoman(remainder) | |
class TestRomanNumerals(unittest.TestCase): | |
def test_zero(self): | |
self.assertEqual('', toRoman(0)) | |
def test_one(self): | |
self.assertEqual('I', toRoman(1)) | |
def test_fity(self): | |
self.assertEqual('L', toRoman(50)) | |
def test_two(self): | |
self.assertEqual('II', toRoman(2)) | |
def test_twenty(self): | |
self.assertEqual('XX', toRoman(20)) | |
def test_four(self): | |
self.assertEqual('IV', toRoman(4)) | |
def test_nineteen(self): | |
self.assertEqual('XIX', toRoman(19)) | |
if __name__ == '__main__': | |
unittest.main() |
This file contains 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 'rspec' | |
def to_roman(n) | |
return '' if n.nil? || n == 0 | |
map = { 1 => 'I', 4 => 'IV', 5 => 'V', 9 => 'IX', 10 => 'X', 40 => 'XL', 50 => 'L', 90 => 'XC', 100 => 'C' } | |
base = map.keys.sort.reverse.find { |x| x <= n } | |
times, remainder = n.divmod(base) | |
map[base] * times + to_roman(remainder) | |
end | |
describe 'converting roman numerals' do | |
{ | |
1 => 'I', | |
2 => 'II', | |
3 => 'III', | |
4 => 'IV', | |
5 => 'V', | |
6 => 'VI', | |
9 => 'IX', | |
10 => 'X', | |
11 => 'XI', | |
20 => 'XX', | |
25 => 'XXV', | |
40 => 'XL', | |
49 => 'XLIX', | |
50 => 'L', | |
90 => 'XC', | |
100 => 'C', | |
194 => 'CXCIV', | |
200 => 'CC' | |
}.each do |k, v| | |
it "converts #{k} to #{v}" do | |
to_roman(k).should == v | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment