Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. from math import floor
  2.  
  3. def romanize_digit(digit: int, place: str):
  4. """
  5. Place should take either 'I', 'X', 'C', or 'M'
  6. """
  7. index = ["I","X","C","M"]
  8. fives = {
  9. "I": "V",
  10. "X":"L",
  11. "C":"D",
  12. "M": "MMMMM"
  13. }
  14.  
  15. if digit == 9:
  16. next_place = index[index.index(place)+1]
  17. return place+next_place if place != 'M' else 'M'*9
  18.  
  19. elif digit > 5:
  20. return fives[place]+place*(digit % 5)
  21.  
  22. elif digit == 4:
  23. return place+fives[place]
  24. else:
  25. return place*digit
  26.  
  27. def roman_numeral(num: int) -> str:
  28. """
  29. Let's approach this digit by digit. So we can turn the int into a list of chars:
  30. 238 --> ['2','3','8']
  31. """
  32. roman_numerals = ''
  33.  
  34. digits = [int(c) for c in str(num)]
  35. index = ["I","X","C","M"]
  36.  
  37. for i in range(min(len(digits), 4 if num < 10000 else 3)):
  38. place = index[i]
  39. roman_numerals = romanize_digit(digits[-i-1], place) + roman_numerals
  40.  
  41. if num > 10000:
  42. roman_numerals = 'M'*(floor(num/1000)) + roman_numerals
  43.  
  44. return roman_numerals
  45.  
  46.  
  47. def test_roman_numeral():
  48. assert roman_numeral(3) == "III"
  49. assert roman_numeral(7) == "VII"
  50. assert roman_numeral(9) == "IX"
  51. assert roman_numeral(12) == "XII"
  52. assert roman_numeral(238) == "CCXXXVIII"
  53. assert roman_numeral(6000) == "MMMMMM"
  54. assert roman_numeral(11001) == "MMMMMMMMMMMI"
  55. assert roman_numeral(19011) == "MMMMMMMMMMMMMMMMMMMXI"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement