I have a function roman(x)
that takes an int
(>= 1
) and returns the roman numeral as a string. I have achieved a working example with:
def roman(x: int) -> str:
"""Convert `int` to roman numeral"""
L = [(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')]
y = ""
for val, sym in L:
y += sym*(x//val)
x -= val*(x//val)
return y
>>> roman(399)
'CCCXCIX'
I am asking how to convert the for loop:
y = ""
for val, sym in L:
y += sym*(x//val)
x -= val*(x//val)
return y
Into a list comprehension
return "".join([ ... ])
L
Does not need to be embedded into the list comprehension, and can remain as is. Such that the function is in this form:
def roman(x: int) -> str:
"""Convert into to roman numeral"""
L = [(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')]
# Return list comprehension as a string
return "".join([ ... ])