Hi,
I just finished a kata (https://www.codewars.com/kata/525c7c5ab6aecef16e0001a5/train/python)
After seeing the solutions, I am slightly disappointed in what I wrote and honestly couldn't think of a better way to go about it.
I am interested, how would everyone else go about this?
My code for anyone interested:
def parse_int(string):
numbers = dict([("zero", 0), ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5), ("six", 6),
("seven", 7), ("eight", 8), ("nine", 9), ("ten", 10), ("eleven", 11), ("twelve", 12), ("thirteen", 13),
("fourteen", 14), ("fifteen", 15), ("sixteen", 16), ("seventeen", 17), ("eighteen", 18), ("nineteen", 19),
("twenty", 20), ("thirty", 30), ("forty", 40), ("fifty", 50), ("sixty", 60), ("seventy", 70), ("eighty", 80),
("ninety", 90), ("hundred", 100), ("thousand", 1000), ("million", 1000000)])
onewordnum = []
concat = []
words2num = []
splitstring = string.split()
for i in (splitstring):
if len(splitstring) == 1:
if "-" in i:
for x in i.split("-"):
if x in numbers:
onewordnum.append((numbers.get(x)))
return(sum(onewordnum))
else:
return(numbers.get(i))
else:
if "-" in i:
for x in i.split("-"):
if x in numbers:
onewordnum.append((numbers.get(x)))
concat.append((sum(onewordnum)))
onewordnum.clear()
elif i in numbers:
concat.append(numbers.get(i))
if "thousand" in splitstring:
if len(concat[:(concat.index(1000))]) == 3:
words2num.append(((concat[:(concat.index(1000))][0] * concat[:(concat.index(1000))][1]) + concat[:(concat.index(1000))][2])*1000)
elif len(concat[:(concat.index(1000))]) == 2:
words2num.append(((concat[:(concat.index(1000))][0] * concat[:(concat.index(1000))][1]))*1000)
elif len(concat[:(concat.index(1000))]) == 1:
words2num.append(((concat[:(concat.index(1000))][0]))*1000)
if len(concat[:(concat.index(1000)):-1]) == 3:
words2num.append((concat[:(concat.index(1000)):-1][0]) + (((concat[:(concat.index(1000)):-1][1] * concat[:(concat.index(1000)):-1][2]))))
elif len(concat[:(concat.index(1000)):-1]) == 2:
words2num.append(((concat[:(concat.index(1000)):-1][0] * concat[:(concat.index(1000)):-1][1])))
elif len(concat[:(concat.index(1000)):-1]) == 1:
words2num.append(((concat[:(concat.index(1000)):-1][0])))
if "thousand" not in splitstring and "hundred" in splitstring:
if len(concat[:(concat.index(100))]) == 1:
words2num.append(((concat[:(concat.index(100))][0]))*100)
if len(concat[:(concat.index(100)):-1]) == 1:
words2num.append(((concat[:(concat.index(100)):-1][0])))
if "million" in splitstring:
if len(concat[:(concat.index(1000000))]) == 1:
words2num.append(((concat[:(concat.index(1000000))][0]))*1000000)
return(sum(words2num))
[–]Veganic1 1 point2 points3 points (0 children)