dimanche 9 décembre 2018

generating phone numbers using specific set of rules in python

I want to write a function which generates all possible numbers from a standard phone keypad (figure 1), using following set of rules:

  • phone numbers begin with the digit 2
  • phone number are 10 digit long
  • successive digits in each phone number are chosen as a knight moves in chess

In chess, a knight (sometimes called a horse) moves two steps vertically and one step horizontally OR two steps horizontally and one step vertically.

enter image description here

Only numerical digits can be used in phone numbers - i.e. the (#) and (*) keys are not allowed.

The function has to take length of the phone number and initial position as input and for the output gives the number of unique phone numbers.

I am a newbie and facing difficulty to build the logic. I tried to do it as follow which is definitely not a right approach.

def genNumbers(len, initpos):
numb = list('2xxxxxxxxx')

#index 1
numb[1] = 7 or 9

if numb[1] == 7:
    numb[2] == 2 or 6
elif numb[1] == 9:
    numb[2] == 2 or 4

#index 2
if numb[2]== 2:
    numb[3] == 7 or 9
elif numb[2]== 4:
    numb[3] == 3 or 9
elif numb[2]== 6:
    numb[3] == 1 or 7

#index 3
if numb[3]== 1:
    numb[4] == 6 or 8  
elif numb[3]== 3:
    numb[4] == 4 or 8 
elif numb[3]== 7:
    numb[4] == 2 or 6 
elif numb[3]== 9:
    numb[4] == 2 or 4 

#index 4
if numb[4] == 8:
    numb[5]== 1 or 3
elif numb[4] == 2:
    numb[5]== 7 or 9
elif numb[4] == 4:
    numb[5]== 3 or 9
elif numb[4] == 6:
    numb[5]== 1 or 7

#index 5
if numb[5] == 1:
    numb[6]== 6 or 8
elif numb[5] == 3:
    numb[6]== 4 or 8
elif numb[5] == 7:
    numb[6]== 2 or 6 
elif numb[5] == 9:
    numb[6]== 2 or 4

#index 6 
if numb[6] == 2:
    numb[7]== 7 or 9
elif numb[6] == 4:
    numb[7]== 3 or 9 
elif numb[6] == 6:
    numb[7]== 1 or 7
elif numb[6] == 8:
    numb[7]== 1 or 3

#index 7 
if numb[7] == 1:
    numb[8]== 6 or 8
elif numb[7] == 3:
    numb[8]== 4 or 8
elif numb[7] == 7:
    numb[8]== 2 or 6   
elif numb[7] == 9:
    numb[8]== 2 or 4

#index 8
if numb[8] == 6:
    numb[9]== 1 or 7
elif numb[8] == 8:
    numb[9]== 1 or 3
elif numb[8] == 4:
    numb[9]== 3 or 9
elif numb[8] == 2:
    numb[9]== 7 or 9


return numb

Any help would be highly appreciated!




Aucun commentaire:

Enregistrer un commentaire