Project Euler 89 (python, 0.04s)

#-*- coding:utf-8 -*-
from datetime import datetime

def smallest_num(n):
	counter = 0
	num = n
	dict_num = {"0":0, "1":1, "2":2, "3":3, "4":2, "5":1, "6":2, "7":3, "8":4, "9":2}
	if n >= 1000:
		counter += num / 1000
		num = num % 1000
	for i, d in enumerate(str(num)):
		counter += dict_num[d]
	return counter
	
def count_roma(n,last=0):
	dict_roma = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
	I_list = ["V", "X"]
	X_list = ["L", "C"]
	C_list = ["D", "M"]	
	counter = 0
	length = len(n)
	for i, x in enumerate(n):
		if ((length - 1) == i) and last != 1:
			break
		if ((length - 1) == i) and last == 1:
			counter += dict_roma[x]
			break
		if x ==  "C" and n[i +1] in C_list:
			counter -= 100
		elif x == "X" and n[i +1] in X_list:
			counter -= 10
		elif x == "I" and n[i + 1] in I_list:
			counter -= 1
		else:
			counter += dict_roma[x]
	return counter
		
	
def Euler89(file1):
	before, after = 0, 0
	Number = 0
	for d, i in enumerate(file1):
		if d != 999: Number = count_roma(i)
		else:	Number = count_roma(i, 1)
		length = len(str(i))
		if d != 999: before += length - 1
		else: before += length
		after += smallest_num(Number)
	return before - after

def main():
	f = open("roman.txt", "r")
	file = f.readlines()
	f.close()
	
	start = datetime.now()
	answer = Euler89(file)
	end = datetime.now()
	print end - start, answer
	
if __name__ == "__main__":
	main()


replace() を使うと綺麗だし速い。
敗北感。。。

#こっちだと0.000957s
#-*- coding:utf-8 -*-
from datetime import datetime
def Euler89():
	dict_roma = [["DCCCC", "CM"], ["LXXXX", "XC"], ["VIIII", "IX"], ["IIII", "IV"], ["XXXX", "XL"], ["CCCC" , "CD"]]
	f = open("roman.txt", "r")
	file = f.readlines()
	f.close()
	before = ''
	for x in file:
		before += x
	after = before
	for  x in dict_roma:
		after = after.replace(x[0], x[1])
	return len(before) - len(after)

def main():
	start = datetime.now()
	answer = Euler89()
	end = datetime.now()
	print end - start, answer
	
if __name__ == "__main__":
	main()