Comments on Single digit Roman numeral
Parent
Single digit Roman numeral
Given a single character, which is a valid Roman numeral, output its value.
Values
There are 7 valid single character Roman numerals, with the following values:
| Character | Value |
|---|---|
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
Input
- A single character, which will always be one of
IVXLCDM.
Output
- The corresponding value.
- The output value must not be a Roman numeral.
- It is acceptable to have a trailing decimal point
.or.0for some or all of the outputs.
Test cases
As there are only 7 valid inputs, the list of test cases is exhaustive.
Test cases are in the format "input" : output.
"I" : 1
"V" : 5
"X" : 10
"L" : 50
"C" : 100
"D" : 500
"M" : 1000
Scoring
This is a code golf challenge. Your score is the number of bytes in your code.
Explanations are optional, but I'm more likely to upvote answers that have one.
Python 3.8+, 51 byte ```pyt …
3y ago
C, 59 byte ```c h(n){retur …
3y ago
Japt v2.0a0, 22 bytes n …
5mo ago
[Perl], 45 bytes Reads char …
6mo ago
Python 3.8+, 49 byte ```pyt …
6mo ago
[AWK], 80 bytes {split( …
2y ago
[Swift], 114 bytes …
3y ago
Haskell, 62 bytes ``` (\n- …
3y ago
Vyxal, 12 bitsv2, 1.5 or 2 byt …
3y ago
Post
Python 3.8+, 51 byte
lambda n:((i:="IVXLCDM".index(n))%2*4+1)*10**(i//2)
Testing the code:
f=lambda n:((i:="IVXLCDM".index(n))%2*4+1)*10**(i//2)
for s in "IVXLCDM":
print(s, f(s))
The walrus operator stores the index in the variable i, that is used in the exponent.
A much more readable version with the same logic:
def f(n):
i = "IVXLCDM".index(n)
return (i%2*4+1) * 10 ** (i // 2)
Thanks for [Object object] for getting rid of 5 bytes.

2 comment threads