473,400 Members | 2,163 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,400 software developers and data experts.

Problem with a dictionary program....

Hello.

I'm trying to write a small program that lets you put in a number as an
integer and then it tells you the textuel representation of the number.

Like if your input is 42, it will say four two.

I found out that I have to make a dictionary like this: List = { 1:"one",
2:"two" and so on )

and I have to use the raw_input method to get the number:

indput : raw_input(" Tell me the number you want to transform to textuel
representaion")

The I have to transform the input to a string
indput = str(indput)

so that I can count how many decimals the number has, like 23 has 2 decimals
and 3000 has 4 decimals.

After I have gotten the lenght of the string, I will write a loop, that goes
through the dictionary as many times as the lengt of the string, and the
gives me the corresponding numbers, the numner 21 would go 2 times through
the loop and give me the output two one

Will one of you be so kind and tell me how I count the lengt of the indput
number i was thinking on something like input.count[:] but that dosnt
work...

and how I make the loop.

Im trying to understand dictionaries but have gotten a bit stuck...

Thanks for all replies....

Jul 18 '05 #1
16 2034
"Ling Lee" <ja*****@mail.trillegaarden.dk> wrote in message
news:41***********************@nntp05.dk.telia.net ...

and I have to use the raw_input method to get the number:

indput : raw_input(" Tell me the number you want to transform to textuel
representaion")

The I have to transform the input to a string
indput = str(indput)
Actually, the value returned by raw_input() *is* a string, but you might
want to check to see whether the user has actually typed in an integer as
opposed to typing, say, "Go away you stupid computer."

try:
indput = str(int(indput))
except ValueError:
print "No, you need to give me an integer."
Will one of you be so kind and tell me how I count the lengt of the indput
number i was thinking on something like input.count[:] but that dosnt
work...


You could consider using the built-in function len().
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #2
Thanks Russell Blau, its smart to tjeck for it is really is an integer that
the user types in :)

I have read the tutorial, but still its a bit hard for me to see how I make
the loop and how I count the lengt of the number. When I use the len(input)
I get the reply: Error len() of unsized object. Think that is why len()
only works on dictionaries and lists, not strings.

indput = raw_input(" Tell me the number you want to transform to textuel
representaion")
try:
indput = str(int(indput))
except ValueError:
print "No, you need to give me an integer."

This works fine.

But how do i then count the length of the number and make the loop: My goal
was to:

" I'm trying to write a small program that lets you put in a number as an
integer and then it tells you the textuel representation of the number.

Like if your input is 42, it will say four two.

I found out that I have to make a dictionary like this: List = { 1:"one",
2:"two" and so on )

After I have gotten the lenght of the string, I will write a loop, that goes
through the dictionary as many times as the lengt of the string, and the
gives me the corresponding numbers, the numner 21 would go 2 times through
the loop and give me the output two one.

Sorry to ask this easy questions, but think that things really would make
sense for me after this little
program is done. I have a lot easier to grasp the magic of pragramming
through looking at programs than
to read tutorials about it....

Thanks

"Russell Blau" <ru******@hotmail.com> wrote in message
news:2r*************@uni-berlin.de...
"Ling Lee" <ja*****@mail.trillegaarden.dk> wrote in message
news:41***********************@nntp05.dk.telia.net ...

and I have to use the raw_input method to get the number:

indput : raw_input(" Tell me the number you want to transform to textuel
representaion")

The I have to transform the input to a string
indput = str(indput)


Actually, the value returned by raw_input() *is* a string, but you might
want to check to see whether the user has actually typed in an integer as
opposed to typing, say, "Go away you stupid computer."

try:
indput = str(int(indput))
except ValueError:
print "No, you need to give me an integer."
Will one of you be so kind and tell me how I count the lengt of the
indput
number i was thinking on something like input.count[:] but that dosnt
work...


You could consider using the built-in function len().
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.

Jul 18 '05 #3
Ling Lee wrote:
After I have gotten the lenght of the string, I will write a loop, that
goes through the dictionary as many times as the lengt of the string, and
the gives me the corresponding numbers, the numner 21 would go 2 times
through the loop and give me the output two one.


There is no need to count the length. You can iterate over each character in
a Python string (or other object) without first calculating the size of the
loop, like so:

output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

As Russel pointed out, you'll have to iterate over indput as as a string --
not convert it to an integer first, because you can't iterate over an
integer's digits, but you can iterate over a string's characters.

Jeffrey
Jul 18 '05 #4
So this code should work:

indput = raw_input(" Tell me the number you want to transform to textuel
representaion")
try:
indput = str(int(indput))
except ValueError:
print "No, you need to give me an integer."

List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"si x",7:"seven",8:"eight",9:"nine"}
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

I read it like this first output is an empty list, then for each character
in the input it will be run through the "List" and when it find the number
it will apend it to the output, and in the last print line it will join the
output ( if there has been more than one number) and print it-

But if I run the program and type in the number 34 I get the error:

Traceback (most recent call last):
File "C:/Python23/taltilnumre.py", line 10, in -toplevel-
output.append(List[character])
KeyError: '3'

How can that be, it looks right to me ...

Thanks
"Jeffrey Froman" <je*****@fro.man> wrote in message
news:10*************@corp.supernews.com...
Ling Lee wrote:
After I have gotten the lenght of the string, I will write a loop, that
goes through the dictionary as many times as the lengt of the string, and
the gives me the corresponding numbers, the numner 21 would go 2 times
through the loop and give me the output two one.


There is no need to count the length. You can iterate over each character
in
a Python string (or other object) without first calculating the size of
the
loop, like so:

output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

As Russel pointed out, you'll have to iterate over indput as as a
string --
not convert it to an integer first, because you can't iterate over an
integer's digits, but you can iterate over a string's characters.

Jeffrey

Jul 18 '05 #5
The keys in your dictionary are numbers and the variable 'character' in your
program is a character. That means one is equivalent to a=1, the other one
is equivalent to a="1". Either make the keys in the dictionary strings
(i.e., {"1":"one", ...) or convert 'character' to an integer with int( ).

"Ling Lee" <ja*****@mail.trillegaarden.dk> wrote in message
news:41***********************@nntp05.dk.telia.net ...
So this code should work:

indput = raw_input(" Tell me the number you want to transform to textuel
representaion")
try:
indput = str(int(indput))
except ValueError:
print "No, you need to give me an integer."

List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"si x",7:"seven",8:"eight",9:"nine"}
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

I read it like this first output is an empty list, then for each character
in the input it will be run through the "List" and when it find the number
it will apend it to the output, and in the last print line it will join
the output ( if there has been more than one number) and print it-

But if I run the program and type in the number 34 I get the error:

Traceback (most recent call last):
File "C:/Python23/taltilnumre.py", line 10, in -toplevel-
output.append(List[character])
KeyError: '3'

How can that be, it looks right to me ...

Thanks
"Jeffrey Froman" <je*****@fro.man> wrote in message
news:10*************@corp.supernews.com...
Ling Lee wrote:
After I have gotten the lenght of the string, I will write a loop, that
goes through the dictionary as many times as the lengt of the string,
and
the gives me the corresponding numbers, the numner 21 would go 2 times
through the loop and give me the output two one.


There is no need to count the length. You can iterate over each character
in
a Python string (or other object) without first calculating the size of
the
loop, like so:

output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

As Russel pointed out, you'll have to iterate over indput as as a
string --
not convert it to an integer first, because you can't iterate over an
integer's digits, but you can iterate over a string's characters.

Jeffrey


Jul 18 '05 #6
Ling Lee <ja*****@mail.trillegaarden.dk> wrote:
Hello.
Hi! I suspect (from your name and address) that English is not your
mother tongue (it ain't mine, either), so I hope you'll appreciate some
suggestions in the following about natural language as well as Python.
I'm trying to write a small program that lets you put in a number as an
integer and then it tells you the textuel representation of the number.
"Textual".
Like if your input is 42, it will say four two.
Ah, "Digit by digit". The "textual representation of 42" would be
"fortytwo" -- a harder problem than outputting "four two".
I found out that I have to make a dictionary like this: List = { 1:"one",
2:"two" and so on )
Yes, such a dict is one possibility (no "have to", really, since there
ARE quite practicable alternatives), but [a] don't name it List, that's
WAY confusing, and [b] you may consider using as keys the digit strings
rather than the corresponding numbers, e.g '1' instead of 1 and so on,
it might simplify your coding.
Still, let's assume that this thing IS what you have, one way or
another.

and I have to use the raw_input method to get the number:
You don't HAVE to (you could obtain it in other ways) but, sure, it's
one possibility. (Maybe you overuse "have to" a bit...?)

indput : raw_input(" Tell me the number you want to transform to textuel
representaion")
No doubt you mean to use an equals-sign here, not a colon, since you are
assigning the result of raw_input to your variable 'indput' (VERY
confusing name, again).
The I have to transform the input to a string
indput = str(indput)
Not at all, this is a "no-operation", since the result of raw_input IS a
string already.
so that I can count how many decimals the number has, like 23 has 2 decimals
and 3000 has 4 decimals.
"digits". When you say a number has "2 decimals" this would normally be
interpreted as meaning "two digits after the decimal point", something
like "27.12". But I don't see why you would care, anyway. Rather, try
checking indput.isdigit() to verify all of the chararacters are digits.
After I have gotten the lenght of the string, I will write a loop, that goes
through the dictionary as many times as the lengt of the string, and the
gives me the corresponding numbers, the numner 21 would go 2 times through
the loop and give me the output two one
Nah, loop on the string directly, that will give you one character at a
time in order. No need to worry about lengths, number of times through,
etc. Just "for c in indput: ...", that's all.

Will one of you be so kind and tell me how I count the lengt of the indput
number i was thinking on something like input.count[:] but that dosnt
work...
That would be len(indput), but you don't need it.

and how I make the loop.
You do it with a 'for' statement as above, no worry about the length.

Im trying to understand dictionaries but have gotten a bit stuck...

Thanks for all replies....


The Tutor list might be very helpful to you. Happy studying!
Alex
Jul 18 '05 #7
Ling Lee <ja*****@mail.trillegaarden.dk> wrote:
...
List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"si x",7:"seven",8:"eight",9
:"nine"}
You're missing 0, so an input such as 103 would give an error even if
all the rest of your code was correct.
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)


This will print N times when you have N digits... outdent the print
statement so it's executed after the 'for' and not inside it.
Alex
Jul 18 '05 #8

"Alex Martelli" <al*****@yahoo.com> wrote in message
news:1gku3wn.1o7mvyb1gtif84N%al*****@yahoo.com...
Ling Lee <ja*****@mail.trillegaarden.dk> wrote:
...
List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"si x",7:"seven",8:"eight",9
:"nine"}


You're missing 0, so an input such as 103 would give an error even if
all the rest of your code was correct.


Here's another idea: use a (real) list instead of a dictionary:
List =
["zero","one","two","three","four","five","six","se ven","eight","nine"]

Then you have to convert the 'character' variable with int(character) before
indexing in List. Now, this would not help you in learning dictionaries,
but it must be a good lesson for something. ;-)
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)


This will print N times when you have N digits... outdent the print
statement so it's executed after the 'for' and not inside it.


That print statement is actually wrong in many ways. It was probably meant
to be something like
print ','.join(List[int(character)]) # List[int(character)], not
output
but even that would start with ',' and it would be on multiple lines
(probably not your intention). Alex is right. You're better off with an
unindented
print output
although that would have square brackets around the output list. Or try an
indented
print List[int(character)],
which would just not have the commas between the numbers
Jul 18 '05 #9
"Ling Lee" <ja*****@mail.trillegaarden.dk> wrote in message
news:41***********************@nntp05.dk.telia.net ...
I have read the tutorial, but still its a bit hard for me to see how I make the loop and how I count the lengt of the number. When I use the len(input) I get the reply: Error len() of unsized object. Think that is why len()
only works on dictionaries and lists, not strings.

len("I am a string.")

14

Maybe it was a spelling error -- did you type len(input) instead of
len(indput) perhaps?

--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #10
Ling Lee wrote:
Hello.

I'm trying to write a small program that lets you put in a number as an
integer and then it tells you the textuel representation of the number.

Like if your input is 42, it will say four two.

I found out that I have to make a dictionary like this: List = { 1:"one",
2:"two" and so on )

and I have to use the raw_input method to get the number:

indput : raw_input(" Tell me the number you want to transform to textuel
representaion")

The I have to transform the input to a string
indput = str(indput)

so that I can count how many decimals the number has, like 23 has 2 decimals
and 3000 has 4 decimals.

After I have gotten the lenght of the string, I will write a loop, that goes
through the dictionary as many times as the lengt of the string, and the
gives me the corresponding numbers, the numner 21 would go 2 times through
the loop and give me the output two one

Will one of you be so kind and tell me how I count the lengt of the indput
number i was thinking on something like input.count[:] but that dosnt
work...

and how I make the loop.

Im trying to understand dictionaries but have gotten a bit stuck...

Thanks for all replies....

Here's an example of what you want:

""" Just run it, you'll see what it does.

This code is released into the public domain absolutely free by http://journyx.com
as long as you keep this comment on the document and all derivatives of it.

"""

def getfractionwords(num):
frac = num-int(num)
numstr = str(int(frac*100+.5))
if len(numstr) == 1:
numstr = '0'+numstr
fracstr = ' and ' + numstr + '/100'
return fracstr

def convertDigit(digit):
digits = ('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven',
'Eight', 'Nine')
return digits[int(digit+.5)]

def breakintochunks(num):
(left,right) = breakintwo(num)
rv = [right]
while left > 999:
(left,right) = breakintwo(left)
rv.append(right)
rv.append(left)
rv.reverse()
return rv

def breakintwo(num):
leftpart = int(num/1000.0)+0.0
rightpart = 1000.0*(num/1000.0 - leftpart)
return (int(leftpart+.5),int(rightpart+.5))

def enties(num):
tens = ('','','Twenty' ,'Thirty', 'Forty', 'Fifty', 'Sixty',
'Seventy', 'Eighty', 'Ninety')
indx = int(num/10.0)
return tens[indx]

def convert2digit(num):
teens = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen',
'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen')
if num < 10:
return convertDigit(num)
if num <20:
return teens[num-10]
if num > 19:
tens = enties(num)
ones = convertDigit(10*(num/10.0-int(num/10.0)))
if ones:
rv= tens+'-'+ones
else:
rv=tens
return rv

def convert3digit(num):
threenum = str(num)
ln = len(threenum)
if ln==3 :
a= convertDigit(int(threenum[0]))
b= ' Hundred '
c= convert2digit(int(threenum[1:]))
return a+b+c
if ln<3 :
return convert2digit(int(threenum))
raise 'bad num',num

def num2words(num):
thousandchunks = breakintochunks(int(num))
rv = ' '
if num >= 1000000:
rv=rv+ convert3digit(thousandchunks[-3])+ ' Million '
if num >= 1000:
c3d= convert3digit(thousandchunks[-2])
if c3d:
rv=rv+ c3d+ ' Thousand '
rv = rv + convert3digit(thousandchunks[-1])+ getfractionwords(num)
return squishWhiteSpace(rv)

def squishWhiteSpace(strng):
""" Turn 2 spaces into one, and get rid of leading and trailing
spaces. """
import string,re
return string.strip(re.sub('[ \t\n]+', ' ', strng))

def main():
for i in range(1,111,7):
print i,num2words(i)

for i in (494.15, 414.90, 499.35, 400.98, 101.65, 110.94, \
139.85, 12349133.40, 2309033.75, 390313.41, 99390313.15, \
14908.05, 10008.49, 100008.00, 1000008.00, 100000008.00, \
14900.05, 10000.49, 100000.00, 1000000.00, 100000000.00, 8.49):
print i,num2words(i)

import whrandom
for i in range(33):
num = whrandom.randint(1,999999999) + whrandom.randint(1,99)/100.0
print num,num2words(num)

if __name__ == '__main__':
main()
Jul 18 '05 #11
Dan Perl wrote:
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

That print statement is actually wrong in many ways. It was probably meant
to be something like
print ','.join(List[int(character)]) # List[int(character)], not
output
but even that would start with ',' and it would be on multiple lines
(probably not your intention).


No, it wouldn't start with ',' -- you're not parsing that line the same
way that Python does. ;)

aString.join(aList) will combine a list of strings into a single string,
using the referenced string as "glue" to stick the pieces together.
Thus, when the referenced string is ', ', you'll get "item0, item1, item2".

Python will evaluate the call to ', '.join() *before* it prints
anything. The print statement is given the resulting (single) string as
its argument. Indeed, that line could be split into several lines for
clarity:

separator = ', '
outputstring = separator.join(output)
print outputstring

The point here is that the for loop builds a list of strings (called
'output'). *After* the for loop finishes, then str.join() combines that
list into a single string, which is printed. However, the O.P. has an
indentation problem in his code -- he's put the print statement inside
his for loop, which means that every intermediate stage of the
partially-built output will get printed as well. All that needs done to
fix it is to outdent it one level (as Alex suggested).

Your suggestion ("print ','.join(List[int(character)])"), by the way,
will give results that are far different from what you expect. ;)
List = ['zero', 'one', 'two', 'three']
print ",".join(List[int('3')]) t,h,r,e,e


You're correctly looking up the word to use for a given digit, but then
you're passing that single string (rather than a list) to join(), which
works on any sequence (not just lists). Well, strings are sequences too
(a sequence of characters), so join() creates a string with each element
(character) of the sequence separated by the specified string (",").

Jeff Shannon
Technician/Programmer
Credit International


Jul 18 '05 #12
Sorry, my bad. I didn't pay attention and I mistook the join( ) for an
append( ) while just copying and pasting. I've never used join( ) myself so
it didn't click in my mind.

Dan

"Jeff Shannon" <je**@ccvcorp.com> wrote in message
news:10************@corp.supernews.com...
Dan Perl wrote:
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)

That print statement is actually wrong in many ways. It was probably
meant to be something like
print ','.join(List[int(character)]) # List[int(character)], not
output
but even that would start with ',' and it would be on multiple lines
(probably not your intention).


No, it wouldn't start with ',' -- you're not parsing that line the same
way that Python does. ;)

aString.join(aList) will combine a list of strings into a single string,
using the referenced string as "glue" to stick the pieces together. Thus,
when the referenced string is ', ', you'll get "item0, item1, item2".

Python will evaluate the call to ', '.join() *before* it prints anything.
The print statement is given the resulting (single) string as its
argument. Indeed, that line could be split into several lines for
clarity:

separator = ', '
outputstring = separator.join(output)
print outputstring

The point here is that the for loop builds a list of strings (called
'output'). *After* the for loop finishes, then str.join() combines that
list into a single string, which is printed. However, the O.P. has an
indentation problem in his code -- he's put the print statement inside his
for loop, which means that every intermediate stage of the partially-built
output will get printed as well. All that needs done to fix it is to
outdent it one level (as Alex suggested).

Your suggestion ("print ','.join(List[int(character)])"), by the way, will
give results that are far different from what you expect. ;)
List = ['zero', 'one', 'two', 'three']
print ",".join(List[int('3')]) t,h,r,e,e


You're correctly looking up the word to use for a given digit, but then
you're passing that single string (rather than a list) to join(), which
works on any sequence (not just lists). Well, strings are sequences too
(a sequence of characters), so join() creates a string with each element
(character) of the sequence separated by the specified string (",").

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #13
And my bad, again. Strings do not have an append anyway.

"Dan Perl" <da*****@rogers.com> wrote in message
news:Iu********************@rogers.com...
Sorry, my bad. I didn't pay attention and I mistook the join( ) for an
append( ) while just copying and pasting. I've never used join( ) myself
so it didn't click in my mind.

Dan

Jul 18 '05 #14
Thanks for all your help, I really appreciate it, its very interesting to
start programming but at times a bit confusing :D
I read all your input, and clap my hands for this friendly newsgroup :D

Stay safe....
"Larry Bates" <lb****@syscononline.com> wrote in message
news:ZJ********************@comcast.com...
Ling Lee wrote:
Hello.

I'm trying to write a small program that lets you put in a number as an
integer and then it tells you the textuel representation of the number.

Like if your input is 42, it will say four two.

I found out that I have to make a dictionary like this: List = { 1:"one",
2:"two" and so on )

and I have to use the raw_input method to get the number:

indput : raw_input(" Tell me the number you want to transform to textuel
representaion")

The I have to transform the input to a string
indput = str(indput)

so that I can count how many decimals the number has, like 23 has 2
decimals and 3000 has 4 decimals.

After I have gotten the lenght of the string, I will write a loop, that
goes through the dictionary as many times as the lengt of the string, and
the gives me the corresponding numbers, the numner 21 would go 2 times
through the loop and give me the output two one

Will one of you be so kind and tell me how I count the lengt of the
indput number i was thinking on something like input.count[:] but that
dosnt work...

and how I make the loop.

Im trying to understand dictionaries but have gotten a bit stuck...

Thanks for all replies....

Here's an example of what you want:

""" Just run it, you'll see what it does.

This code is released into the public domain absolutely free by
http://journyx.com
as long as you keep this comment on the document and all derivatives of
it.

"""

def getfractionwords(num):
frac = num-int(num)
numstr = str(int(frac*100+.5))
if len(numstr) == 1:
numstr = '0'+numstr
fracstr = ' and ' + numstr + '/100'
return fracstr

def convertDigit(digit):
digits = ('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine')
return digits[int(digit+.5)]

def breakintochunks(num):
(left,right) = breakintwo(num)
rv = [right]
while left > 999:
(left,right) = breakintwo(left)
rv.append(right)
rv.append(left)
rv.reverse()
return rv

def breakintwo(num):
leftpart = int(num/1000.0)+0.0
rightpart = 1000.0*(num/1000.0 - leftpart)
return (int(leftpart+.5),int(rightpart+.5))

def enties(num):
tens = ('','','Twenty' ,'Thirty', 'Forty', 'Fifty', 'Sixty',
'Seventy', 'Eighty', 'Ninety')
indx = int(num/10.0)
return tens[indx]

def convert2digit(num):
teens = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen',
'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen',
'Nineteen')
if num < 10:
return convertDigit(num)
if num <20:
return teens[num-10]
if num > 19:
tens = enties(num)
ones = convertDigit(10*(num/10.0-int(num/10.0)))
if ones:
rv= tens+'-'+ones
else:
rv=tens
return rv

def convert3digit(num):
threenum = str(num)
ln = len(threenum)
if ln==3 :
a= convertDigit(int(threenum[0]))
b= ' Hundred '
c= convert2digit(int(threenum[1:]))
return a+b+c
if ln<3 :
return convert2digit(int(threenum))
raise 'bad num',num

def num2words(num):
thousandchunks = breakintochunks(int(num))
rv = ' '
if num >= 1000000:
rv=rv+ convert3digit(thousandchunks[-3])+ ' Million '
if num >= 1000:
c3d= convert3digit(thousandchunks[-2])
if c3d:
rv=rv+ c3d+ ' Thousand '
rv = rv + convert3digit(thousandchunks[-1])+ getfractionwords(num)
return squishWhiteSpace(rv)

def squishWhiteSpace(strng):
""" Turn 2 spaces into one, and get rid of leading and trailing
spaces. """
import string,re
return string.strip(re.sub('[ \t\n]+', ' ', strng))

def main():
for i in range(1,111,7):
print i,num2words(i)

for i in (494.15, 414.90, 499.35, 400.98, 101.65, 110.94, \
139.85, 12349133.40, 2309033.75, 390313.41, 99390313.15,
\
14908.05, 10008.49, 100008.00, 1000008.00, 100000008.00,
\
14900.05, 10000.49, 100000.00, 1000000.00, 100000000.00,
8.49):
print i,num2words(i)

import whrandom
for i in range(33):
num = whrandom.randint(1,999999999) +
whrandom.randint(1,99)/100.0
print num,num2words(num)

if __name__ == '__main__':
main()

Jul 18 '05 #15
I¡ve got a program that already does what you want.
I don't remember the author, I got it somewhere on the net, but it
works great. It's in spanish but you'll get the idea...

def unidades(x):
if x == 0:
unidad = "cero"
if x == 1:
unidad = "un"
if x == 2:
unidad = "dos"
if x == 3:
unidad = "tres"
if x == 4:
unidad = "cuatro"
if x == 5:
unidad = "cinco"
if x == 6:
unidad = "seis"
if x == 7:
unidad = "siete"
if x == 8:
unidad = "ocho"
if x == 9:
unidad = "nueve"
return unidad

def teens(x):
if x == 0:
teenname = "diez"
if x == 1:
teenname = "once"
if x == 2:
teenname = "doce"
if x == 3:
teenname = "trece"
if x == 4:
teenname = "catorce"
if x == 5:
teenname = "quince"
return teenname
def tens(x):
if x == 1:
tensname = "diez"
if x == 2:
tensname = "veinte"
if x == 3:
tensname = "treinta"
if x == 4:
tensname = "cuarenta"
if x == 5:
tensname = "cincuenta"
if x == 6:
tensname = "sesenta"
if x == 7:
tensname = "setenta"
if x == 8:
tensname = "ochenta"
if x == 9:
tensname = "noventa"
return tensname

def tercia(num):
numero=str(num)
if len(numero) == 1:
numero='00'+numero
if len(numero) == 2:
numero='0'+numero
a=int(numero[0])
b=int(numero[1])
c=int(numero[2])
# print a, b, c
if a == 0:
if b == 0:
resultado=unidades(c)
return resultado
elif b == 1:
if c >= 0 and c <= 5:
resultado = teens(c)
return resultado
elif c >= 6 and c <= 9:
resultado = tens(b)+' y '+unidades(c)
return resultado
elif b == 2:
if c == 0:
resultado = 'veinte'
return resultado
elif c > 0 and c <= 9:
resultado ='veinti '+unidades(c)
return resultado
elif b >=3 and b <= 9:
if c == 0:
resultado = tens(b)
return resultado
if c >= 1 and c <= 9:
resultado = tens(b)+' y '+unidades(c)
return resultado
if a == 1:
if b == 0:
if c == 0:
resultado = 'cien'
return resultado
elif c > 0 and c <= 9:
resultado ='ciento '+unidades(c)
return resultado
elif b == 1:
if c >= 0 and c <= 5:
resultado = 'ciento '+teens(c)
return resultado
elif c >= 6 and c <= 9:
resultado = 'ciento '+tens(b)+' y '+unidades(c)
return resultado
elif b == 2:
if c == 0:
resultado = 'ciento veinte'
return resultado
elif c > 0 and c <= 9:
resultado ='ciento veinti '+unidades(c)
return resultado
elif b >= 3 and b <= 9:
if c == 0:
resultado = 'ciento '+tens(b)
return resultado
elif c > 0 and c <= 9:
resultado = 'ciento '+tens(b)+ ' y '+unidades(c
)
return resultado

elif a >= 2 and a <= 9:
if a == 5:
prefix='quinientos '
elif a == 7:
prefix='setecientos '
elif a == 9:
prefix='novecientos '
else:
prefix=unidades(a)+' cientos '
if b == 0:
if c == 0:
resultado = prefix
return resultado
elif c > 0 and c <= 9:
resultado = prefix+unidades(c)
return resultado
elif b == 1:
if c >= 0 and c <= 5:
resultado = prefix+teens(c)
return resultado
elif c >= 6 and c <= 9:
resultado = prefix+tens(b)+' y '+unidades(c)
return resultado
elif b == 2:
if c == 0:
resultado = prefix+' veinte'
return resultado
elif c > 0 and c <= 9:
resultado = prefix+' veinti '+unidades(c)
return resultado
elif b >= 3 and b <= 9:
if c == 0:
resultado = prefix+tens(b)
return resultado
elif c > 0 and c <= 9:
resultado = prefix+tens(b)+' y '+unidades(c)
return resultado
def main(num):
result=''
numero=str(num)
if len(numero) == 1:
numero='00000000'+numero
if len(numero) == 2:
numero='0000000'+numero
if len(numero) == 3:
numero='000000'+numero
if len(numero) == 4:
numero='00000'+numero
if len(numero) == 5:
numero='0000'+numero
if len(numero) == 6:
numero='000'+numero
if len(numero) == 7:
numero='00'+numero
if len(numero) == 8:
numero='0'+numero
posicion=1
for i in [0,3,6]:
var=numero[i]+numero[i+1]+numero[i+2]
if int(var) != 0:
res=tercia(var)
if i == 0:
result=res+" millones "
elif i == 3:
result=result+res+" mil "
elif i == 6:
result=result+res
return result
Jul 18 '05 #16
On Tue, 28 Sep 2004 17:47:29 +0200, al*****@yahoo.com (Alex Martelli)
declaimed the following in comp.lang.python:
Ling Lee <ja*****@mail.trillegaarden.dk> wrote:
...
List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"si x",7:"seven",8:"eight",9
:"nine"}
You're missing 0, so an input such as 103 would give an error even if
all the rest of your code was correct.
output = []
for character in indput:
output.append(List[character])
print ', '.join(output)


My silly version (hope this wasn't a homework assignment);
doesn't validate the overall format, but is extended for floats and
signs (as mentioned, no validation -- it will take 1-e3.5)

import string

words = { "0" : "zero",
"1" : "one",
"2" : "two",
"3" : "three",
"4" : "four",
"5" : "five",
"6" : "six",
"7" : "seven",
"8" : "eight",
"9" : "nine",
"," : "comma",
"." : "point",
"e" : "E",
"E" : "E",
"-" : "dash", # or hyphen, or minus
"+" : "plus" }
while 1:
inl = raw_input("Enter the number to be translated")
if not inl:
break
for c in inl: # no check for valid format is performed
if c in string.whitespace: # however, spaces/tabs are skipped
continue
print words.get(c, "invalid-character-'%s'" % c),
print
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: teoryn | last post by:
I've been spending today learning python and as an exercise I've ported a program I wrote in java that unscrambles a word. Before describing the problem, here's the code: *--beginning of file--*...
10
by: Alistair King | last post by:
Jon Clements wrote: sorry, this has been a little rushed XDS is defined before the function and is a float. the Fxas values are also and they are integers
3
by: Marc 'BlackJack' Rintsch | last post by:
On Thu, 28 Aug 2008 09:13:00 -0700, SUBHABRATA wrote: a1, a2, a2, …, a20? You must be kidding. Please stop numbering names and use *meaningful* names instead! Could you describe them...
0
by: bearophileHUGS | last post by:
Subhabrata, it's very difficult for me to understand what your short program has to do, or what you say. I think that formatting and code style are important. So I suggest you to give meaningful...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.