2015-10-22 148 views
0

我写了下面的代码来实现预期的结果。它的工作很好,直到200 input.i认为优化这段代码将解决我的问题。任何人都可以请帮我优化下面的代码。任何人都可以帮助我优化我的代码吗?

from collections import defaultdict 
number=input() 
list_mine=[] 
for i in range(1,number+1): 
    list_mine.append(raw_input("")) 
    #print list_mine 
#understanding the number of unique occurence 

unique=list(set(list_mine)) 

number_of_unique_occurence=len(unique) 

d=defaultdict(int) 
count=0 
for i in unique: 
    for j in list_mine: 
     #print "i is "+str(i) 
     if i==j: 
      count = count+1 
      d[i]=count 

    count=0 

print str(number_of_unique_occurence) 
check = 0 
counts =0 
list_for=[] 
for hel in list_mine: 
    #print "current element " + str(hel) 
    #print "index of that element is "+str(list_mine.index(hel)) 
    check = check+1 

    if list_mine.index(hel) > 0: 
     #print "check = " +str(check) 
     for jj in range(0,list_mine.index(hel)): 
      #print jj 
      if hel == list_mine[jj]: 
       #print "elemnt are there" 
       break 
      else: 
       if counts == list_mine.index(hel)-1: 
        #print "greater then zero   "+ str(hel) +" "+str(d[hel]) 
        list_for.append(d[hel]) 
        continue 
      counts=counts+1 

    else: 
     if check <= 1: 
      #print "at zero    "+ str(d[hel]) 
      list_for.append(d[hel]) 


print '%s' %' '.join(map(str, list_for)) 

样品输入

4 
bcdef 
abcdefg 
bcde 
bcdef 

样本输出

3 
2 1 1 

“BCDEF” 出现两次,在第一和最后位置输入即,换言之出现一次每个。第一次出现的次序是“bcdef”,“abcdefg”和“bcde”因此是输出。

+0

我几乎不敢问在200输入时会发生什么。 – TigerhawkT3

+0

实际执行时间越来越多..注意到..我从来没有优化过我的代码。我认为这将有助于解决问题吗? –

+0

我的代码是否有阻塞元素增加执行时间? –

回答

1

除非我在这里错过了一些细节,您正在寻找OrderedDict类型,它允许您按插入它们的顺序读出词典的条目,例如,

from collections import OrderedDict 
number=input() 

occurrences = OrderedDict() 
for i in range(1,number+1): 
    s = raw_input("") 
    occurrences[s] = occurrences.get(s, 0) + 1 
number_of_unique_occurence=len(occurrences) 
print number_of_unique_occurence 
print '%s' %' '.join(map(str, occurrences.values())) 
相关问题