#!/usr/bin/env python """ Copyright (C) 2012 Bo Zhu http://about.bozhu.me Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ def Berlekamp_Massey_algorithm(sequence): N = len(sequence) s = sequence[:] for k in range(N): if s[k] == 1: break f = set([k + 1, 0]) # use a set to denote polynomial l = k + 1 g = set([0]) a = k b = 0 for n in range(k + 1, N): d = 0 for ele in f: d ^= s[ele + n - l] if d == 0: b += 1 else: if 2 * l > n: f ^= set([a - b + ele for ele in g]) b += 1 else: temp = f.copy() f = set([b - a + ele for ele in f]) ^ g l = n + 1 - l g = temp a = b b = n - l + 1 # output the polynomial def print_poly(polynomial): result = '' lis = sorted(polynomial, reverse=True) for i in lis: if i == 0: result += '1' else: result += 'x^%s' % str(i) if i != lis[-1]: result += ' + ' return result return (print_poly(f), l) if __name__ == '__main__': seq = (0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0) (poly, span) = Berlekamp_Massey_algorithm(seq) print 'The input sequence is %s.' % str(seq) print 'Its characteristic polynomial is (%s),' % poly, print 'and linear span is %d.' % span