python-3.x - 如何翻转二进制表示中的位模式?
问题描述
我有一个像这样的字符串BGGBG。现在我必须将所有BG翻转到GB。在这个字符串中有两个BG。现在如果我想将它表示为二进制(取 B=0 和 G=1),那么它将是01101。所以从这里想要翻转01到10。这可能吗?如果是,如何在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
解决方案
我并不是说这是最好的、最可持续的,甚至是可接受的方式,但写这篇文章确实很有趣。我希望它能让你更接近解决你想要解决的问题:
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)
推荐阅读
- python - 在 Python 的 for 循环中使用 next 是否安全?
- python - 具有 keras=2.0.5 和 tensorflow-gpu=1.2.1 的 CUDA_ERROR_INVALID DEVICE
- python - Python在文件更改时锁定文件
- html - 两个 div:顶部 - 具有恒定高度和 div 内容的标题
- git - 无法将未更改的文件推送到 GITLAB
- excel - 将多列表转换为具有重复模式的单列
- android - MapBox userTrackingMode 在 Android 上无法正常工作
- javascript - 在 Node 中返回带有 fast-csv 的数组
- excel - VBA Excel - 填写网络表单无法点击提交按钮
- beagleboneblack - Beagleboard Black 上的 SPI