【问题标题】:Return the number of times that the string "code" appears anywhere in the given string [closed]返回字符串“code”出现在给定字符串中任何位置的次数[关闭]
【发布时间】:2015-08-05 06:25:13
【问题描述】:

返回字符串"code"在任意位置出现的次数 给定的字符串,除了我们将接受'd' 的任何字母,所以 "cope""cooe" 计数。

我使用正则表达式通过以下代码实现了这一点:

import re


def count_code(str):
    exp = '^co[a-z|A-Z]e$'
    count = 0
    for i in range(len(str) - 1):
        if re.match(exp, str[i:i + 4]):
            count = count + 1

    return count

print count_code('aaacodebbb')  # prints 1
print count_code('codexxcode')  # prints 2
print count_code('cozexxcope')  # prints 2

有没有其他方法可以在不使用正则表达式的情况下实现这一点?

【问题讨论】:

  • 您的正则表达式变体效率低下。查看re.findall,并将其与len结合起来。
  • “还有其他方法吗……” - 是的,当然有。您有真正的问题吗?
  • len(re.findall(r'co[a-zA-Z]e', string))

标签: python string


【解决方案1】:

一种方法是您可以使用 co*e 生成所有可能的字符串,其中 * 是任何字母

喜欢

x=["co"+i+"e" for i in string.lowercase]

然后迭代

for i in x:
    if i in <your string>:
        count+=<your string>.count(i)

【讨论】:

  • 如果是codexxxcode 怎么办?那只会得到一个。
  • 您可以使用 str.count() 计算所有不重叠的实例。
【解决方案2】:

你可以试试这个:

def count_code(str):
    x=["co"+i+"e" for i in str.lower()]
    count = 0
    index = 0
    for i in x:
        if i in str[index:]:
            index = str.find(i)+1
            count+=1
    return count

print count_code('aaacodebbb')  # prints 1
print count_code('codexxcode')  # prints 2
print count_code('cozexxcope')  # prints 2      

【讨论】:

    【解决方案3】:

    这是一个简单而干净的解决方案:

      def count_code(str):
          count = 0
          for i in range(len(str)):
            if str[i:i+2] == "co" and str[i+3:i+4] == "e":
              count+=1
          return count
    

    【讨论】:

    • str 是 python 关键字。更简单的语法是使用“in”。
    • 是的,我知道。我使用 str 这个词的原因是因为这是一个 CodingBat 练习,他们使用 str 作为参数。但这仍然是一个好点。
    【解决方案4】:

    要改进其他答案,请注意不需要切片。我们可以将感兴趣的三个位置与应该存在的字母进行比较:

    def count_code(str):
      count = 0
      for i in range(len(str)-3):
        if str[i]=='c' and str[i+1] == 'o' and str[i+3]=='e':
          count+=1
      return count
    

    【讨论】:

    • 请解释为什么应该在现有答案上使用它。另外,在提交代码时,请确保代码实际上会先编译。
    【解决方案5】:
    def count_code(str):
      a = 0
      for i in range(len(str) - 3):
        if str[i:i+2] + str[i+3] == 'coe':
          a += 1
      return a
    

    【讨论】:

      【解决方案6】:

      你也可以试试: 使用 Python 字符串方法'count'

       def count_code1(str):
             counts=0
             for i in range(97,123):   #all the lowercase ASCII characters
              count+= str.count('co'+chr(i)+'e')
             return counts 
      

      【讨论】:

        【解决方案7】:
        def count_code(str):
          code = 0
          for c in range(len(str)-1):
            if str[c+1] == 'o' and str[c:c+4:3] == 'ce':
              code+=1
          return code
        

        【讨论】:

          【解决方案8】:

          您可以以一种可以重用的方式定义您的逻辑 - 在这种情况下,无需计数或正则表达式

          def count_code(str):
              start = 'co' #first 2 letter
              start1 = 'e' #last letter
              counter = 0 #initiate counter
              strlen=len(str) #for each word
              for i,x in enumerate(str):
                  if str[i:i+2]==start: 
                  #for each letter - is that letter and the next equal to start
                      if len(str[i:strlen]) >=4: #is string long enough?
                          if str[i+3]==start1: # if so is last letter right?
                              counter+=1
                          else:
                              counter
              return counter
          

          【讨论】:

            【解决方案9】:
            def count_code(s):
              count=0
              for i in range(len(s)):
                if s[-(i+3):-(i+1)]=='co' and s[-i]=='e':
                  count=count+1
              return count  
            

            【讨论】:

            • 避免使用名为 str 的参数隐藏内置类型 str
            • 欢迎来到 StackOverflow。虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。 How to Answer
            【解决方案10】:

            这应该也可以:

            def count_code(str):
              counter = 0
              for i in range(len(str)-3):
                if str[i:i+2] == 'co' and str[i+3] == 'e':
                  counter +=1
              return counter
            

            希望能帮到你!

            【讨论】:

              【解决方案11】:
              def count_code(str):
                a=''
                count=0
                for char in ("abcdefghijklmnopqrstuvwxyz"):
                  a=char
                  count+=str.count("co"+a+"e")
                return (count)
              

              【讨论】:

              • 不要使用str作为名字,它是一个内置类型并且与这个问题相关。
              【解决方案12】:
                a = 0
                for i in range(len(str)-3):
                   if str[i:i+2] == 'co' and str[i+3] == 'e':
                     a +=1
                return a
              

              【讨论】:

              • 之前的答案中已经给出了相同的解决方案。
              猜你喜欢
              • 2023-01-02
              • 2020-08-18
              • 2018-11-07
              • 1970-01-01
              • 1970-01-01
              • 2011-07-04
              • 2013-10-04
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多