This code I try to write based on last week codewars event that I joined which I can't figure it out during the event.
The question is:
T9 Autocomplete The file contacts.txt has names and phone numbers.
The format is:
column 1 = name
column 2 = phone numberYour program should receive a sequence of numbers and return the possible contacts that it could match on a phone keypad.
The letters for T9 autocomplete are:
[[2, "ABC"], [3, "DEF"], [4, "GHI"], [5, "JKL"], [6, "MNO"], [7, "PQRS"], [8, "TUV"], [9, "WXYZ"]]
For simplicity: - Ignore 1's and 0's for name matching. - Assume that matches always start at the beginning of the name or phone number
Output the autocomplete contacts for the following inputs:
- 728
- 5203
- 273
- 2738
I paste the contact list (contacts.txt) here.
My idea:
- create a dictionary key-value pair between number and characters
- translate number into a list of characters e.g. 728 --> ['PQRS', 'ABC', 'TUV']
- loop through the contacts.txt file and check the first characters whether it is valid in the first element of list in #2 above or not. if yes, then add correct point by 1. then, check the second characters in that line whether it exist in list #2 above or not. if yes, then add another correct point by 1. if not, reset the score and go to next line.
- If the correct point when the loop finish means we found the result based on the search condition. return that line.
t9_dict = {
2: "ABC",
3: "DEF",
4: "GHI",
5: "JKL",
6: "MNO",
7: "PQRS",
8: "TUV",
9: "WXYZ",
}
def t9_input(number):
list_text = []
for i in str(number):
if int(i) != 0:
list_text.append(t9_dict[int(i)])
return list_text
def read_contact(list_text):
filename = 'contacts.txt'
count = 0
f = open(filename, "r")
for line in f:
for j in range(len(list_text)):
if count < len(list_text):
if line.upper()[count] in list_text[count]:
count += 1
else:
count = 0
break
else:
count = 0
break
if count == len(list_text):
f.close()
return(line)
f.close()
return "no result"
#print(t9_input(728))
#print(t9_input(5203))
print(read_contact(t9_input(728))) #return Patricia Adkins 741-256-2766
print(read_contact(t9_input(5203))) #return Kadyn Giles 597-981-0606
print(read_contact(t9_input(273))) #return Brennan Rosales 930-238-6553
print(read_contact(t9_input(2738))) #return no result
Even though the above functions return the correct answer, however, I want to know what I can improve further.