3

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

georg
  • 211,518
  • 52
  • 313
  • 390
rana tamer
  • 59
  • 5

2 Answers2

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.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • could you please tell me what if __name__ == '__main__': means ?? – rana tamer Oct 21 '13 at 08:29
  • @ranatamer Well, its like a `main` function in C++. Basically, if python is running the current file, then the `__name__` of the file becomes `__main__`. In this example, you really don't need to use it, you can just type in `XorBlock("12345", "23456")`, and it will work just fine. – Games Brainiac Oct 21 '13 at 08:31
  • @ranatamer Take a look at [this](http://stackoverflow.com/questions/419163/what-does-if-name-main-do). It explains it better than I did. – Games Brainiac Oct 21 '13 at 08:33
0

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!

aIKid
  • 26,968
  • 4
  • 39
  • 65