2016-11-10 31 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

相關問題