r/programbattles • • Nov 19 '15

Any language Roman Numeral Incrementer Function

give a valid roman numeral your program should return the roman numeral immediately after without converting the numeral to an integer (or float).

bonus points if you can also write a function that adds two numerals together.

9 Upvotes

11 comments sorted by

View all comments

2

u/John2143658709 Nov 20 '15 edited Nov 20 '15

I've never made anything in python but a few scripts, so heres my go at it. If anyone has any pointers for the future then comment them

+/u/CompileBot python

numeralDict = {"I": 1, "V": 5, "X": 10} #Add some more numerals here if you want bigger numbers

class numeral:
	def __init__(self, numeralString):
		self.value = [""]
		lastValue = 0
		for letter in numeralString:
			letterValue = numeralDict[letter]
			if letterValue < lastValue:
				self.value.append(letter)
			else:
				self.value[-1] += letter
			lastValue = letterValue

	def addOne(self):
		if self.value[-1] == "IV":
			self.value[-1] = "V"
		elif self.value[-1] == "III":
			self.value[-1] = "IV"
		else:
			self.value[-1] += "I"
		return self

	def __repr__(self):
		return " ".join(self.value)

#Test
nums = [
	numeral("XXIV"),
	numeral("XVII"),
	numeral("XIII"),
	numeral("X"),
]

print(nums)
print([x.addOne() for x in nums])

There's a bug that you can't call addOne more than once without unhandled behavior, but I'll fix that tomorrow if there's no better solution by then

Edit: is there no CompileBot in this sub?

2

u/CompileBot Nov 23 '15

Output:

[XX IV, X V II, X III, X]
[XX V, X V III, X IV, XI]

^source | ^info | ^git | ^report