Get the number of letters in a number

jcao219 0 Tallied Votes 173 Views Share

This is not my code! Taken from this SO post.

You can use this to get the number of letters in the English representation of an integer, from 0 to 99.
So for example 5 (five) is len("five") which is 4.

len_of_num = lambda x: 3+int('1yrof7i9b1lsi207bozyzg2m7\
sclycst0zsczde5oks6zt8pedm\
nup5omwfx56b29',36)/10**x%10

for x in range(100):
    print "The length of the word for {0} is {1}.".format(x,
                                                         len_of_num(x))
TrustyTony 888 pyMod Team Colleague Featured Poster

Seems to work until 20, then does not count dash in numbers like twenty-one, over 99 does not work.

Here my test and suggestion if you need number as string using more conventinal base than 36 (16)

from __future__ import print_function   ## let's practice Python 3 printing
import sys
sys.path.append('D:\test')  ## put here the location of the snippet
from intoeng import inttoeng ## replace with name of the file you saved integer to English snippet

def numberlength(x):
    try:
        return int('433544355436688779886aacbbaccb6aacbbaccb599baa9bba599baa9bba599baa9bba7bbdccbddc6aacbbaccb6aacbbaccb'[x],16)
    except IndexError:
        raise ValueError,'Number word length out of range 0..99'

##  string copied from run from:
##  res=''
##  for i in range(100):
##      res+=hex(len(inttoeng(i)))[-1]
##  print res


### from original post
len_of_num = lambda x: 3+int('1yrof7i9b1lsi207bozyzg2m7\
sclycst0zsczde5oks6zt8pedm\
nup5omwfx56b29',36)/10**x%10

for x in range(101): ## extended to see behaviour with wrong input
    # this is test of string, will of course match as the
    # inttoeng is source of information in string,
    # 100 will raise error from numberlength if next line uncommented
    len_of_num=numberlength 
    diff = len(inttoeng(x))-len_of_num(x)
    print("The length of the word for {0} is {1}".
          format(x,
                 len_of_num(x),
                 ),
          ", {0}, difference {1}".
          format(len(inttoeng(x)), diff) if diff
          else ' matching.'
    )
TrustyTony 888 pyMod Team Colleague Featured Poster

Posted my version to SO link with original '-' does not count counts:

n=input();r='%i is '%n
while n-4:n=int('43354435543668877988699baa9bba699baa9bba588a998aa9588a998aa9588a998aa97aacbbaccb699baa9bba699baa9bba'[n],16);r+='%i.\n%i is '%(n,n)
print r+'magic.'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.