我有一段代码:
#!/usr/bin/python3
from bitstring import BitArray
import itertools
# Helper functions
def get_bitset_by_letter(letter, encoding):
return encoding[letter] if letter in encoding else None
def get_letter_by_bitset(bitset, encoding):
for letter, encoding_bitset in encoding.items():
if bitset == encoding_bitset:
return letter
return None
class Word():
def __init__(self, word, encoding):
self.encoding = encoding
self.as_word = ''
self.as_bits = []
if isinstance(word, str):
self.as_word = word
self._encode_to_bits()
elif all(isinstance(i, BitArray) for i in word):
self.as_bits = word
self._decode_to_word()
else:
raise('class Word: Unexpected type of word arg')
def __ixor__(self, other):
for index, bitset in enumerate(other.as_bits):
print('In XOR: %d-%s-%s' % (index, self.as_bits[index], bitset))
self.as_bits[index] ^= bitset
return self
def as_bits(self):
return self.as_bits
def as_word(self):
return self.as_word
def _encode_to_bits(self):
for letter in self.as_word:
bitset = get_bitset_by_letter(letter, self.encoding)
if bitset is None:
raise('Can not find bitset by given letter %s in encoding.' % str(letter))
else:
self.as_bits.append(bitset)
def _decode_to_word(self):
for bitset in self.as_bits:
letter = get_letter_by_bitset(bitset, self.encoding)
if letter is None:
raise('Can not find letter by given bitset %s in encoding.' % str(bitset))
else:
self.as_word += letter
def main():
encoding = {
'A': BitArray(bin='000'),
'B': BitArray(bin='001'),
'C': BitArray(bin='010'),
'D': BitArray(bin='011'),
'E': BitArray(bin='100'),
'F': BitArray(bin='101'),
'G': BitArray(bin='110'),
'H': BitArray(bin='111'),
}
print(encoding)
print()
word_1 = Word('ABCHE', encoding)
print('word_1 = %s' % word_1.as_bits)
word_2 = Word('FGDEA', encoding)
print('word_2 = %s' % word_2.as_bits)
word_1 ^= word_2
print(word_1.as_bits)
if __name__ == '__main__':
main()
详细信息:我使用bitstring.BitArray
类将字母表示为三位的集合并以这种方式编码字(某种家庭任务)。另外,我的代码应该能够对这个词进行异或。问题:列表的每个最后一个元素other.as_bits
在到达功能时都有不正确的值。如果我评论该行
#self.as_bits[index] ^= bitset
的最后一个值other.as_bits
是正确的。我究竟做错了什么?
这是输出(python 3.5.2):
{'C': BitArray('0b010'), 'B': BitArray('0b001'), 'G': BitArray('0b110'),
'F': BitArray('0b101'), 'A': BitArray('0b000'), 'H': BitArray('0b111'),
'D': BitArray('0b011'), 'E': BitArray('0b100')}
word_1 = [BitArray('0b000'), BitArray('0b001'), BitArray('0b010'), BitArray('0b111'), BitArray('0b100')]
word_2 = [BitArray('0b101'), BitArray('0b110'), BitArray('0b011'), BitArray('0b100'), BitArray('0b000')]
In XOR: 0-0b000-0b101
In XOR: 1-0b001-0b110
In XOR: 2-0b010-0b011
In XOR: 3-0b111-0b100
In XOR: 4-0b100-0b101
[BitArray('0b101'), BitArray('0b111'), BitArray('0b001'), BitArray('0b011'), BitArray('0b001')]
从这里你可以看到,in 的最后第四个元素word_2
是__ixor__
,0b101
应该是0b000
谢谢!