Python - N 重复 K字符的非重叠出现
给定一个字符串,计算 N 个重复的 K 个字符的非重叠出现。
Input : test_str = ‘aaabaaaabbaa’, K = “a”, N = 3
Output : 2
Explanation : “aaa” occurs twice as non-overlapping run.
Input : test_str = ‘aaabaaaabbbaa’, K = “b”, N = 3
Output : 1
Explanation : “bbb” occurs once as non-overlapping run.
方法 #1:使用 sum() + split() [仅适用于双字符串]
在这种情况下,在 K 以外的字符处执行拆分,然后计算每个段的出现次数,并使用 sum() 对频率求和。这适用于仅包含 2 个唯一字符的字符串。
Python3
# Python3 code to demonstrate working of
# Non-Overlapping occurrences of N Repeated K character
# Using split() + sum
# initializing string
test_str = 'aaabaaaabbaa'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "a"
# initializing N
N = 2
# getting split char
spl_char = [ele for ele in test_str if ele != K][0]
# getting split list
temp = test_str.split(spl_char)
# getting Non-Overlapping occurrences
res = sum( len(sub) // N for sub in temp)
# printing result
print("The Non-Overlapping occurrences : " + str(res))
Python3
# Python3 code to demonstrate working of
# Non-Overlapping occurrences of N Repeated K character
# Using re.findall()
import re
# initializing string
test_str = 'aaabaaaabbaa'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "a"
# initializing N
N = 2
# getting length using len()
# getting all occ. of substring
res = len(re.findall(K * N, test_str))
# printing result
print("The Non-Overlapping occurrences : " + str(res))
输出
The original string is : aaabaaaabbaa
The Non-Overlapping occurrences : 4
方法 #2:使用 re.findall()
这是可以执行此任务的另一种方式。这可以处理所有类型的字符串并使用 regex() 来解决这个问题。
Python3
# Python3 code to demonstrate working of
# Non-Overlapping occurrences of N Repeated K character
# Using re.findall()
import re
# initializing string
test_str = 'aaabaaaabbaa'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "a"
# initializing N
N = 2
# getting length using len()
# getting all occ. of substring
res = len(re.findall(K * N, test_str))
# printing result
print("The Non-Overlapping occurrences : " + str(res))
输出
The original string is : aaabaaaabbaa
The Non-Overlapping occurrences : 4