handshake.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from functools import reduce

OPS = (
    ('wink', 0b1),
    ('double blink', 0b10),
    ('close your eyes', 0b100),
    ('jump', 0b1000),
)

REVERSE = 0b10000


def handshake(n):
    """Encode sequence of events into a binary code"""
    if isinstance(n, str):
        # Convert binary string to int
        try:
            n = int(n, 2)
        except ValueError:
            n = 0
    n = max(n, 0)

    # Encode operations
    ops = [
        op
        for op, code in OPS
        if n & code
    ]

    return list(reversed(ops)) if n & REVERSE else ops


def code(ops):
    """Decode binary code into sequence of events"""
    op_lookup = dict(OPS)
    try:
        codes = [op_lookup[op] for op in ops]
    except KeyError:
        codes = [0]

    code = reduce(lambda c, op: c | op, codes)

    # Detect reverse order of operations
    if len(codes) > 1 and codes[0] > codes[1]:
        code |= REVERSE

    return bin(code)[2:]

Comments


You're not logged in right now. Please login via GitHub to comment