首先请允许我说,出于好奇,我正在自学 Python,并且有人向我推荐了一门公开的免费在线计算机科学类(class),所以如果我使用的术语不正确,我深表歉意。
我以前在这里看到过关于这个特定问题的问题 - 但我有一个单独的问题,不想劫持这些线程。问题:
“子字符串是另一个字符串中的任何连续字符序列。相同的子字符串可能在同一字符串中出现多次:例如,“assesses”有 2 次子字符串“sses”,而“trans-Panamanian banana”有子字符串 "an"6 次。编写一个程序,接受两行输入,我们称第一行针和第二行 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 语句,如果 location 小于 0,则中断。有什么方法可以使它成为“全局”条件,这样我就没有重复代码了吗?我想随着程序复杂性的提高,效率变得至关重要,所以我现在正在努力开发良好的实践。
python 专家会如何优化这段代码,还是我太挑剔了?
请您参考如下方法:
我认为 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避免多次检查位置 <0
