简体   繁体   English

在Python中对两个块进行异或

[英]XOR two blocks in python

i am new to programming in python...i want to make XOR between 2 blocks here is my code 我是python编程的新手...我想在2个块之间进行XOR,这是我的代码

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 所以请任何人帮助我这段代码中的错误在哪里..提前谢谢

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 0 s before any digits of value. 我决定最好将两个参数都保留为字符串,因为在二进制中,您可能必须在值的任何数字前加上0 s。

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. 简而言之,python将您的%2视为字符串格式命令。

"string"%something

will expect the string to specify where it should format something . 将期望字符串指定应该格式化something If it doesn't specify anything, the current TypeError will be raised. 如果未指定任何内容,则将TypeError当前的TypeError 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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM