让全球条件破裂

时间:2012-07-29 06:20:56

标签: python variables conditional break conditional-statements

请允许我通过说我自己学习python作为我自己的好奇心的一部分,并且我被推荐一个公开的免费在线计算机科学课程,所以我道歉,如果我使用不正确的术语,我会道歉。

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

“子字符串是另一个字符串中的任何连续字符序列。相同的子字符串可能在同一个字符串中多次出现:例如”assesses“有子串”sses“2次,而”trans-Panamanian banana“有编写一个带有两行输入的程序,我们称之为第一个针和第二个干草堆。打印针作为大海捞针的子串发生的次数。“

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

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语句,如果location小于0,则断开。有没有办法使这个'全局'的条件,所以我没有重复的代码?我认为效率对于提高计划的复杂程度至关重要,因此我现在正努力发展良好的实践。

python gurus如何优化这段代码,或者我只是太挑剔了?

7 个答案:

答案 0 :(得分:4)

我认为马修和达山有最好的解决方案。我将发布一个基于您的解决方案的变体:

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,使您无需检查位置&lt;多次0次

答案 1 :(得分:3)

查看正则表达式,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)))

答案 2 :(得分:0)

如Matthew Adams所述,最好的方法是使用python'd re module 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

这应该只花一天时间。

答案 3 :(得分:0)

甚至你的aproach也可以简化(使用这个事实,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]

答案 4 :(得分:0)

needle = "ss"
haystack = "ssi lass 2 vecess estan ss."

print 'needle occurs %d times in haystack.' % haystack.count(needle)

答案 5 :(得分:0)

你走了:

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)

答案 6 :(得分:0)

<强>答案

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)