【问题标题】:Return the number of times that the string "hi" appears anywhere in the given string -- Python codingbat problem返回字符串“hi”出现在给定字符串中任意位置的次数——Python codingbat问题
【发布时间】:2020-08-18 02:26:23
【问题描述】:

我知道我可以为此使用 .count() 函数,但我尝试使用 for 循环来执行此操作,并且在第 6 行中不断收到编译错误。有人看到这段代码有什么问题吗?为什么它不会给出相同的输出?提前致谢!

def count_hi(string):
# Create an empty list to add to
  num_hi = []
  # for every index in string , if the character is h and the next is i, 
  # add element to list
  for index in string:
    if string[index] == 'h' AND string[index + 1] == 'i':
      num_hi.append('hi found')
  return len(num_hi) # return length of list

【问题讨论】:

  • python 区分大小写。使用and 而不是AND
  • 我发现了两个问题。 AND 应该是小写的and。而你的 for 循环是循环遍历元素,而不是索引,所以index 是一个字符,例如'h'。代替for index in string,使用for index in range(len(string))

标签: python string loops for-loop


【解决方案1】:

为什么不使用count

def count_hi(string):
    return string.count('hi')

修复您的代码:

def count_hi(string):
    count = 0
    for i in range(1, len(string)):
        if string[i - 1] == 'h' and string[i] == 'i':
            count += 1
    return count
  1. Python 区分大小写,不是 AND 而是 and
  2. 追加到列表并计算它的开销很大,您应该只使用一个变量并在每次找到hi时递增它。
  3. 您可以使用range 从索引1 开始,而不是枚举,并从i - 11 检查您的字符串。避免再次检查。
  4. 我更喜欢使用.count() 的先前解决方案。既然有适合你的内置方法,为什么还要编写代码?

【讨论】:

    【解决方案2】:

    Harshal Parekh's Asnwer,它提供了更好的分析和解释。

    当你迭代一个字符串时,你迭代的不是索引,而是字母本身。对此的快速解决方法可能是:

    def count_hi(string):
      num_hi = []
      # for every index in string , if the character is h and the next is i, add element to list
      for index, _character in enumerate(string):
        if index == len(string) - 1:
          break  # on the last one, you'd get an index error.
        if string[index] == 'h' and string[index + 1] == 'i':  # "and", not "AND"
          num_hi.append('hi found')
      return len(num_hi) # return length of list
    

    【讨论】:

    • 虽然您的解决方案回答了这个问题,但它缺少一些可以帮助 OP 的有用点。就像附加到列表并计算元素是解决这个问题的正确方法一样吗?您的检查是否有必要打破(我们可以从索引 1 开始迭代)?这是一种计算字符串中子字符串的pythonic方法吗?
    【解决方案3】:

    最简单的方法是使用内置的集合模块。

    from collections import Counter
    
    def count_hi(string):
        counts = Counter(string.split())
        return print(counts['hi'])
    

    【讨论】:

      【解决方案4】:

      你可以试试这个,它应该可以解决问题。

      def count_hi(str):
            counter = 0
            str.lower()
            str.replace(' ', '')
            for i in range(0, len(str)-1):
              if str[i] == 'h' and str[i+1] == 'i':
                counter += 1
            return counter
      

      【讨论】:

        【解决方案5】:

        我的解决方案:

        def count_hi(str):
          sum = 0
          for i in range(len(str)-1):
            if str[i:(i+2)] == "hi":
              sum += 1
          return sum
        

        【讨论】:

        • 您可以尝试评论您的解决方案,以便其他人理解。我这样说是因为这是一个非 Python 的答案,更类似于在其他语言中如何解决同样的问题,在这些语言中,诸如 return s.count('hi') 之类的东西不可用或不鼓励使用。
        猜你喜欢
        • 2018-11-07
        • 2023-01-02
        • 2015-08-05
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 2012-07-13
        相关资源
        最近更新 更多