• + 2 comments

    Can somebody tell me how to approach this question. I am trying with dictionary but getting time out. Here have a look at my code and let me know if I can do any optimization? Or if I need to use another technique than please provide some resource related to that techinque.

    import re
    def solve(s,loc,word):
        if loc == len(s):
            wo = ''.join(word);
            for key, value in dictionary.items():
                if len(key) >= len(s) and wo == key[:len(s)]:
                    ans.append([value,key]);
        else:
            for i in range(len(mobile[s[loc]-2])):
                word.append(mobile[s[loc]-2][i]);
                solve(s,loc+1,word);
                word.pop();
    
    mobile = ["abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"];
    
    file = open("t9Dictionary",'r');
    
    dictionary = {}
    ans = []
    for line in file:
        dictionary[line.split("\n")[0]] = 0;
    #print(len(dictionary));   
    file = open("t9TextCorpus",'r');
    for line in file:
        for i in line.split():
            kk = re.findall(r'^[a-zA-Z]*[a-zA-Z]$',i)
            if len(kk) > 0:
                if i in dictionary:
                    dictionary[i] = dictionary[i]+1;
    
    #print(dictionary["over"]);               
    t = int(input());
    for i in range(t):
        test = input().strip();
        test1 = [int(x) for x in test];
        if test1.count(1) > 0:
            print("No Suggestions");
        else:
            solve(test1,0,[]);
            ans.sort(reverse=True);
            if len(ans) == 0:
                print("No Suggestions");
            else:
                for i in range(5):    
                    print(ans[i][1],end=';') 
                print("")
        ans.clear();