Skip to content

Instantly share code, notes, and snippets.

@ayumi
Created October 7, 2011 02:28
Show Gist options
  • Save ayumi/1269295 to your computer and use it in GitHub Desktop.
Save ayumi/1269295 to your computer and use it in GitHub Desktop.
new communication protocol checker for jesse farmer!
#-------------------------------------------------------------------------------
# new communication protocol checker for jesse farmer!
#
# Author: ayumi yu
# Created: 06.10.2011
# Last mod: 08.10.2011
# Licence: MIT
#-------------------------------------------------------------------------------
#!/usr/bin/env python
# ** imports and stuff
import string
# ** FUNctions
def checkValid( message ):
"""
Check if a message is valid according to the protocol.
The message is assumed to have only the 15 valid characters (a-j, ZMKPQ)
"""
# > Invalidation
# Rightmost char must be a-j; they're the only independently valid messages
if message[ len(message)-1: ] not in list(string.ascii_lowercase[:10]):
return False
# Second to last char cannot be KMPQ, that requires at least 2 more chars after
elif message[ len(message)-2 : len(message)-1] in ['K','M','P','Q']:
return False
# > Validation
# Single characters a-j are valid
elif message in list(string.ascii_lowercase[:10]):
return True
# If Zxx then check if the xx is a valid message
elif message[:1] == 'Z' and len(message) >= 2 and checkValid(message[1:]):
return True
# If Myy/Kyy/Pyy/Qyy check if yy can be split into 2 valid messages
elif message[:1] in ['K','M','P','Q'] and len(message) >= 3:
# Divide in 2, in all possible ways and check the pairs
for x in range(2, len(message)):
if checkValid( message[1:x] ) and checkValid(message[x:]):
return True
# > Failed to validate. Return invalid by default
else:
return False
# Logic begins!
testInput = raw_input("Input, please! ")
# Go through each message split by whitespace
for message in testInput.split():
result = 'VALID' if checkValid(message) else 'INVALID'
print "%s %s" % ( message, result )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment