Python 查找循环字符串中字符串出现的总数
我目前正在学习Python,我被困在这个特定的问题上。 这是我目前的代码:Python 查找循环字符串中字符串出现的总数,python,python-3.x,Python,Python 3.x,我目前正在学习Python,我被困在这个特定的问题上。 这是我目前的代码: word = input() text = 0 wordch = 0 positions = 0 repeated = 0 while repeated != 2: for i in range(0, len(tablet)): if tablet[i] == word[wordch]: text += 1 wordch += 1
word = input()
text = 0
wordch = 0
positions = 0
repeated = 0
while repeated != 2:
for i in range(0, len(tablet)):
if tablet[i] == word[wordch]:
text += 1
wordch += 1
if text == len(word):
positions += 1
text = 0
wordch = 0
elif repeated == 1 and text == len(word):
positions += 1
text = 0
wordch = 0
break
elif i == len(tablet)-1:
repeated += 1
break
elif tablet[i] != word[wordch]:
text == 0
wordch == 0
print(positions)
我希望有一个代码是真正的基本使用相同的概念,但请不要回答。
谢谢大家! 我试图用不同的方法来解决这个问题。正如我们所知,如果我们试图从末尾以循环方式创建子字符串,那么我们只能使用
(len(fav_word))-1
字母,因为如果我们获取更多字符,我们将从一开始就创建它们,而无需循环
因此,我刚刚从原始字符串创建了一个新字符串,将起始的(len(fav_word))-1添加到原始字符串,然后在新字符串中查找所有出现的fav_字符串
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += 1
x = "cabccabcab"
fav = "abc"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 3
x = "ababa"
fav = "aba"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 2
x = "aaaaaa"
fav = "aa"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 6
x = "abaaba"
fav = "aaba"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 2
我试图用不同的方法来解决这个问题。正如我们所知,如果我们试图从末尾以循环方式创建子字符串,那么我们只能使用(len(fav_word))-1
字母,因为如果我们获取更多字符,我们将从一开始就创建它们,而无需循环
因此,我刚刚从原始字符串创建了一个新字符串,将起始的(len(fav_word))-1添加到原始字符串,然后在新字符串中查找所有出现的fav_字符串
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += 1
x = "cabccabcab"
fav = "abc"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 3
x = "ababa"
fav = "aba"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 2
x = "aaaaaa"
fav = "aa"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 6
x = "abaaba"
fav = "aaba"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 2
def find_str(g,find):
lg=len(g)
lf=len(查找)
x=0
s=“”
对于索引,枚举中的i(g):
如果i==查找[0]:
如果索引+lfdef find_str(g,find):
lg=len(g)
lf=len(查找)
x=0
s=“”
对于索引,枚举中的i(g):
如果i==查找[0]:
如果index+lf,我认为leetcode中存在这个问题。这样的圆形阵列问题,一般需要连续运行两个for循环。第一个运行一次,并保留一个余数。第二个循环仅部分运行,直到剩余部分达到find字符串的大小。请注意n中的顺序。我认为这个问题存在于leetcode中。这样的圆形阵列问题,一般需要连续运行两个for循环。第一个运行一次,并保留一个余数。第二个循环仅部分运行,直到剩余部分达到find字符串的大小。请注意此处n中的顺序。伟大的解决方案。我认为您的事件不正确AAAAA findall aa应该有3次而不是6次请检查问题陈述。伟大的解决方案。我认为您的事件不正确AAAAA findall aa应该有3次而不是6次请检查问题陈述。
def split(word):
return [char for char in word]
x = "aaaaaa"
pattern = "aa"
mylist=split(x)
ok=True
occurrences=0
buffer=""
while ok:
char=mylist.pop(0)
buffer+=char
if buffer==pattern:
occurrences+=1
buffer=""
if len(mylist)==0:
ok=False
print(occurrences)
output:3