【发布时间】:2016-11-04 12:40:50
【问题描述】:
我想计算子字符串在字符串中“相邻”出现的次数, 例如,给定字符串“8448442844”和子字符串“844”,我想要结果“2”。 我知道 string.count(substring) 函数,在这个例子中,使用这个函数,我会得到结果“3”。但我想要结果“2”。我怎样才能实现我的目标,在此先感谢。
【问题讨论】:
-
为此写一个算法,简单:)
我想计算子字符串在字符串中“相邻”出现的次数, 例如,给定字符串“8448442844”和子字符串“844”,我想要结果“2”。 我知道 string.count(substring) 函数,在这个例子中,使用这个函数,我会得到结果“3”。但我想要结果“2”。我怎样才能实现我的目标,在此先感谢。
【问题讨论】:
这对于任何相邻的子字符串都可以正常工作:
a = "8448442844"
sol, sub = 0, "844"
for i in range(1, a.count(sub)+1):
if a.count(str(sub*i)): sol = i
else: break
print (sol)
# 2
也可以使用Comprehension 和sum 转换为单行:
a, sub = "8448442844", "844"
sol = sum([1 for x in range(1, a.count(sub)+1) if a.count(str(sub*x))])
# 2
【讨论】:
使用 str.count
>>> nStr = '000123000123'
>>> nStr.count('123')
2
或者使用类似的东西
nStr = '000123000123'
pattern = '123'
count =0
flag=True
start=0
while flag:
a = nStr.find(pattern,start) # find() returns -1 if the word is not found,
#start i the starting index from the search starts(default value is 0)
if a==-1: #if pattern not found set flag to False
flag=False
else: # if word is found increase count and set starting index to a+1
count+=1
start=a+1
print(count)
【讨论】:
你可以这样试试。也许把它放在一个def中。它工作得很好
import string
s = "8448442844"
sub = "844"
max_sub = sub
count = 0
while string.find(s, max_sub) != -1:
max_sub = max_sub + sub
count +=1
print count
【讨论】:
您可以使用str.split、itertools.groupby 和max 的技巧来获得结果:
In [1]: import itertools
In [2]: "8448442844".split("844")
Out[2]: ['', '', '2', '']
In [3]: [len(list(lst)) for key, lst in itertools.groupby("8448442844".split("844")) if key == ""]
Out[3]: [2, 1]
In [4]: max([len(list(lst)) for key, lst in itertools.groupby("8448442844".split("844")) if key == ""])
Out[4]: 2
【讨论】: