2

我是 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)];

但是当我打电话时它给了我

TypeError: not all arguments converted during string formatting

所以请任何人帮助我这个代码中的错误在哪里..提前谢谢

4

2 回答 2

0

这部分错了,看一下:

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

这两个项目都是字符串,因此,结果是一个字符串。简而言之,python 将您%2视为字符串格式化命令。

"string"%something

将期望字符串指定它应该格式化的位置something。如果它没有指定任何东西,电流TypeError将被提高。你可能需要的是这样的:

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

希望这可以帮助!

于 2013-10-21T09:27:25.993 回答
0

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.

于 2013-10-21T08:21:45.840 回答