XOR two blocks in python

自古美人都是妖i 提交于 2019-12-10 22:56:32

问题


i am new to programming in python...i want to make XOR between 2 blocks here is my code

def XorBlock(block1, block2):
    l = len(block1);
    if (l != len(block2)):
        raise ValueError, "XorBlock arguments must be same length"
    return [(block1[j]+block2[j]) % 2 for j in xrange(l)];

but when i call it gives me

TypeError: not all arguments converted during string formatting

so please anyone help me where is the bug in this code..thanks in advance


回答1:


Perhaps this is what you're looking for:

def XorBlock(block1, block2):
    l = len(block1)
    if l != len(block2):
        raise ValueError
    #         |-> Converting into int
    return [(int(block1[j])+int(block2[j])) % 2 for j in xrange(l)]
    #                        |-> Converting into int


if __name__ == '__main__':
    print XorBlock("12345", "23456")

>>> XorBlock("010101", "108734")
[1, 1, 0, 0, 1, 1]

I decided that keeping both arguments as strings would be best, as in binary, you may have to have some 0s before any digits of value.




回答2:


This part is wrong, take a look:

(block1[j]+block2[j]) % 2

both items are string, therefore, the result is a string. In short, python treats your %2 as a string formatting command.

"string"%something

will expect the string to specify where it should format something. If it doesn't specify anything, the current TypeError will be raised. What you probably need is something like this:

return[(int(block1[j])+int(block2[j])) % 2 for j in xrange(l)]
#This converts it to integers, then xor it.

Hope this helps!



来源:https://stackoverflow.com/questions/19489283/xor-two-blocks-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!