如何让我的程序更快

时间:2018-02-16 17:45:14

标签: python-3.x

"""
ID: nihaowa2
LANG: PYTHON3
TASK: namenum
"""
import time
start=time.time()
translate = {2: ("A","B","C"), 5: ("J","K","L"), 8: ("T","U","V"), 3:("D","E","F"), 6: ("M","N","O"), 9: ("W","X","Y"), 4: ("G","H","I") ,7 ("P","R","S")}
names=[""]
def newlist(nl,num):
    nnl=[]
    for i in translate[num]:
        for j in nl:
            nnl.append(j+i)
               return nnl
gnd=open ('dict.txt', 'r')
goodnames=[]
for i in range(4616):
    goodnames.append(gnd.readline()[:-1])
goodnames.append(gnd.readline())
fin = open ('namenum.in', 'r')
fout = open ('namenum.out', 'w')
namenumber=(fin.readline().split()[0])
for i in namenumber:
    names=newlist(names,int(i))
ok=[]
for i in names:
    if i in goodnames:
        ok.append(i)
if ok==[]:
    fout.write("NONE\n")
else:
    ok.sort()
    for i in ok:
       fout.write(i+"\n")
fout.close()

上面的代码是我尝试解决this问题。但是平地机说这太慢了。我需要它在1秒钟内运行。有人可以给我一些建议吗?

1 个答案:

答案 0 :(得分:0)

如果您读完整个文件,从{"Number" : [list of names]}准备字典会更快 - 为简单起见,我选择保留字符串输入并从字典的键中创建一个字符串{str:[str,...], ...}

然后你可以简单地在字典中查找奶牛数字,其中包括O(1):

mapping = {'A': '2', 'B': '2', 'C': '2', 
           'D': '3', 'E': '3', 'F': '3', 
           'G': '4', 'H': '4', 'I': '4', 
           'J': '5', 'K': '5', 'L': '5', 
           'M': '6', 'N': '6', 'O': '6', 
           'P': '7', 'R': '7', 'S': '7',
           'T': '8', 'U': '8', 'V': '8', 
           'W': '9', 'X': '9', 'Y': '9', 
           'Q': '', 'Z': ''  # part of names in the file, not mapped to a number
      } 

# read file, one word per list entry, cleaned
def readDict(fn="dict.txt"):
    with open(fn) as f:
        all = f.readlines()
    return [x.strip('\n').strip() for x in all] 

# a name as number
def getNameAsNum(name):
    return ''.join( mapping[c] for c in name)

# dict of numbers as key and all names as list
def namesAsNums(): 
    names = readDict()

    d={}
    for name in names: 
        asNum = getNameAsNum(name) 
        if asNum and name:
            d.setdefault(asNum[:], list())  
            d[asNum].append(name[:])
            d[asNum].sort()
    return d

# get the mapping of number to list of names
nan = namesAsNums()

# get input and ---
cow = input("Which cow serial number?")
# limit string to 12
cow = ''.join(cow[0:12])

# ... check and print
if cow in nan:
    for n in nan[cow]:
        print(n)
else:
    print ("NONE")

解析文件需要我的笔记本电脑0.16秒 - 在字典中查找它是可以忽略不计的。

如果文件中有许多具有相同编号的名称,我会放弃每个dict-insert上的排序,并在所有名称都在其中时使用第二个遍历整个dict对列表进行排序 - 但对于此文件,相同的运行时间。