有没有更快的方法可以在 python 中计算二进制运算?
假设我有一个二进制字符串:z = abc
,其中a、b、c是0或1,因此我们可以将c
转换为0到7之间的整数。现在我想给 a,b,c 另一个“层”值,其中 a = 1/2^1 = 1/2, b = 1/2^2 = 1/4, c = 1/2^3 = 1/8。我的目标是创建一个字典,其中键是整数0-7,值是基于a、b、c值的关联计算。
我能够解决这个问题的唯一方法是“暴力”结果。例如,当键为 5 (z = 101) 时,值为 1/2+0+1/8 = 5/8,并手动执行所有计算,然后将该项目追加到字典中。 python 中是否有工具/方法可以让我更快地创建计算?我真的不知道该怎么做。任何建议/帮助表示赞赏。
Suppose I have a binary string: z = abc
, where a,b,c are either 0 or 1, so we can convert c
into an integer from 0 to 7. Now I want to give a,b,c another 'layer' of value, where a = 1/2^1 = 1/2, b = 1/2^2 = 1/4, c = 1/2^3 = 1/8. My goal is to create a dictionary, where the keys are integers 0-7, and values are the associated calculations based on a,b,c values.
The only way I'm able to solve this question is to 'brute force' the results. For example, when the key is 5 (z = 101), the value would be 1/2+0+1/8 = 5/8, and perform all calculations manually, then append the item to the dictionary. Is there a tool / method in python that will allow me to create the calculation faster? I really have no idea how I can do that. Any suggestions / help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种简单的方法是迭代位串,并将每个位乘以 0.5 的匹配幂:
对于
z = "101"
,这将使res
为 0.625即5/8
可以使用
sum
进行压缩:如果
z
实际上是一个整数,只需更改z
上面的s到format(z, 'b')
获取其二进制字符串表示形式。One naïve approach would be to iterate over the bit-string, and multiply each bit by the matching power of 0.5:
For
z = "101"
this will giveres
as 0.625 which is5/8
Could be compacted using
sum
:If
z
is actually an integer, just change thez
s above toformat(z, 'b')
to get its binary string representation.只是稍微详细说明一下我的评论:
输出:
这是您正在寻找的输出吗?
Just to elaborate on my comment a bit:
Output:
Is this the output you're looking for?
另一种方法是受益于矢量化:
输出:
Another way would be to benefit vectorization :
output :