2016-11-10 33 views
0

add name,其中是一个表示联系人姓名的字符串。这必须作为应用程序中的新联系人存储。 查找部分,其中是表示部分名称的字符串,用于搜索应用程序。它必须对开始的联系进行计数,并在新行上打印计数。 给定顺序添加和查找操作,按顺序执行每个操作。在Python中搜索另一个列表中的第n个字符串

Input: 
4 
add hack 
add hackerrank 
find hac 
find hak 

Sample Output 
2 
0 

We perform the following sequence of operations: 

1.Add a contact named hack. 
2.Add a contact named hackerrank. 
3.Find and print the number of contact names beginning with hac. 
    There are currently two contact names in the application 
    and both of them start with hac, so we print 2 on a new line. 
4.Find and print the number of contact names beginning with hak. 
    There are currently two contact names in the application 
    but neither of them start with hak, so we print 0 on a new line. 

我解决了它,但它需要很长时间的大量的字符串。我的代码是

addlist =[] 
findlist=[] 
n = int(input().strip()) 
for a0 in range(n): 
    op, contact = input().strip().split(' ') 
    if(op=='add'): 
     addlist.append(contact) 
    else: 
     findlist.append(contact) 
for item in findlist: 
    count=0 
    count=[count+1 for item2 in addlist if item in item2 if item==item2[0:len(item)]] 
    print(sum(count)) 

是否有任何其他方式来避免长时间的计算。

回答

0

就优化而言,为了便于阅读,我将代码分解了一些,并删除了多余的if语句。我不确定是否有可能进一步优化。

addlist =[] 
findlist=[] 

n = int(input().strip()) 

for a0 in range(n): 
    op, contact = input().strip().split(' ') 
    if(op=='add'): 
     addlist.append(contact) 
    else: 
     findlist.append(contact) 

for item in findlist: 
    count = 0 
    for item2 in addlist: 
     if item == item2[0:len(item)]: 
      count += 1 
    print(count) 

我在一次测试10562项,它会立即处理,因此,如果它落后于你,将您的处理器上被指责

+0

两者都是同样的事情。我只是想知道,如何减少多次迭代。 –

+0

如果我们检查80000到100000 –

+0

@Bishan Singh,我不能看到任何需要处理那么多数据的情况,但是如果你觉得疯狂,你可以尝试实现多线程并将负载分配到情侣线程。对于那些疯狂的高数字,这会提高处理速度。 – TheBestNightSky

相关问题