문제

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 0s 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!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top