首页 > 解决方案 > 如何翻转二进制表示中的位模式?

问题描述

我有一个像这样的字符串BGGBG。现在我必须将所有BG翻转到GB。在这个字符串中有两个BG。现在如果我想将它表示为二进制(取 B=0 和 G=1),那么它将是01101。所以从这里想要翻转0110。这可能吗?如果是,如何在Python中完成?

仅供参考:这不仅仅是翻转位(0 到 1,反之亦然)。而是与翻转模式有关(如本例中的01)。

我知道我可以像这样使用 str.replace() :

string=string.replace("BG","GB") # will replace all BG to GB

实际上,这可能是在 codeforces 解决此问题的一种不错的方法。https://codeforces.com/problemset/problem/266/B

标签: python-3.xbit-manipulation

解决方案


我并不是说这是最好的、最可持续的,甚至是可接受的方式,但写这篇文章确实很有趣。我希望它能让你更接近解决你想要解决的问题:

import re

# I’m assuming that the string is "((BG)*(GB)*)*"
# any other characters will make this fail
input = 'BGBGBGGBGBGB'
output = ''

for two in re.findall('..', input):
    output += int.to_bytes(int.from_bytes(two.encode(), 'big') ^ 1285, 2, 'big').decode('ascii')

print(input)
print(output)

推荐阅读