[英]How can I compare 2 words and count the strings?
有人可以用我的代碼幫助我比較 2 個單詞,然后計算字符串差異嗎? 現在我的代碼生成了錯誤的差異計數。 好像數的太多了。 我檢查了我的變量是否正確,確實如此。
def difference(word_one, word_two):
count = 0
for letter in range(6):
if word_one[letter] == word_two[letter]:
count += 1
print(letter, "letter is right.")
return count
更新我的代碼,但仍然有些不工作。 有時當我數出正確的字母時,它們並不像這樣匹配。
BETTER Password incorrect 5/6 correct BASHER
def correct_letter(word_one, word_one):
count = 0
for letter in range(6):
if word_one[letter] != word_two[letter]:
count += 1
print(letter, "out of 6 letter is right.")
return count
只是另一個建議:
def difference(word_one, word_two):
return sum(l1 != l2 for l1, l2 in zip(word_one, word_two))
這具有不要求word_one
和word_two
具有相同長度的優點,以及您可能從zip
和sum
獲得的任何效率增益。
你當然應該使用
def overlap(word_one, word_two):
return sum(l1 == l2 for l1, l2 in zip(word_one, word_two))
如果你想找到兩個字符串之間的相似之處而不是差異
def strcmp(word_one, word_two):
count = 0
i = j = 0
while i < len(word_one) and j < len(word_two):
if word_one[i] != word_two[j]:
count += 1
i += 1
j += 1
while i < len(word_one):
count += 1
i += 1
while j < len(word_two):
count += 1
j += 1
return count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.