# Demo by Theo Varvadoukas, s1265135
'''
Description
------------
Implementation of the Sardinas-Patterson algorithm.
This algorithm is used to determine in polynomial time whether
a given variable-length code is uniquely decodable.
http://e...content-available-to-author-only...a.org/wiki/Sardinas-Patterson_algorithm
Input
-----
The core function is `uniqdecod`. It accepts a set of
codewords and each codeword must be a string.
E.g.
ExampleUnique = set(['0', '10', '110', '111'])
print uniqdecod(ExampleUnique)
Output
-------
True in case it is uniquely decodable or
False otherwise.
Further notes
--------------
For a complete example of use check the main() function.
'''
def removeprefix(prefix, S):
''' Remove prefix from S.'''
return S[len(prefix):]
def findprefix(prefix, L):
''' Return the dangling suffixes of each matching string.'''
dangling = []
for l in L:
if l.startswith(prefix):
dangling.append(removeprefix(prefix, l))
return set(dangling)
def crossprefix(L1, L2):
''' Return the dangling suffixes between 2 lists. '''
L1L2 = set()
for l1 in L1:
L1L2 |= findprefix(l1, L2)
L2L1 = set()
for l2 in L2:
L2L1 |= findprefix(l2, L1)
return L1L2 | L2L1
def uniqdecod(codewords):
# Only for the first iteration.
# Find the dangling suffixes between the first
# set and the codeword.
C = {}
C[0] = set()
for c in codewords:
C[0] |= findprefix(c, codewords - set([c]))
i = 1
while True:
C[i] = crossprefix(C[i-1],codewords)
#print i, C[i] # print each set if you wish.
if '' in C[i]:
return False
# Check if C[i] is equal with any other previous set.
# If yes, the code is uniquely decodable.
for j in range(0,i):
if C[j] == C[i]:
return True
i = i + 1
def main():
# ----------------
# Examples of use
# ----------------
ExampleNonUnique = set(['01', '01111', '111110'])
ExampleUnique = set(['0', '10', '110', '111'])
mycode = ExampleNonUnique
decodable = uniqdecod(mycode)
if decodable:
print("Wow congratulations! The code IS decodable!")
else:
print("Damn.. the code is NOT decodable!")
if __name__ == '__main__':
main()# your code goes here