The judicious insertion of print()
statements can help you find bugs in your code:
def movie_year(number):
roman = { 1:'I', 5:'V', 10:'X', 50:'L', 100:'C', 500:'D', 1000:'M', }
output = []
divisor = 1000
print(f'movie_year({number})')
for digit in [int(x) for x in str(number)]:
print(f' digit={digit} divisor={divisor}')
if digit <= 3:
# e.g. 3 -> 3*'I' -> 'III'
output.append( roman[divisor] * digit )
elif digit == 4:
output.append( roman[divisor] + roman[divisor * 5] )
elif 5 < digit <= 8:
output.append( roman[divisor * 5] + roman[digit] * (divisor - 5) )
elif digit == 9:
output.append( roman[divisor] + roman[divisor * 10] )
divisor = int(divisor / 10)
print(' ', output)
return ''.join(output)
Here’s what you’ll get:
>>> movie_year(2015)
movie_year(2015)
digit=2 divisor=1000
['MM']
digit=0 divisor=100
['MM', '']
digit=1 divisor=10
['MM', '', 'X']
digit=5 divisor=1
['MM', '', 'X']
'MMX'
For production software, print()
might not be a good long term solution. Python’s comprehensive logging library is a better choice:
Daniel Faria on June 10, 2020
Beautiful!