【问题标题】:Count the number of the same letters in 2 strings [duplicate]计算2个字符串中相同字母的数量[重复]
【发布时间】:2020-02-08 03:00:23
【问题描述】:

我需要计算 2 个字符串中有多少个共享字母。

s1="hello"
s2="leeo"

def shared(s1, s2):
    for letter in s2:
        if letter in s1:
            find = s2.count(s1)
            print(find)

它给我的输出:

0
0
0
0
0
0
0
None

但它假设是:

3

我有点迷路了。

【问题讨论】:

  • 我猜是重复的,在 SO 上搜索集合交集
  • 应该有类似s1.count(letter) 的东西,我们正在计算letters1 中出现的频率,不是吗?!

标签: python


【解决方案1】:

您的问题是您计算了字符串'leo''hello' 的出现次数,它正好为0,因为'leo' 中不存在字符串'hello'

在您的情况下,变量letter 在循环中一个接一个地保存值'l''e''o'。要使您的代码正常工作,请将行更改为

find = s1.count(letter)

【讨论】:

    【解决方案2】:

    试试这个:

    s1="hello"
    s2="leo"
    
    def shared(s1, s2):
      find = 0
    
      for letter in s2:
          if letter in s1:
              find += 1
      return find
    
    print(shared(s1, s2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-17
      • 2017-12-05
      • 2016-01-01
      • 2019-12-09
      • 1970-01-01
      • 2013-11-04
      • 2015-09-19
      • 1970-01-01
      相关资源
      最近更新 更多