fork download
  1. from operator import xor
  2. from functools import reduce
  3.  
  4. class LFSR(object):
  5. def __init__(self, taps, func, init):
  6. self.func = func
  7. self.state = int(init, 2)
  8. self.width = len(init)
  9. self.taps = [self.width - t - 1 for t in taps]
  10.  
  11. def _bit(self, b):
  12. return (self.state & 1 << b) >> b
  13.  
  14. def step(self):
  15. shift = reduce(self.func, (self._bit(t) for t in self.taps)) & 1
  16. self.state >>= 1
  17. if shift:
  18. self.state |= 1 << (self.width - 1)
  19.  
  20. def __str__(self):
  21. return '{:0{}b}'.format(self.state, self.width)
  22.  
  23. def xnor(a, b):
  24. return ~xor(a, b)
  25.  
  26. def run(challenge):
  27. taps, func, start, count = challenge.split()
  28. taps = list(map(int, taps[1:-1].split(',')))
  29. func = xor if func == 'XOR' else xnor
  30. count = int(count)
  31.  
  32. reg = LFSR(taps, func, start)
  33. print(0, reg)
  34. for i in range(1, count + 1):
  35. reg.step()
  36. print(i, reg)
  37.  
  38. if __name__ == '__main__':
  39. for challenge in ['[1,2] XOR 001 7',
  40. '[0,2] XNOR 001 7',
  41. '[1,2,3,7] XOR 00000001 16',
  42. '[1,5,6,31] XOR 00000000000000000000000000000001 16']:
  43. run(challenge)
  44. print()
Success #stdin #stdout 0.03s 9548KB
stdin
Standard input is empty
stdout
0 001
1 100
2 010
3 101
4 110
5 111
6 011
7 001

0 001
1 000
2 100
3 010
4 101
5 110
6 011
7 001

0 00000001
1 10000000
2 01000000
3 10100000
4 11010000
5 01101000
6 00110100
7 00011010
8 10001101
9 11000110
10 11100011
11 11110001
12 01111000
13 10111100
14 01011110
15 00101111
16 00010111

0 00000000000000000000000000000001
1 10000000000000000000000000000000
2 01000000000000000000000000000000
3 10100000000000000000000000000000
4 01010000000000000000000000000000
5 10101000000000000000000000000000
6 01010100000000000000000000000000
7 00101010000000000000000000000000
8 10010101000000000000000000000000
9 11001010100000000000000000000000
10 01100101010000000000000000000000
11 00110010101000000000000000000000
12 10011001010100000000000000000000
13 01001100101010000000000000000000
14 00100110010101000000000000000000
15 00010011001010100000000000000000
16 10001001100101010000000000000000