Roman Sum

history.com history.com

You thought summation was easy, until you accidentally time-traveled to ancient Rome and you have to deal with arithmetic such as

C C V I I + C X X I I I = C C C X X X \mathtt{CCVII+CXXIII=CCCXXX}

Fortunately, you brought a roman numeral cheatsheet.

I V X L C D M
1 5 10 50 100 500 1000

This file contains 100 space-separated roman numerals. What is the sum of all these numbers written in decimal representation?

Notes :


The answer is 97078.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

3 solutions

Christopher Boo
Jul 7, 2016

Since we are not dealing with Subtractive Notation, we just need to map the roman numerals to decimals as presented in the cheatsheet above and sum them up.

1
2
3
4
m = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000, ' ':0}

L = raw_input()
print sum([m[c] for c in L])

Unlike list where the indexes are non-negative integers, dictionary let us define our own indexes. Literally, m['I'] = 1 and so on. However, note that there's a map of space to 0 at the end of the dictionary. This is because the input are space-separated and we want to ignore those.

This is a very good use of Python dictionary. It reduces tedious if-else statement and provide more readability.

The dictionary trick is certainly very neat. Is there a similar analogue in C++?

Agnishom Chattopadhyay - 4 years, 11 months ago

Log in to reply

Yes, there is. In C++11, you can use std::map for a dictionary (you'd need to #include<map> at the start)

1
std::map<char,int> m={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000},{' ',0}};

Prasun Biswas - 4 years, 11 months ago
Ratul Pan
Jul 8, 2016

Or you can simply copy - paste the whole text into Ms Word and then replace M by another letter and it will show the number of replacements.
Then you can multiply it by its face value i.e. 1000 for M.
Repeat this for all the alphabets and the answer will come to be 97078

Similar approach to Christopher:

1
2
3
4
5
roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
import urllib2
words = urllib2.urlopen("http://pastebin.com/raw/gMkXnAvw").read().split()
hindu = lambda s: sum([roman[i] for i in s])
print sum(map(hindu, words))

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...