+ 2
how can we write code for roman numerals?
3 Antworten
+ 2
oh..I actually thought the other way around, converting Roman to number conversion. anyway, you need extra logic in your example.
1986 is input, but we don't know input.
steps 1-3 look good.
(3. valid if decimal is greater than 0 and less than 4000, for "small Roman numeral") and included below
I prefer recursion here with lists, but a while loop is sufficient as well:
4. numList = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
romanList = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
5. check and convert-
if arabic_number > 0 and arabic_number < 4000
for i in range(1, 13) # max 13 in decimal list
while (arabic_number >= numList[i])
arabic_number -= numList[i]
roman_number += romanList[i]
print (roman_number)
as I finished this, I realized it's the same as Jasper's, so my bad Jasper, your logic is correct. I propose using a dictionary (ordered) rather than two lists. same logic. I'll post the recursive version later. :)
sorry, I meant to write pseudo-code and ended up using python. ;p
+ 3
Interesting question. Let's try to translate a number like 1986 to a roman numeral.
1. create the variable "roman_number" (or whatever you want to call it).
2. ask for user input (enter a number), store this in the variable "arabic_number"
3. check whether or not input is valid
4. divide by 1000, and add (concatonate or append) an 'M' times the result to roman_numeral. then change arabic_number to be the remainder (using the % operator)
5. divide by 900, add result times 'CM' to roman_number. change arabic number to be the remainder
6. same for: 500 and 'D'
7. 400 and 'CD'
8. 100 and 'C'
9. 90 and 'XC'
10. 50 and 'L'
11. 40 and 'XL'
12. 10 and 'X'
13. 9 and 'IX'
14. 5 and 'V'
15. 4 and 'IV'
16. 1 and I
17. then print the result
This should work for all numbers from 1 to a few thousand. Please let me know if I made a mistake, or if there are more elegant methods.
0
I did this way back in college with switch cases (c++ and Unix c). unfortunately, Python doesn't have switch cases per se, but you can use dictionary mappings. hope this gets you started...