Skip to content

Instantly share code, notes, and snippets.

@ypxu
Last active June 20, 2016 06:58
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 ypxu/d2914e82686d73cef1cc32bd9306ec2b to your computer and use it in GitHub Desktop.
Save ypxu/d2914e82686d73cef1cc32bd9306ec2b to your computer and use it in GitHub Desktop.
Simple Text Protocol
# a - j, Z, M,K,P,Q
"""
Thoughts
Consider the message a tree, walk the message until we meet the valid
considition which there's no more charactors.
When we encouter a - j, we substract one from the message. When we see
Z, we look for next valid message, when we counter M,K,P,Q, we look
for two valid message.
"""
def is_valid(message):
return helper(message) == ""
def helper(message):
if message is None or len(message) == 0:
return False
first_char = message[0]
lower_charset = [chr(97 + i) for i in xrange(10)]
if first_char in lower_charset:
return message[1:]
if first_char == 'Z' and len(message) >= 2:
return helper(message[1:])
if first_char in ['M', 'K', 'P', 'Q'] and len(message) >= 3:
return helper(helper(message[1:]))
return message
VALID = True
INVALID = False
assert is_valid("Qa") == INVALID
assert is_valid("Zj") == VALID
assert is_valid("MZca") == VALID
assert is_valid("Khfa") == INVALID
assert is_valid('Ma') == INVALID
# We have decided to extend the protocol to accept an arbitrary number of valid messages.
# If a message begins with a number, precisely that number of valid messages must follow.
"""
Thoughts:
We will use the number to determine how many loop/valid message we will need to get.
in the helper we will have a loop to go through the number of valid message. It fails when
we don't have that many valid messages in the following.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment