【问题标题】:make a global condition break使全局条件中断
【发布时间】:2012-07-29 06:20:56
【问题描述】:

请允许我先说我正在自学 Python 作为我自己好奇心的一部分,并且我被推荐了一个免费的在线计算机科学课程,该课程是公开的,所以如果我使用的术语不正确,我深表歉意。

我之前在这里看到过关于这个特定问题的问题 - 但我有一个单独的问题来自他们并且不想劫持这些线程。问题:

"一个子字符串是另一个字符串中任意连续的字符序列。同一个子字符串在同一个字符串中可能出现多次:例如,“assesses”有 2 次子字符串“sses”,而“trans-Panamanianbanana”有子字符串 "an" 6 次。编写一个接受两行输入的程序,我们调用第一个 needle 和第二个 haystack。打印该 needle 出现的次数作为 haystack 的子字符串。"

我的解决方案(有效)是:

first = str(input())
second = str(input())

count = 0
location = 0
while location < len(second):
   if location == 0:
      location = str.find(second,first,0)
      if location < 0:
         break
      count = count + 1                          
   location = str.find(second,first,location +1)   
   if location < 0:
      break
   count = count + 1
print(count)

如果你注意到,我在两个不同的场合做了 if 语句,如果位置小于 0,则中断。有没有办法让它成为“全局”条件,所以我没有重复的代码?我想随着程序复杂性的提高,效率变得至关重要,所以我现在正努力发展良好的做法。

python 大师会如何优化这段代码,还是我太挑剔了?

【问题讨论】:

  • 在两个单独的路口断掉没有什么问题。
  • 话虽如此,一个完整的循环退出的简单方法是将代码封装在一个函数中并使用return。

标签: python variables conditional break conditional-statements


【解决方案1】:

我认为 Matthew 和 darshan 有最好的解决方案。我将根据您的解决方案发布一个变体:

first = str(input())
second = str(input())  

def count_needle(first, second):

        location = str.find(second,first)
        if location == -1:
                return 0 # none whatsoever
        else:
                count = 1
                while location < len(second):
                   location = str.find(second,first,location +1)   
                   if location < 0:
                      break
                   count = count + 1
        return count

print(count_needle(first, second))

想法:

  • 在适当的时候使用函数来构造代码
  • 在进入 while 循环之前初始化变量 location 可以避免多次检查位置

【讨论】:

    【解决方案2】:

    查看正则表达式,python 的 re 模块 (http://docs.python.org/library/re.html)。例如,

    import re
    first = str(input())
    second = str(input())
    regex = first[:-1] + '(?=' + first[-1] + ')'
    print(len(re.findall(regex, second)))
    

    【讨论】:

    • 虽然正则表达式通常很好,但findall 方法不适用于这个问题。使用“评估”示例尝试您的代码,它只会看到一个匹配项。原因是某些匹配项可能会重叠,这是正则表达式通常不允许的。
    • @Blckknght 好电话。我将对其进行编辑以包含前瞻(尽管这有点 hack-y)。
    • 为了澄清这些 cmets 对未来读者的意义,我的原始答案实际上是 regex=first 而不是当前的正则表达式,这导致了 Blckknght 指出的问题。
    【解决方案3】:

    正如 Matthew Adams 所说,最好的方法是使用 python'd re 模块 Python re module

    对于您的情况,解决方案如下所示:

    import re
    
    def find_needle_in_heystack(needle, heystack):
      return len(re.findall(needle, heystack))
    

    既然您正在学习 python,最好的方法是使用“DRY”[不要重复自己] 口头禅。有很多 python 实用程序可用于许多类似的情况。

    要快速了解一些非常重要的 python 模块,您可以学习这个课程:

    Google Python Class

    这应该只需要你一天的时间。

    【讨论】:

    • 正如我在 Matthew Adams 的回答中提到的,findall 不适用于重叠匹配。
    【解决方案4】:

    即使您的方法也可以简化(使用事实,即 find 返回 -1,而您要求它从不存在的偏移量进行搜索):

    >>> x = 'xoxoxo'
    >>> start = x.find('o')
    >>> indexes = []
    >>> while start > -1:
    ...     indexes.append(start)
    ...     start = x.find('o',start+1)
    >>> indexes
    [1, 3, 5]
    

    【讨论】:

      【解决方案5】:
      needle = "ss"
      haystack = "ssi lass 2 vecess estan ss."
      
      print 'needle occurs %d times in haystack.' % haystack.count(needle)
      

      【讨论】:

        【解决方案6】:

        给你:

        first = str(input())
        second = str(input())
        x=len(first)
        counter=0
        for i in range(0,len(second)):
           if first==second[i:(x+i)]:
              counter=counter+1
        print(counter)
        

        【讨论】:

          【解决方案7】:

          回答

          needle=input()
          haystack=input()
          counter=0
          for i in range(0,len(haystack)):
            if(haystack[i:len(needle)+i]!=needle):
               continue
            counter=counter+1
          print(counter)
          

          【讨论】:

            猜你喜欢
            • 2021-03-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-12-15
            • 1970-01-01
            相关资源
            最近更新 更多