Problem with a dictionary program....

L

Ling Lee

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....
 
R

Russell Blau

Ling Lee said:
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().
 
L

Ling Lee

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 said:
Ling Lee said:
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().
 
J

Jeffrey Froman

Ling said:
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
 
L

Ling Lee

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:"six",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 said:
Ling said:
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
 
D

Dan Perl

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 said:
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:"six",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 said:
Ling said:
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
 
A

Alex Martelli

Ling Lee said:

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 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
 
A

Alex Martelli

Ling Lee said:
List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",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
 
D

Dan Perl

Alex Martelli said:
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","seven","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
 
R

Russell Blau

Ling Lee said:
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.
14

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

Larry Bates

Ling said:
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 =

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()​
 
J

Jeff Shannon

Dan said:
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
 
D

Dan Perl

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 said:
Dan said:
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
 
L

Ling Lee

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 said:
Ling said:
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 =

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()​
 
N

Neuruss

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+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
 
D

Dennis Lee Bieber

Ling Lee said:
List =
{1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",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


--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top