Skip to content

Instantly share code, notes, and snippets.

@seanballais
Created May 17, 2018 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanballais/0a2877b172b2f8f263de5015737fdb19 to your computer and use it in GitHub Desktop.
Save seanballais/0a2877b172b2f8f263de5015737fdb19 to your computer and use it in GitHub Desktop.
Converts a whole number to roman numberals.
import sys
def main():
roman_numerals = {
0: '', 1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V',
6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX',
10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50: 'L',
60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC',
100: 'C', 200: 'CC', 300: 'CCC', 400: 'CD', 500: 'D',
600: 'DC', 700: 'DCC', 800: 'DCCC', 900: 'CM',
1000: 'M'
}
multiple = 0
roman_numeral_repr = ''
whole_number = int(input('Enter a number: '))
if whole_number >= 4000:
print('Cannot convert numbers greater than 4000... for now. We need to use a line above letter.')
sys.exit(1)
while whole_number != 0:
digit = (whole_number % 10) * (10 ** multiple)
if (digit >= 1000):
letter_occurences = digit / 1000
roman_numeral = str(roman_numerals[1000]) * letter_occurences
else:
roman_numeral = str(roman_numerals[digit])
roman_numeral_repr = roman_numeral + roman_numeral_repr
whole_number //= 10
multiple += 1
print('Roman Numeral: {}'.format(roman_numeral_repr))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment