问题描述
我写了下面的代码来达到预期的效果。直到200次输入都可以正常工作。我认为优化此代码可以解决我的问题。 谁能帮我优化以下代码。
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”,因此是输出。
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()))