[Tutor] puzzled by main()
Dick Moores
rdm at rcblue.com
Fri Aug 20 07:53:54 CEST 2004
I wrote intSpell.py for practice with integers, strings and modules. It
works fine by itself, but I'd like to figure out how to use it as a
module which I can import and use as intSpell(n). Is my use of main() the
problem? Or if not, what should I do?
intSpell.py will take an integer n and create a string that spells out n.
Not completely, but as shown by these examples:
123000000 -> 123 million
12008787987-> 12 billion, 8 million, 787 thousand, 987
123000879870 -> 123 billion, 879 thousand, 870
Thanks, tutors.
Dick Moores
-------------- next part --------------
def convertNToString(n):
"convert integer to string"
return str(n)
def regularizeFirstGroup(s):
"prepend enough zeros, if any needed, to make a group of 3 digits: 45-> 045"
if len(s) % 3 != 0:
numOfZerosToPrepend = 3 - (len(s) % 3)
stringOfZerosToPrepend = "0" * numOfZerosToPrepend
s = stringOfZerosToPrepend + s
return s
else:
return s
# example: illionNum of group "345" in "111345666000" is "2"
def ComputeIllionNum(s):
"find illionNum of group"
illionNum = len(s) / 3 - 1
return illionNum
#example: illionName of group "111" in "111345666000" is "billion"
def illionNumToName(illionNum):
"find illionName of group, given its illionNum"
names = [ \
"",
"thousand",
"million",
"billion",
"trillion",
"quadrillion",
"quintillion",
"sextillion",
"septillion",
"octillion",
"nonillion",
"decillion",
"undecillion",
"duodecillion",
"tredecillion",
"quattuordecillion",
"quindecillion",
"sexdecillion",
"septendecillion",
"octodecillion",
"novemdecillion",
"vigintillion"]
illionName = names[illionNum]
return illionName
def extractGroup(s):
"get group to work on"
group = s[:3]
return group
def stripFrontZeros(r):
"strip zeros at front of group, if any. E.g., 045 -> 45, 003 -> 3"
if int(r) == 0:
return ""
while r[0] == "0":
r = r[1:]
return r
def prepareGroupForPrinting(group):
"use stripFrontZeros(group) on group"
return stripFrontZeros(group)
def main():
s = convertNToString(n)
s = regularizeFirstGroup(s)
a = ""
# work on each group in turn, from first group to end group of s
for index in range(0,len(s),3):
illionNum = ComputeIllionNum(s[index:])
illionName = illionNumToName(illionNum)
group = extractGroup(s[index:])
group = prepareGroupForPrinting(group)
# don't print illionName if group is originally "000"
if group == "":
illionName = ""
continue
a = a + " " + group + " " + illionName + ","
# remove final " ," or ","
if a[-2:] == " ,":
a = a[:-2]
else:
a = a[:-1]
answer = a
return answer
if __name__=='__main__':
n = 12008787987
print main()
More information about the Tutor
mailing list