比方说,如果一个子字符串包含一定数量的字符,我想要匹配它。然而,我不知道这个字符的确切数量,但我知道它不是负的。我该如何编写这个正则表达式?
from sys import stdin
import re
k = int(raw_input())
combo = re.compile(r'(?=(.*1.*){k})')
print [ s for s in combo.findall(stdin.readline().strip()) ]这有可能做到吗?如果是这样,我该怎么做呢?
编辑:示例输入:k=2字符串= 01010
预期输出:"101","0101","1010","01010“
因此在每个子字符串中,它恰好包含2个字符'1‘
发布于 2021-05-06 14:59:33
所以在这么多年之后,有人对这个问题给予了肯定。
一开始,我想不起我在哪里第一次看到这个问题,当我把这个问题发布在SO上的时候。不,这不是 comment所暗示的家庭作业,但只需在谷歌中键入几个关键字,我在以下位置找到了问题描述:
我对codeforces的判断是对的。我看到我实际上已经想出了一个解决方案并提交了它。这是我最快的解决方案:https://codeforces.com/contest/165/submission/4171748
k = int(raw_input())
def stable_search( zero, bin_num ):
import collections
c_one = ans = temp_ans = temp_z = 0
c_zero = collections.deque()
for f in bin_num[zero:]:
if f == '1':
c_zero.append(zero); zero = 0
c_one = -~c_one
if c_one >= k:
ans = ans + ( temp_z * temp_ans ) + temp_z
temp_ans = 0; temp_z = -~c_zero.popleft()
else: temp_ans, zero = -~temp_ans, -~zero
return ans + ( temp_z * temp_ans ) + temp_z
def mid(bin_num):
return stable_search(bin_num.find('1'), bin_num)
def find_zeros(bin_num):
import re
return sum((len(sed)*-~len(sed))>>1 for sed in re.findall( '0+', bin_num))
if k == 0: print find_zeros(raw_input())
else: print mid(raw_input())呀!看看所有这些位操作(我最近一定学到了按位操作)。顺便说一句,-~n只是在n上增加了一个。
再次查看代码,我看到正则表达式用于解决问题的一个方面(当k为0时),但在其他方面则使用一种我现在不确定完全理解的技术来完成。这看起来像是2分的问题,但我认为可能会有更多的问题,特别是考虑到时间限制。
如你所见,这个解决方案是在O(N)时间运行的,并且是用Python2编写的(当时有传言说Python3比Python2慢,所以每个人都坚持使用Python2,包括你的)。让我们看看在python3中重写它是否真的会让它变慢:
https://codeforces.com/contest/165/submission/115388714
不是的!变得更快了。
#!/usr/bin/python3
import collections
import re
def find_bin_ksubs (k: int, bin_num: str) -> int:
tmp_z = tmp_count = count = count_1 = 0
zeros = collections.deque()
count_0 = bin_num.find('1')
if count_0 == -1:
return 0
for b in bin_num[count_0:]:
if b == '1':
zeros.append(count_0)
count_0 = 0
count_1 += 1
if count_1 >= k:
count = count + (tmp_z * tmp_count) + tmp_z
tmp_count = 0
tmp_z = zeros.popleft() + 1
else:
count_0 += 1
tmp_count += 1
return count + (tmp_z * tmp_count) + tmp_z
def find_empties (bin_num: str) -> int:
reg = re.compile(r'0+')
return sum((count ** 2 + count) >> 1 \
for zeros in reg.findall(bin_num) if (count := len(zeros)))
if __name__ == '__main__':
if (k := int (input ())) == 0:
print (find_empties(input()))
else:
print (find_bin_ksubs(k, input()))编辑
公平地说,计算机自2013年以来一直在发展,所以我决定再次上传python2解决方案,只是为了进行比较fair...well看起来传言仍然是真的:
发布于 2013-06-10 15:57:24
正则表达式是字符串,所以可以随意使用您最喜欢的字符串格式结构:
combo = re.compile(r'(?=(.*1.*){%d})' % k)关于你编辑过的问题,我找不到一种简单的方法来使用正则表达式,下面呢?
def all_substrings(s):
m = len(s)
for i in range(m):
for j in range(i, m):
yield s[i:j+1]
s = '01010'
print [x for x in all_substrings(s) if x.count('1') == 2]https://stackoverflow.com/questions/17019235
复制相似问题