[英]Algorithms for counting identical characters in the same position between two strings
兩者中哪一個是最佳代碼和/或更多pythonic代碼? 函數返回字符串1中在字符串2的相應位置中包含相同字符的位置數:
def compare(s1, s2):
count = 0
for i in s1:
if i == s2[s1.index(i)]:
count += 1
print(count)
def compare2(s1, s2):
count = 0
for i in range(0, len(s1)):
if s1[i] == s2[i]:
count += 1
print(count)
就性能而言,嚴格來說,第一個compare()是二次函數,因為它在O(n)for循環內具有O(n) index()操作。 第二個compare2()更好,因為它與i
一起使用O(1)隨機訪問索引。
也就是說,@ CharlesDuffy指出了正確性問題,需要首先解決。
對於函數調用開銷並不重要的長字符串,請考慮以下替代方法,它應該運行得非常快:
>>> a = 'abcdefghijklmnopqrstuvwxyz'
>>> b = 'a---e---i-----o-----u---y-'
>>> sum(map(str.__eq__, a, b))
6
在Python 2中,添加此優化以提高緩存效率:
>>> from itertools import imap # iterator version of map()
>>> sum(imap(str.__eq__, a, b))
6
第二個是最佳選擇,因為您不必不必要地調用函數(c1.index())。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.