Menu

gitpiper

to_roman_numeral python Code Snippet in 2024

mathstringintermediate

Last Updated: 16 September 2024

Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).

  • Create a lookup list containing tuples in the form of (roman value, integer).
  • Use a for loop to iterate over the values in lookup.
  • Use divmod() to update num with the remainder, adding the roman numeral representation to the result.
def to_roman_numeral(num): lookup = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] res = '' for (n, roman) in lookup: (d, num) = divmod(num, n) res += roman * d return res
to_roman_numeral(3) # 'III' to_roman_numeral(11) # 'XI' to_roman_numeral(1998) # 'MCMXCVIII'

python snippet similar to to_roman_numeral For You in September 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️