给定二进制字符串计数所有二进制数的频率与各种lenghts

发布于 2025-02-10 04:30:27 字数 356 浏览 1 评论 0原文

给定一个字符串,例如'0100011' length = 2我们必须计算字符串对的频率:00,01,10,11

00 - > 2,01-> 2,10 - > 1,11-> 1

问题是,如果我只使用count('00')函数,则它不起作用,因为它只找到一个出现:<代码>“ _ _ _ 000 _ _” 。

我一直想知道解决此类问题的正确方法是什么,因为目前我尝试使用2个指针(索引和长度)创建某种形式的子字符串检查器,这些检查器来回肯定它不是错过任何组合,但感觉不对劲

Given a string like '0100011'
and a length = 2 we have to count the frequency of pairs in the string: 00,01,10,11.

00 -> 2 , 01 -> 2 , 10 ->1 , 11->1

The problem is if I just use the count('00') function, it doesn't work since it only finds one occurrence: " _ _ 000 _ _".

I've been wondering what the right approach to this kind of problem would be, since for the moment i've tried to create some sort of substring checker with 2 pointer(index and length) which goes back and forth to be sure it doesn't miss any combination but it doesn't feel right

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

獨角戲 2025-02-17 04:30:27

这是我的做法:

length = 2
s = '0100011'

counter = {}

for i in range(2**length):
    b = f'{i:0{length}b}'
    for j in range(len(s)-1):
        if b == s[j:j+length]:
            counter[b] = counter.get(b, 0) + 1

print(counter)

将产生:

{'00': 2, '01': 2, '10': 1, '11': 1}

长度== 3:

{'000': 1, '001': 1, '010': 1, '011': 1, '100': 1}

...

对于长度== 7,显然:

{'0100011': 1}

here is how I did it:

length = 2
s = '0100011'

counter = {}

for i in range(2**length):
    b = f'{i:0{length}b}'
    for j in range(len(s)-1):
        if b == s[j:j+length]:
            counter[b] = counter.get(b, 0) + 1

print(counter)

will produce:

{'00': 2, '01': 2, '10': 1, '11': 1}

for length == 3:

{'000': 1, '001': 1, '010': 1, '011': 1, '100': 1}

...

for length == 7, obviously:

{'0100011': 1}
最初的梦 2025-02-17 04:30:27

如果要找到单个二进制子字符串的出现数量,则可以使用字符串切片来获取每个连续的字母对:

data = "0100011"
target = "00"

sum(data[start:start+len(target)] == target for start in range(len(data) - len(target)))

此输出:

2

如果您想找到特定长度的所有二进制字符串的出现数量,则可以使用collections.counter而不是:

Counter(data[start:start+len(target)] for start in range(len(data) - len(target)))

输出:

Counter({'01': 2, '00': 2, '10': 1})

此 返回0。)

If you want to find the number of occurrences of a single binary substring, you can use string slicing to get each consecutive pair of letters:

data = "0100011"
target = "00"

sum(data[start:start+len(target)] == target for start in range(len(data) - len(target)))

This outputs:

2

If you want to find the number of occurrences of all binary strings of a particular length, you could use a collections.Counter instead:

Counter(data[start:start+len(target)] for start in range(len(data) - len(target)))

This outputs:

Counter({'01': 2, '00': 2, '10': 1})

(Note that if you try to look up the frequency of a binary string that doesn't occur, the Counter will simply return 0.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文