I'm a beginner as you can see and I would like to know how I can improve my code. Studying for 6 months now. Thank you.
roman_dict = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD',
500: 'D', 900: 'CM', 1000: 'M'}
divide_list = [1000, 100, 10, 1]
def not_in_dict(fixed_decimal, divide_num):
sub_count = 0
sub_roman_multi = roman_dict[divide_num]
temp_decimal = fixed_decimal
while temp_decimal not in roman_dict:
temp_decimal -= divide_num
sub_count += 1
return roman_dict[temp_decimal]+(sub_count*sub_roman_multi)
def decimal_to_roman(decimal):
original_decimal = decimal
roman = ""
for divide_num in divide_list:
if decimal >= divide_num:
reminder = decimal//divide_num
if(reminder >= 1) and ((reminder*divide_num) in roman_dict):
roman += roman_dict[(reminder*divide_num)]
decimal -= reminder*divide_num
else:
roman += not_in_dict(reminder*divide_num, divide_num)
decimal -= (reminder*divide_num)
return str(original_decimal)+' = '+roman
1 Answer 1
If you use a list of tuples instead of a dictionary and reverse the order, you can simply iterate over it. Your while
loop also becomes a lot easier to understand and there is no longer any need to outsource it to another function that returns the literal and its count.
Instead of manually adding strings (something you should basically never do in in Python), use str.join
.
ROMAN_LITERALS = [(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')]
def decimal_to_roman(x):
out = []
for value, literal in ROMAN_LITERALS:
while x >= value:
x -= value
out.append(literal)
return "".join(out)
Instead of the while
loop you can also use integer division like you did:
def decimal_to_roman(x):
out = []
for value, literal in ROMAN_LITERALS:
n = x // value # will be 0 if value is too large
out.extend([literal] * n) # will not do anything if n == 0
x -= n * value # will also not do anything if n == 0
return "".join(out)
-
1\$\begingroup\$ @Ofeks: If this helped you, consider accepting it as the correct answer (by clicking the checkmark to the left of the answer). It is customary to wait about 24 hours, though, to give everyon on the globe a chance to answer and not discourage other people from commenting. \$\endgroup\$Graipher– Graipher2019年04月04日 14:01:34 +00:00Commented Apr 4, 2019 at 14:01