简体   繁体   中英

XOR two blocks in python

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

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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