944,119 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 7279
  • Python RSS
0

Roman Numerals (Python)

by on Jan 26th, 2007
Let Python do the work for you and figure out the roman numerals for a given integer. I have to ask you to keep the integer values somewhat reasonably low (from 1 to 4999), since roman numerals from 5000 on use characters with an overline and most PCs don't have those in the character set.
Last edited by vegaseat; Oct 17th, 2009 at 4:25 pm.
Python Code Snippet (Toggle Plain Text)
  1. # convert an integer to a roman numeral
  2. # keep it reasonable since from 5000 on special characters are used
  3. # see also: http://en.wikipedia.org/wiki/Roman_numerals
  4. # tested with Python24 vegaseat 25jan2007
  5.  
  6. def int2roman(number):
  7. numerals = { 1 : "I", 4 : "IV", 5 : "V", 9 : "IX", 10 : "X", 40 : "XL",
  8. 50 : "L", 90 : "XC", 100 : "C", 400 : "CD", 500 : "D", 900 : "CM", 1000 : "M" }
  9. result = ""
  10. for value, numeral in sorted(numerals.items(), reverse=True):
  11. while number >= value:
  12. result += numeral
  13. number -= value
  14. return result
  15.  
  16. print int2roman(input("Enter an integer (1 to 4999): "))
  17.  
  18. """
  19. Enter an integer (1 to 4999): 2007
  20. MMVII
  21. """
Comments on this Code Snippet
Oct 15th, 2009
0

Re: Roman Numerals (Python)

i'm just playing around with python and decided to try this code out but keep getting a syntax error pointing to the colon after the 1 in,
Newbie Poster
pythonuser18 is offline Offline
2 posts
since Oct 2009
Oct 15th, 2009
0

Re: Roman Numerals (Python)

I just tested it with python 2.6 and it works. For python 3.1, I had to change the last statement to
python Syntax (Toggle Plain Text)
  1. print(int2roman(int(input("Enter an integer (1 to 4999): "))))
and it works.
Posting Maven
Gribouillis is offline Offline
2,656 posts
since Jul 2008
Oct 15th, 2009
0

Re: Roman Numerals (Python)

@pythonuser18
you used () instead of {}
a dictionary container needs the curly braces.
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 16th, 2009
0

Re: Roman Numerals (Python)

def DecToRom (number) :
numerals={1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M"}
result=""
for value, numeral in sorted(numerals.items(), reverse=True):
while number >= value:
result += numeral
number -= value
return result
print DecToRom(raw_input(“Decimal number: “))

could someone tell me why this isn't working? It says Syntax Error: invalid syntax

I know the indents aren't formatted correctly on this post, but they are as they are suppose to be in python
Last edited by pythonuser18; Oct 16th, 2009 at 12:57 am.
Newbie Poster
pythonuser18 is offline Offline
2 posts
since Oct 2009
Oct 16th, 2009
1

Re: Roman Numerals (Python)

@@pythonuser18 For reference, I got it working, with python 2.6 and this last line:
python Syntax (Toggle Plain Text)
  1. print DecToRom(int(raw_input("Decimal number: ")))
Posting Maven
Gribouillis is offline Offline
2,656 posts
since Jul 2008
Oct 16th, 2009
1

Re: Roman Numerals (Python)

Roman to integer. Note that it will take something like XXIXV and convert it. If someone already has a routine to check for valid input, please post it. And I'm afraid we've just eliminated one standard homework question. Oh well, nothing lasts forever.
Python Syntax (Toggle Plain Text)
  1. roman_to_decimal = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, \
  2. 'D': 500, 'M': 1000 }
  3.  
  4. roman = raw_input("Enter the roman numeral to convert to arabic: ").upper()
  5.  
  6. converted = True
  7. arabic = 0
  8. for n in range(0, len(roman)-1):
  9. this_char = roman[n]
  10. next_char = roman[n+1]
  11. if (this_char in roman_to_decimal) and \
  12. (next_char in roman_to_decimal):
  13.  
  14. this_number = roman_to_decimal[this_char]
  15. next_number = roman_to_decimal[next_char]
  16. print "converting %s to %d....." % (this_char, this_number),
  17. if this_number < next_number:
  18. arabic -= this_number
  19. else:
  20. arabic += this_number
  21. print "Total now =", arabic
  22.  
  23. else:
  24. print "\nthis chr (%s) or next chr (%s) is not a valid roman numeral" \
  25. % (this_char, next_char)
  26. converted = False
  27. break
  28.  
  29. if converted:
  30. ## add last roman numeral
  31. arabic += roman_to_decimal[roman[len(roman)-1]]
  32.  
  33. print "\nThe roman numeral", roman, "is equal to",arabic
Nearly a Posting Maven
woooee is offline Offline
2,307 posts
since Dec 2006
Jun 15th, 2010
0

Re: Roman Numerals (Python)

A quick solution that does both directions:

python Syntax (Toggle Plain Text)
  1.  
  2. # Roman Numerals
  3. # 2010-06-15, Eljakim Schrijvers
  4.  
  5. mapping = [ ('cd','cccc'), ('xl','xxxx'),('iv','iiii'),('d','ccccc'),('l','xxxxx'),('v','iiiii'), ('cm','ccccccccc'), ('xc','xxxxxxxxx'),('ix','iiiiiiiii')]
  6. mapping.reverse()
  7. bignums = [ ('m',1000), ('c',100), ('x', 10), ('i',1) ]
  8.  
  9. def fromroman(x):
  10. for (kort, lang) in mapping: x= x.replace(kort, lang)
  11. x = '+'.join(list(x))
  12. for (karakter, waarde) in bignums: x = x.replace(karakter, str(waarde))
  13. if x=='': x = '0'
  14. return eval(x)
  15.  
  16. def toroman(x):
  17. val = ''
  18. for (karakter, waarde) in bignums:
  19. val = val + (x / waarde) * karakter
  20. x = x % waarde
  21. for (kort, lang) in mapping:
  22. val = val.replace(lang,kort)
  23. return val
Newbie Poster
eljakim is offline Offline
2 posts
since Jun 2010
Jun 15th, 2010
0

Re: Roman Numerals (Python)

Nice concept but fails in execution:
Python Syntax (Toggle Plain Text)
  1. # Roman Numerals
  2. # 2010-06-15, Eljakim Schrijvers
  3.  
  4. # bug testing, translation of variables and reformating
  5. # Tony Veijalainen 2010-06-16
  6.  
  7. mapping = [ ('cd','cccc'),
  8. ('xl','xxxx'),
  9. ('iv','iiii'),
  10. ('d','ccccc'),
  11. ('l','xxxxx'),
  12. ('v','iiiii'),
  13. ('cm','ccccccccc'),
  14. ('xc','xxxxxxxxx'),
  15. ('ix','iiiiiiiii')]
  16.  
  17.  
  18. mapping.reverse()
  19. bignums = [ ('m',1000), ('c',100), ('x', 10), ('i',1) ]
  20.  
  21. def fromroman(x):
  22. for (shortv, longv) in mapping: x= x.replace(shortv, longv)
  23. x = '+'.join(list(x))
  24. for (character, word) in bignums: x = x.replace(character, str(word))
  25. if x=='': x = '0'
  26. return eval(x)
  27.  
  28. def toroman(x):
  29. val = ''
  30. for (character, word) in bignums:
  31. val = val + (x / word) * character
  32. x = x % word
  33. for (shortv, longv) in mapping:
  34. val = val.replace(longv,shortv)
  35. return val
  36.  
  37. for i in range(5000):
  38. if fromroman(toroman(i)) != i:
  39. print ('Bug found: %i, %s, %s' % (i,toroman(i),fromroman(toroman(i))))

The code gives plenty of bugs printed.
Last edited by pyTony; Jun 15th, 2010 at 6:57 pm.
Industrious Poster
pyTony is offline Offline
4,208 posts
since Apr 2010
Jun 15th, 2010
1

Re: Roman Numerals (Python)

Got it passing my test by rearranging the values that were present in bug cases in the mapping (cleaned up multiletter expressions by *):
Python Syntax (Toggle Plain Text)
  1. # Roman Numerals
  2. # 2010-06-15, Eljakim Schrijvers
  3.  
  4. # bug testing, translation of variables and reformating
  5. # Tony Veijalainen 2010-06-16
  6.  
  7. mapping = [ ('d',5*'c'),
  8. ('l',5*'x'),
  9. ('v',5*'i'),
  10. ('cm',9*'c'),
  11. ('xc',9*'x'),
  12. ('ix',9*'i'),
  13. ('cd',4*'c'),
  14. ('iv',4*'i'),
  15. ('xl',4*'x')]
  16.  
  17.  
  18. mapping.reverse()
  19. bignums = [ ('m',1000), ('c',100), ('x', 10), ('i',1) ]
  20.  
  21. def fromroman(x):
  22. for (shortv, longv) in mapping: x= x.replace(shortv, longv)
  23. x = '+'.join(list(x))
  24. for (character, word) in bignums: x = x.replace(character, str(word))
  25. if x=='': x = '0'
  26. return eval(x)
  27.  
  28. def toroman(x):
  29. val = ''
  30. for (character, word) in bignums:
  31. val = val + (x / word) * character
  32. x = x % word
  33. for (shortv, longv) in mapping:
  34. val = val.replace(longv,shortv)
  35. return val
  36.  
  37. bugs=0
  38. for i in range(5000):
  39. if fromroman(toroman(i)) != i:
  40. print ('Bug found: %i, %s, %s' % (i,toroman(i),fromroman(toroman(i))))
  41. bugs+=1
  42.  
  43. print(('Number of bugs found: %i' % bugs) if bugs else 'Test passed!')
  44.  
  45.  
  46. """ Output:
  47. Test passed!
  48. """
Last edited by pyTony; Jun 15th, 2010 at 7:25 pm.
Industrious Poster
pyTony is offline Offline
4,208 posts
since Apr 2010
Message:
Previous Thread in Python Forum Timeline: Counter() problem
Next Thread in Python Forum Timeline: List all instances of a class





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC