发现两个字符串中字母的重复出现,使用for循环和剥离功能

问题描述 投票:0回答:1

算法:-逐一遍历单词1中的每个字符。如果此字符出现在word2中,则将1加到计数中。完成所有字符后,返回总计数。

>>>count_common_occurrences('bob y', 'bobbette z')
    3
>>>count_common_occurrences('bobbette z', 'bob y')
    4

这是我的代码

def count_common_occurrences(word1, word2):
    count = 0 
    for i in word1.strip():
        if i in word2.strip():
            count = count + 1
    return count

我得到的结果总是比示例中的结果大一倍,我最初怀疑函数的计数空间,因此我使用了strip,但此后结果仍然相同。我不知道是什么导致该函数计数超出其应有的数量

python for-loop strip
1个回答
1
投票

将空格字符视为匹配项,因此返回的字符数比您期望的多。

最简单的解决方法是检查空格字符并跳过它。

def count_common_occurrences(word1, word2):
    count = 0 
    for i in word1.strip():
        if i != ' ':
            if i in word2.strip():
                count = count + 1
    return count

print(count_common_occurrences('bob y', 'bobbette z'))
print(count_common_occurrences('bobbette z', 'bob y'))
© www.soinside.com 2019 - 2024. All rights reserved.