这个替代的按位运算符函数有什么问题?

时间:2016-04-19 07:40:08

标签: python bitwise-operators

n1 = "0b1110"
n2 = "0b101"

def bitwise_or(num1, num2):
    diff1 = ""
    new_num1 = []
    new_num2 = []
    new_num = []
    for c in num1:
        new_num1.append(c)
    for c in num2:
        new_num2.append(c)
    if len(num1) != len(num2):
        if len(num1) > len(num2):
            diff1 = "0" * (len(num1) - len(num2))
            for c in diff1:
                new_num2.append(c)
        if len(num1) < len(num2):
            diff1 = "0" * (len(num2) - len(num1))
            for c in diff1:
                new_num1.append(c)
    for i in range(len(new_num1)):
        if new_num1[i] == "1" or new_num2[i] == "1":
            new_num.append("1")
        else:
            new_num.append(new_num1[i])
    final = "".join(new_num)
    return final

print(bitwise_or(n1,n2))

我创建了一个应该复制|的函数操作,但它无法正常工作。正确的答案是打印出0b1111,但我不明白它是如何得到的。

3 个答案:

答案 0 :(得分:1)

当您填充零时,您应该在之前插入数字的位。

0b1表示数字1。如果您尝试使用0b111010b10000,则无法将其更改为0b00001,您必须将其填充为0b

此外,您对0b11101的处理方式仍有效,但并不清晰,因此无法读取。它只是&#34;发生&#34;工作是因为当你循环遍历0b000010时,第一个字符都是new_num.append(new_num1[0]),因此你最终会进入b != '1'然后if,因此b测试失败,new_num插入list

我建议您只需删除开头的前缀,然后在结尾添加。这也略微简化了正确的填充。

顺便说一句:要将字符串转换为字符列表,您只需在其上调用new_num1 = list(num1)

extend

此外,要向列表中添加一定数量的元素,您可以使用>>> my_list = list('hello') >>> my_list ['h', 'e', 'l', 'l', 'o'] >>> my_list.extend('world') >>> my_list ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] 方法,或者可以使用切片分配:

def bitwise_or(num1, num2):
    new_num1 =list(num1)
    new_num2 = list(num2)
    if len(num1) > len(num2):
        new_num2[2:2] = '0' * (len(num1) - len(num2))
    elif len(num1) < len(num2):
        new_num1[2:2] = '0' * (len(num2) - len(num1))

    new_num = []
    for c1, c2 in zip(new_num1, new_num2):
        if c1 == "1" or c2 == "1":
            new_num.append("1")
        else:
            new_num.append(c1)
    return ''.join(new_num)

所以你的代码会变得像这样:

def bitwise_or(num1, num2):
    new_num1 =list(num1[2:])
    new_num2 = list(num2[2:])
    if len(num1) > len(num2):
        new_num2[:0] = '0' * (len(num1) - len(num2))
    elif len(num1) < len(num2):
        new_num1[:0] = '0' * (len(num2) - len(num1))

    new_num = []
    for c1, c2 in zip(new_num1, new_num2):
        if c1 == "1" or c2 == "1":
            new_num.append("1")
        else:
            new_num.append(c1)
    return '0b' + ''.join(new_num)

但我宁愿明确处理前缀:

<% @pictures.each do |picture| %>
  <%= image_tag('loader.gif', class: 'preloaded-picture', data: {source: picture.source}) %>
<% end %>

答案 1 :(得分:1)

您所遵循的方法有点复杂,但代码中的错误是在长度不同的情况下用右键填充零。在给定的情况下,你得到的0b101变为0b1010,与0b1110的ORed给出你最终得到的结果。你应该留下二进制数字,即0b101将变为0b0101。此代码有效

n1 = "0b1110"
n2 = "0b101"

def bitwise_or(num1, num2):
    new_num1 = []
    new_num2 = []
    new_num = []

    for c in num1[2:]:
        new_num1.append(c)

    for c in num2[2:]:
        new_num2.append(c)

    if len(num1) != len(num2):
        if len(num1) > len(num2):
            diff1 = ["0"] * (len(num1) - len(num2))
            new_num2 = diff1 + new_num2
        if len(num1) < len(num2):
            diff1 = ["0"] * (len(num2) - len(num1))
            new_num1 = diff1 + new_num1
    for i in range(len(new_num1)):
        if new_num1[i] == "1" or new_num2[i] == "1":
            new_num.append("1")
        else:
            new_num.append(new_num1[i])
    final = "".join(new_num)
    return final


print(bitwise_or(n1, n2))

我建议将二进制数(跳过'0b'前缀)转换为整数列表,然后逐位应用OR逻辑运算符。您也可以尝试列出理解,例如

new_num1 = [int(i) for i in n1[2:]]

和外部函数(您也可以在另一个函数中定义,例如左边的函数填充较短的数字。

答案 2 :(得分:0)

这是我的优化版本。一个人不一定要像这样做,但将其视为探索Python功能的灵感。它可以处理任意数量的输入参数btw,但可能(?)仅适用于Python 3 ...

def format_binary_string(bin_string, length, prefix=""):
    return "{}{:0{}b}".format(prefix, int(bin_string, 2), length)

def bitwise_or(*numbers):
    max_length = max(len(n) for n in numbers)
    bits = [format_binary_string(n, max_length, "") for n in numbers]

    new_bits = ["1" if "1" in bs else "0" for bs in zip(*bits)]
    return "".join(new_bits)


n1 = "0b1110"
n2 =  "0b101"
print(bitwise_or(n1, n2))