Python程序获取连续重复子串的个数
给定一个子串 K,任务是编写一个Python程序,找出 K字符串在每次连续出现的 K 中的重复。
例子
Input : test_str = ‘geeksgeeks are geeksgeeksgeeks for all geeks’, K = “geeks”
Output : [2, 3, 1]
Explanation : First consecution of ‘geeks’ is 2.
Input : test_str = ‘geeksgeeks are geeksgeeksgeeksgeeks for all geeks’, K = “geeks”
Output : [2, 4, 1]
Explanation : First consecution of ‘geeks’ is 2, next comes with 4 consecution of geeks.
方法一:使用split() + count() + list comprehension
仅适用于连续以空格分隔的特定情况。在这种情况下,使用 split() 拆分每个单词,并使用 count() 评估每个段的重复计数。
Python3
# Python3 code to demonstrate working of
# Number of repeated substrings in consecution
# Using split() + count() + list comprehension
# initializing string
test_str = 'geeksgeeks are geeksgeeksgeeks for all geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "geeks"
# count() counts repetition
res = [sub.count(K) for sub in test_str.split(' ') if sub.count(K) != 0]
# printing result
print("String repetitions : " + str(res))
Python3
# Python3 code to demonstrate working of
# Number of repeated substrings in consecution
# Using findall() + regex + len()
import re
# initializing string
test_str = 'geeksgeeksaregeeksgeeksgeeksforallgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'geeks'
n = len(K)
# getting regex
regx = re.compile(f'((?:{K})+)')
# getting repeats counts
# findall finding all substring joined repetitions
res = [len(occ) // n for occ in regx.findall(test_str)]
# printing result
print("String repetitions : " + str(res))
输出:
The original string is : geeksgeeks are geeksgeeksgeeks for all geeks
String repetitions : [2, 3, 1]
方法二:使用findall() + regex + len()
在这里,所有的运行都是为子串的重复计算的,然后长度除以子串长度给出重复次数的度量。
蟒蛇3
# Python3 code to demonstrate working of
# Number of repeated substrings in consecution
# Using findall() + regex + len()
import re
# initializing string
test_str = 'geeksgeeksaregeeksgeeksgeeksforallgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'geeks'
n = len(K)
# getting regex
regx = re.compile(f'((?:{K})+)')
# getting repeats counts
# findall finding all substring joined repetitions
res = [len(occ) // n for occ in regx.findall(test_str)]
# printing result
print("String repetitions : " + str(res))
输出:
The original string is : geeksgeeks are geeksgeeksgeeks for all geeks
String repetitions : [2, 3, 1]