1

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

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

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

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

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 大师将如何优化这段代码,还是我太挑剔了?

4

7 回答 7

4

我认为 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使您免于多次检查 location < 0
于 2012-07-29T06:55:50.633 回答
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)))
于 2012-07-29T06:24:44.490 回答
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 模块,您可以通过这个类:

谷歌 Python 类

这应该只需要你一天。

于 2012-07-29T06:43:56.677 回答
0
needle = "ss"
haystack = "ssi lass 2 vecess estan ss."

print 'needle occurs %d times in haystack.' % haystack.count(needle)
于 2012-07-29T22:14:24.380 回答
0

甚至你的方法也可以简化(它使用了这样一个事实,即 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]
于 2012-07-29T06:51:49.100 回答
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)
于 2013-05-18T03:21:53.263 回答
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)
于 2012-08-24T10:04:10.233 回答