- #1
ergospherical
- 1,055
- 1,347
Excluding spaces and hyphens, how many letters are there in a given number between 1 and 1000 (inclusive)? How can I make my algorithm more efficient?
Python:
dig_lens = [4,3,3,5,4,4,3,5,5,4]
tens_lens = [0,3,6,6,6,5,5,7,6,6]
teens_lens = [0,6,6,8,8,7,7,9,8,8]
def num_letters(n):
nlist = []
while(n>=1):
nlist.append(n%10)
n//=10
length = len(nlist)
if(n==1000):
return 11
count = 0
if(length == 1):
count = count + dig_lens[n]
if(length == 2):
if(nlist[1]==1 and nlist[0]>0):
count = count + teens_lens[nlist[0]]
else:
count = count + tens_lens[nlist[1]] + dig_lens[nlist[0]]
if(length == 3):
count = count + dig_lens[nlist[2]] + 7
if(nlist[1]==0 and nlist[0]>0):
count = count + 3 + dig_lens[nlist[0]]
elif(nlist[1]==1 and nlist[0]>0):
count = 3 + count + teens_lens[nlist[0]]
else:
count = 3 + count + tens_lens[nlist[1]] + dig_lens[nlist[0]]
return count
##e.g.##
print(num_letters(816))