Read the checking program (79 lines of Python)
"""Check an exact constant-GC codebook and its specified Hamming constraints."""
from itertools import combinations
import json
import sys
LENGTH = 6
GC = LENGTH // 2
DISTANCE = 3
REVERSE_COMPLEMENT = True
MAX_WORDS = 128
MAX_BYTES = MAX_WORDS * (LENGTH + 2)
ALPHABET = b'ACGT'
COMPLEMENT = bytes.maketrans(b'ACGT', b'TGCA')
LOW_BITS = sum(1 << (2 * index) for index in range(LENGTH))
def encode(word):
result = 0
for letter in word:
result = (result << 2) | ALPHABET.index(letter)
return result
def distance(left, right):
# Each mismatching two-bit base contributes one low bit.
difference = left ^ right
return ((difference | (difference >> 1)) & LOW_BITS).bit_count()
def verify(data):
if len(data) > MAX_BYTES:
raise ValueError('The submission exceeds the byte limit.')
lines = data.splitlines()
if not 1 <= len(lines) <= MAX_WORDS:
raise ValueError('Submit a nonempty codebook within the word limit.')
words = []
seen = set()
for word in lines:
if len(word) != LENGTH or any(letter not in ALPHABET for letter in word):
raise ValueError(f'Each row must contain exactly {LENGTH} letters from A, C, G and T.')
if word.count(b'C') + word.count(b'G') != GC:
raise ValueError(f'Each codeword must contain exactly {GC} G or C letters.')
if word in seen:
raise ValueError('The same codeword appears more than once.')
seen.add(word)
key = encode(word)
if REVERSE_COMPLEMENT:
rc = encode(word.translate(COMPLEMENT)[::-1])
if distance(key, rc) < DISTANCE:
raise ValueError('A word is too close to its own reverse complement.')
else:
rc = None
if any(a == b for a, b in zip(word, word[1:])):
raise ValueError('Adjacent letters in a word must differ.')
words.append((key, rc))
for (left, _), (right, rc) in combinations(words, 2):
if distance(left, right) < DISTANCE:
raise ValueError('Two codewords are too close in Hamming distance.')
# Hamming distance is invariant under simultaneous reverse complementation.
if REVERSE_COMPLEMENT and distance(left, rc) < DISTANCE:
raise ValueError('A codeword is too close to another word’s reverse complement.')
return len(words)
def main():
try:
score = verify(sys.stdin.buffer.read(MAX_BYTES + 1))
except ValueError as error:
result = {'valid': False, 'score': None, 'message': str(error)}
else:
result = {'valid': True, 'score': score, 'message': 'The codebook is valid.'}
print(json.dumps(result))
if __name__ == '__main__':
main()