def compress(s):
    parser = fold(
        shorter(
            map(
                repeat_first(read_any_char), lambda x: f"{x[1]}<{x[0]}>"
                if x[1] not in "<\\" else x[1] * x[0])), lambda a, b: a +
        (b if b != '<' else "\\<"), "")
    return parser(s)[1]
Beispiel #2
0
def hex_string_to_RGB(hex_string):
    read_byte = map(
        seq(
            read_hex_digit,
            read_hex_digit
        ),
        lambda x: x[0] * 16 + x[1]
    )
    parser = map(
        seq(
            read_str('#'),
            read_byte,
            read_byte,
            read_byte
        ),
        lambda x: {'r': x[1], 'g': x[2], 'b': x[3]}
    )
    return parser(hex_string)[1]
def decompress(s):
    parser = fold(
        either(
            map(
                seq_take([True, False, True, False], read_any_char,
                         read_str('<'), read_int, read_str('>')),
                lambda x: x[0] * x[1] if x[0] != '\\' else f"<{x[1]}>"),
            read_any_char), lambda a, b: a + b, "")
    return parser(s)[1]
Beispiel #4
0
def scientific(s):
    parser = map(num_parser, repr_to_exp("e"))
    return parser(s)[1]
Beispiel #5
0
def shorthand(s):
    parser = map(num_parser, repr_to_exp("*10^"))
    return parser(s)[1]
Beispiel #6
0
# python solution to
# https://www.codewars.com/kata/5282b48bb70058e4c4000fa7

from __init__ import read_any_char, map, read_str, seq

read_hex_digit = map(read_any_char, lambda x: int(x, 16))

def hex_string_to_RGB(hex_string):
    read_byte = map(
        seq(
            read_hex_digit,
            read_hex_digit
        ),
        lambda x: x[0] * 16 + x[1]
    )
    parser = map(
        seq(
            read_str('#'),
            read_byte,
            read_byte,
            read_byte
        ),
        lambda x: {'r': x[1], 'g': x[2], 'b': x[3]}
    )
    return parser(hex_string)[1]



import unittest

class HexToStringTests(unittest.TestCase):
Beispiel #7
0
# python solution to
# https://www.codewars.com/kata/5914e068f05d9a011e000054

from __init__ import read_any_char, map, repeat_first, fold

unpack_part = map(read_any_char, lambda x: x[1] * x[0])

def compress(s):
    parser = fold(repeat_first(read_any_char), lambda a, b: a + [b], [])
    return parser(s)[1]

def decompress(t):
    parser = fold(unpack_part, lambda a, b: a + b, "")
    return parser(t)[1]



import unittest

class CompressionTests(unittest.TestCase):
    def test_compress(self):
        self.assertEqual(
            compress("aaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac"),
            [[14, 'a'], [1, 'b'], [41, 'a'], [1, 'c']]
        )

    def test_decompress(self):
        self.assertEqual(
            decompress([[14, 'a'], [1, 'b'], [41, 'a'], [1, 'c']]),
            "aaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac"
        )