Python Forum
phone number, to letters conversion
Thread Rating:
  • 3 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
phone number, to letters conversion
#1
Hi,
This is a program I wrote this morning, to play around with nested loops,
and error handling routines.

It will convert any 7 digit phone number into all the 2000 plus letter
combinations that make up the letters on the modern phone dial.

import os

import os
class klass:
    "docstring"
    def_int-self:
       self.attribute="var"
       if len (self.attribute)<2:
           pass


#python program code starts here!

print("")
tuple0=("","","")
tuple1=("","","")
tuple2=("a","b","c")
tuple3=("d","e","f")
tuple4=("g","h","i")
tuple5=("j","k","l")
tuple6=("m","n","o")
tuple7=("p","q","r","s")
tuple8=("t","u","v")
tuple9=("w","x","y","z")
print("");print("");print("This program will return all the letter conbinations")
print(                          "that are available on the modern phone")
print("You just type in a seven digit number and let the program display")
print("all the letter conbinations that make up that number  Enjoy");print("")

flg=0
quit=0
while quit==0:
    list_numbers=[]
    list_tuple=[] 
    cont=0
    while cont==0:
        print("")
        print ("            Enter (0) to exit out of the program");print ("")
        try:
            phone_number=input("Enter a 7 digit phone number (NO spaces)>>   ")
            dummy=int(phone_number) 
            if (phone_number)=="0":
                flg=1
                break
            elif len(phone_number)< 7:
                print("")
                print ("Do not enter less than (7) digits")
            elif len(phone_number)>7:
                print("")
                print ("Do not enter more than (7) digits")
            else:
                cont=1
             
        except:
            print("")
            print ("Enter numbers only no letters or special characters") 
    for number in (phone_number):
        print (number)
        list_numbers.append(number)
    if flg==1:
        break
    print("")
    print (list_numbers)
    for number in (list_numbers):
        if number =="0":
            list_tuple.append(tuple0)
        if number=="1":
            list_tuple.append(tuple1)
        if number=="2":
            list_tuple.append(tuple2)
        if number=="3":
            list_tuple.append(tuple3)
        if number=="4":
            list_tuple.append(tuple4)
        if number=="5":
            list_tuple.append(tuple5)
        if number=="6":
            list_tuple.append(tuple6)
        if number=="7":
            list_tuple.append(tuple7)
        if number=="8":
            list_tuple.append(tuple8)
        if number=="9":
            list_tuple.append(tuple9)
    print("")
    print(list_tuple)
    print("")

    print("")
    a=(list_tuple[0])
    print (a)
    b=(list_tuple[1])
    print(b)
    c=(list_tuple[2])
    print (c)
    d=(list_tuple[3])
    print(d)
    e=(list_tuple[4])
    print(e)
    f=(list_tuple[5])
    print (f)
    g=(list_tuple[6])
    print (g)
    print("")
    n=1
    for A in (a):
        for B in (b):
            for C in (c):
                for D in (d):
                    for E in (e):
                        for F in (f):
                            for G in (g):
                                print ("(",(n),")  ",(A)+(B)+(C)+(D)+(E)+(F)+(G))
                                print("")
                                n=n+1

    
Reply
#2
Tip: when variable names contain a varying index such as in
tuple0=("","","")
tuple1=("","","")
tuple2=("a","b","c")
tuple3=("d","e","f")
tuple4=("g","h","i")
tuple5=("j","k","l")
tuple6=("m","n","o")
tuple7=("p","q","r","s")
tuple8=("t","u","v")
tuple9=("w","x","y","z")
use a single list variable instead
atuple = [
    ("","",""),
    ("","",""),
    ("a","b","c"),
    ("d","e","f"),
    ("g","h","i"),
    ("j","k","l"),
    ("m","n","o"),
    ("p","q","r","s"),
    ("t","u","v"),
    ("w","x","y","z")]
Then instead of tuple7, use atuple[7]. It allows loops or simplifications such as
list_tuple.append(atuple[int(number)])
Similarly, instead of the variables a, b, c, d, e, f, g, you could use a list to contain them all. Finally, have a look at itertools.product()!
Reply
#3
Hi, thank you for taking the time to look over my code and offering good sugestions;
I'm just new at python, so I am not sure I'm understanding or following advice given
to me to the tee, however with your reply, I think I understand it to be to work
from one list or tuple at the begining when setting up the matching of numbers to letters.

So I rewrote the script, to eleiminate all the redundant tuples, in the begining of the
script, and removed the variable reassignments in the mid section, so as to output
working with index positions from a list directly.

Comparing this script with the one I originally wrote should clarify
what I'm trying to convey.

Thanks for your helpful reply.



import os

import os
class klass:
    "docstring"
    def_int-self:
       self.attribute="var"
       if len (self.attribute)<2:
           pass



print("")
list_tuple=[("","",""),("","",""),("a","b","c"),("d","e","f"),
           ("g","h","i"),("j","k","l"),("m","n","o"),
           ("p","q","r","s"),("t","u","v"),("w","x","y","z")]


print("");print("");print("This program will return all the letter conbinations")
print(                          "that are available on the modern phone")
print("You just type in a seven digit number and let the program display")
print("all the letter conbinations that make up that number  Enjoy");print("")

flg=0
quit=0
while quit==0:
    list_numbers=[]
    list_cnvrt=[] 
    cont=0
    while cont==0:
        print("")
        print ("            Enter (0) to exit out of the program");print ("")
        try:
            phone_number=input("Enter a 7 digit phone number (NO spaces)>>   ")
            dummy=int(phone_number) 
            if (phone_number)=="0":
                flg=1
                break
            elif len(phone_number)< 7:
                print("")
                print ("Do not enter less than (7) digits")
            elif len(phone_number)>7:
                print("")
                print ("Do not enter more than (7) digits")
            else:
                cont=1
             
        except:
            print("")
            print ("Enter numbers only no letters or special characters") 
    for number in (phone_number):
        list_numbers.append(number)
    if flg==1:
        break
    print("")
    print (list_numbers)
    for number in (list_numbers):
        if number =="0":
            list_cnvrt.append(list_tuple[0])
        if number=="1":
            list_cnvrt.append(list_tuple[1])
        if number=="2":
            list_cnvrt.append(list_tuple[2])
        if number=="3":
            list_cnvrt.append(list_tuple[3])
        if number=="4":
            list_cnvrt.append(list_tuple[4])
        if number=="5":
            list_cnvrt.append(list_tuple[5])
        if number=="6":
            list_cnvrt.append(list_tuple[6])
        if number=="7":
            list_cnvrt.append(list_tuple[7])
        if number=="8":
            list_cnvrt.append(list_tuple[8])
        if number=="9":
            list_cnvrt.append(list_tuple[9])
    print("")
    print (list_cnvrt)
    cnt=1
    for A in (list_cnvrt[0]):
        for B in (list_cnvrt[1]):
            for C in (list_cnvrt[2]):
                for D in (list_cnvrt[3]):       
                    for E in (list_cnvrt[4]):      
                        for F in (list_cnvrt[5]):      
                            for G in (list_cnvrt[6]):
                                 print ("(",(cnt),")  ",(A)+(B)+(C)+(D)+(E)+(F)+(G))
                                 print("")
                                 cnt=cnt+1
 
Reply
#4
The whole block of code from line 57 to 77 can now be replaced with
list_cnvrt.extend(list_tuple[int(number)] for number in list_numbers)
and if you write from itertools import product at the top, the huge block of for statements near the end can be replaced with
for A, B, C, D, E, F, G in product(*list_cnvrt):
    print ("(",(cnt),")  ",(A)+(B)+(C)+(D)+(E)+(F)+(G))
    print("")
    cnt=cnt+1
You could even write
for cnt, p in enumerate(product(*list_cnvrt), 1):
    print("({}) {}".format(cnt, sum(p)))
Reply
#5
(Dec-03-2018, 12:49 AM)hobbyprogrammer Wrote:
class klass:
    "docstring"
    def_int-self:
       self.attribute="var"
       if len (self.attribute)<2:
           pass
I'm not sure how you're running your program, but that's not valid, and you should be getting errors.

Let's talk style! Instead of...
print("");print("");print("This program will return all the letter conbinations")
print(                          "that are available on the modern phone")
print("You just type in a seven digit number and let the program display")
print("all the letter conbinations that make up that number  Enjoy");print("")
...try this!
docs = """This program will return all the letter conbinations
that are available on the modern phone
You just type in a seven digit number and let the program display
all the letter conbinations that make up that number  Enjoy"""

print(docs)
Reply
#6
Thank you, guys for your helpful suggestions, I'm not proficient enough in programming
yet, to be able to read codes that is brought to my attention, from others, so please
excuse any code structure that I may leave out, as I'm trying to learn at my own
pace and methods of script writing.

However The suggestion about minimizing the codeing between 57 and 77, has spurred me on
to experimenting with ways to accomplish this. Thankyou for the scriptings you shared
on how to do this, but as I said, I need to work at this at my own level of understanding
so I took your suggestion about reducing that block of code, and this is what I
was able to come up with. This is a learning process for me so please understand, it is
not the substitute codes you showed, but I neded to come up with something on my own,
as all of this is learning exercises for me in python programming.

However I will look at learning how to use the (product function) as you shared,
but for right now I'll just share what I understand at this point in the journey.



import os
class klass:
    "docstring"
    def_int-self:
       self.attribute="var"
       if len (self.attribute)<2:
           pass


print("")
list_tuple=[("","",""),("","",""),("a","b","c"),("d","e","f"),
           ("g","h","i"),("j","k","l"),("m","n","o"),
           ("p","q","r","s"),("t","u","v"),("w","x","y","z")]

about="""     This program will return all the letter conbinations
          that are available on the modern phone
 You just type in a seven digit number and let the program display
    all the letter conbinations that make up that number    Enjoy"""
print(about)

flg=0
quit=0
while quit==0:
    list_numbers=[]
    list_cnvrt=[] 
    cont=0
    while cont==0:
        print("")
        print ("            Enter (0) to exit out of the program");print ("")
        try:
            phone_number=input("Enter a 7 digit phone number (NO spaces)>>   ")
            dummy=int(phone_number) 
            if (phone_number)=="0":
                flg=1
                break
            elif len(phone_number)< 7:
                 print("")
                 print ("Do not enter less than (7) digits")
            elif len(phone_number)>7:
                 print("")
                 print ("Do not enter more than (7) digits")
            elif (" ") in (phone_number):
                print("")
                print ("Do not enter any space characters")
            else:
                 cont=1
        except:
            print("")
            print ("Enter numbers only no letters or special characters")
    for number in (phone_number):
        number=int(number)
        print (number)
        list_numbers.append(number)
    if flg==1:
        break
    print("")
    print (list_numbers)     
    for number in (list_numbers):#this is my understanding of how to minimize the (if) statements. routine starts here
        for compare in range(10):
            if (compare)==(number):
                 list_cnvrt.append(list_tuple[compare])#routine ends here
        
    print("")
    print (list_cnvrt)
    cnt=1
    for A in (list_cnvrt[0]):
        for B in (list_cnvrt[1]):
            for C in (list_cnvrt[2]):
                for D in (list_cnvrt[3]):       
                    for E in (list_cnvrt[4]):      
                        for F in (list_cnvrt[5]):      
                            for G in (list_cnvrt[6]):
                                 print ("(",(cnt),")  ",(A)+(B)+(C)+(D)+(E)+(F)+(G))
                                 print("")
                                 cnt=cnt+1
                                

    

















        

                                
Reply
#7
At line 59, you're trying every digit until you find one that is equal to 'number', then you use it. Why not use 'number' directly?
    for number in (list_numbers):
        list_cnvrt.append(list_tuple[number])
Reply
#8
Yeh, That makes a lot of sense, Thank You,
It's funny how you have a train of thought on how to do a task,
you accomplish it, and an easier solution is right there in front of you
but you don't see it until someone points it out to you.

Thanks, believe me you guys reply's are very helpful in learning programming
when I write programs now I take what I've learned from others replies,
and try to incorporate it, to the best of my understanding.
Reply
#9
I have a couple of questions about this code.
First, this block:
class klass:
    "docstring"
    def_int-self:
       self.attribute="var"
       if len (self.attribute)<2:
           pass
raises a SyntaxError on my machine for "invalid syntax" at 'def_int-self:'

Next, I don't see where the class 'klass' is used anywhere in the script at all, so I'm confused as to why it is there to begin with.

If I comment out that block of code, the program runs, but not as stated. Here is the output I get when I run it:
Output:
% phonecon.py This program will return all the letter conbinations that are available on the modern phone You just type in a seven digit number and let the program display all the letter conbinations that make up that number Enjoy Enter (0) to exit out of the program Enter a 7 digit phone number (NO spaces)>> 4487125 Enter numbers only no letters or special characters Enter (0) to exit out of the program Enter a 7 digit phone number (NO spaces)>> 0 Enter numbers only no letters or special characters Enter (0) to exit out of the program Enter a 7 digit phone number (NO spaces)>>
and that is it. It does not show me any letter combinations and 0 does not exit the program. I have to do a 'ps -e |grep python' to get a process id on the script then 'kill <pid>', because 'Ctrl-c' doesn't work to terminate it either.

I haven't yet looked too closely at the rest of the code. When I do, I will get back to you about anything I notice that might help.
Reply
#10
A couple of apologies are in order, first to the sysadmins, I neglected to add the appropriate tags in my first post, I will remember in the future.

Second, to hobbyprogrammer, I was reviewing my copy of your script and it seems I missed a keypress in the shebang at the head and it was trying to interpret python 3 code with the python 2 interpreter. I fixed that, and with the class definition commented out, the program does run fine. I might suggest a small addition though. It lists all the combinations quite quickly and the list is quite long, so you can't scroll all the way back to see the beginning of the list. Here is a function I have found quite useful:
def any_key():
    """A function to pause execution until a key, almost any key
       is pressed.  It does not catch <CTRL>, <ALT>, <SHIFT>, 
       <NUM LOCK> or <CAPS LOCK>. It does not depend on any system calls.
    """
    import tty, sys, termios

    orig_settings = termios.tcgetattr(sys.stdin) #Store current state of input
                                                 #stream
    tty.setraw(sys.stdin) #Set input stream to raw mode
    print("          Any key to continue...")
    sys.stdin.read(1)[0]
    termios.tcsetattr(sys.stdin,termios.TCSADRAIN, orig_settings) #Restore input
                                                                  #stream to original state
    print()     # Final print() to bring the cursor back to the left side of the
                # screen.  Without this, the cursor is left somewhere towards
                # center screen until the <ENTER> key is pressed.
You can define that function at the head of your script, then call it like so during the printing of the final output:
     for A in (list_cnvrt[0]):
        for B in (list_cnvrt[1]):
            for C in (list_cnvrt[2]):
                for D in (list_cnvrt[3]):       
                    for E in (list_cnvrt[4]):      
                        for F in (list_cnvrt[5]):      
                            for G in (list_cnvrt[6]):
                                 print ("(",(cnt),")  ",(A)+(B)+(C)+(D)+(E)+(F)+(G))
                                 print("")
                                 if(cnt % 10 == 0):
                                     any_key()
                                 cnt=cnt+1
I myself keep it with other functions I have found useful in my own module, MyPy.py
and import as needed.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020