Skip to content

Instantly share code, notes, and snippets.

@mreid
Created October 29, 2013 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mreid/7207161 to your computer and use it in GitHub Desktop.
Save mreid/7207161 to your computer and use it in GitHub Desktop.
A simple noisy channel that flips a single bit in a block of N with probability P.
# A command-line noisy channel
#
# USAGE: python channel.py BLOCK_SIZE FLIP_PROBABILITY
#
# EXAMPLE:
# $ echo "0000000" | python channel.py 7 0.8
# 0000100
#
# AUTHOR: Mark Reid <mark.reid@anu.edu.au>
# CREATED: 2013-10-21
import sys
import random
def flip(c):
"""Return 0 if given character c is 1 and return 1 if c is 0"""
if c == "0":
return "1"
elif c == "1":
return "0"
else:
print("ERROR: Not a bit!")
def corrupt(s,k,p):
"""For each block of k bits, flip a single bit in k with probability p"""
while len(s) > 0:
chunk = list(s[0:k])
if p > random.random():
i = random.randint(0,len(chunk)-1)
chunk[i] = flip(chunk[i])
sys.stdout.write(''.join(chunk))
s = s[k:]
if __name__ == "__main__":
if len(sys.argv) < 2:
print("USAGE: python channel.py BLOCK_SIZE FLIP_PROBABILITY")
else:
p = float(sys.argv.pop())
k = int(sys.argv.pop())
input_string = sys.stdin.read().strip()
corrupt(input_string,k,p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment