Пример #1
0
def dec_to_unary(num):
    """Tally representation e.g. | = 1, / = 5"""
    result = ''
    rounds = num // 5
    fives = 1
    if rounds < 5:
        result = '|' * num
    else:
        for round in range(0, rounds + 1):
            # Reset tally "five" marker every time it gets to five.
            if fives == 5:
                result += '/'
                fives = 0
            else:
                result += '|'
            fives += 1
    print_h4('Base 1', desc='aka "tally"')
    print('{} base 1 = {}'.format(num, result))
Пример #2
0
def dec_to_unary(num):
    """Tally representation e.g. | = 1, / = 5"""
    result = ''
    rounds = num // 5
    fives = 1
    if rounds < 5:
        result = '|' * num
    else:
        for round in range(0, rounds + 1):
            # Reset tally "five" marker every time it gets to five.
            if fives == 5:
                result += '/'
                fives = 0
            else:
                result += '|'
            fives += 1
    print_h4('Base 1', desc='aka "tally"')
    print('{} base 1 = {}'.format(num, result))
Пример #3
0
    return a**a


def g(b):
    return b * 2


def f_g(a, b, arg):
    return a(b(arg))


if DEBUG:
    with Section('Category Theory basics'):
        """Challenge ideas taken from bartoszmilewski.com/2014/11/04
            /category-the-essence-of-composition/ "Challenges" section."""
        print_h4('Identity function')
        for thing in ['cat', 1, 'dog', 2, range(0, 3), 0.03]:
            assert thing == id(thing)
            print(thing, id(thing))
        print_h4('Function composition')
        res = compose_hybrid('composition is neat!', f=dictify, g=listify)
        print(res)
        print_h4('Random funcs')
        print(listify('foo'))
        print(dictify('foo'))

        print_h4('Higher order function composition')
        f2 = compose_hybrid_hof(f=listify, g=dictify)
        print(f2('composition yay!'))

        print_h4('Function composition on a "stream" or incoming set')
Пример #4
0
        binval = encoders.dec_to_bin(int(digit))
        binval = BaseDataType.add(str(binval), bias)
        binary += '{}{}'.format(binval, ' ' * (4 - len(binval) + 1))
        if len(binval) < 4:
            binval = binval.zfill(4)
        bcd += '{} '.format(binval)
        decimals += digit + (' ' * 4)
    _show_bcd(num, decimals, binary, bcd)
    return bcd


if DEBUG:
    with Section('Numerical encoding: Binary Coded Decimal (BCD)'):
        """More exist, but are not covered here.
        See books.google.com/books?id=0f-6diYBV0wC&lpg
            =PA48&ots=jG6NiHY3he&dq=bcd%207421&pg
            =PA51#v=onepage&q=bcd%207421&f=false For more examples."""

        print('D = Decimal, B = Binary, C = Binary Coded Decimal')
        nums = [
            1, 2, 4, 16, 32, 64, 128, 256, 512, 1024, 2048, 1234, 12345,
            123456, 1234567, 12345678, 123456789
        ]
        print_h4('BCD', desc='8421 encoding')
        for num in nums:
            dec_to_bcd_8421(num)

        print_h4('BCD', desc='Excess-3 (bias) encoding')
        for num in nums:
            dec_to_bcd_excess3(num)
Пример #5
0
@trials._test_speed
def trial_exp(func, max=10):
    print('Testing function: "{}"'.format(func.__name__))
    rounds = []
    for x in range(max):
        round = []
        for n in range(max):
            round.append(func(x, n))
        rounds.append(round)
    ppr(rounds)
    return rounds


def test_matrix_with_exp(matrix):
    """Test the exponentiation function with a bonafide matrix."""
    ppr(matrix)
    for row in matrix:
        for k in row:
            print(k, exp_by_squaring(k, 2))


if DEBUG:
    with Section('Matrix Processing algorithms'):
        print_h4('Trials with different squaring functions')
        res = trial_exp(exp_by_squaring)
        res2 = trial_exp(exp_by_convential)
        assert res == res2

        print_h4('Trials with squaring function on matrices')
        test_matrix_with_exp(random_matrix(rows=3, columns=3))
Пример #6
0
                result += '|'
            fives += 1
    print_h4('Base 1', desc='aka "tally"')
    print('{} base 1 = {}'.format(num, result))


if DEBUG:
    with Section('Numerical encoding: "N-ary" (positional) - extended'):
        """I thought I had the extent of the positional number systems,
        but much more exist, and many can be found at:
        http://www.calculand.com/unit-converter/zahlen.php"""

        print_h2('N to Decimal',
                 desc='Conversion to decimal from a given base')

        for n in range(4):
            print_h4('Convert base {}'.format(n))
            n_to_dec(999, n)

        print_h2(
            'Decimal to N',
            desc='Conversion of numbers to any base with divide-by technique.')

        for base_info in BASES:
            base, title = base_info['base'], base_info['name']
            print_h4('Base {}'.format(base), desc='aka "{}"'.format(title))
            test_base(base_info)

        for num in [4, 256, 512]:
            dec_to_unary(num)
Пример #7
0
                'edges': [],
                'parent': 1
            },
            4: {
                'edges': [],
                'parent': 2
            },
            5: {
                'edges': [],
                'parent': 2
            },
        }
        btree = BinaryTree(data)
        print(btree)

        print_h4('Binary trees',
                 desc=('They can have no more than two nodes, '
                       'so adding new edges that do not conform'
                       ' should throw an error.'))
        try:
            btree[6] = {'edges': [7, 8, 9], 'parent': 3}
        except InvalidChildNodeCount:
            cmd_title('Error called successfully', newlines=False)

        bst = NaiveBinarySearchTree(data)
        print(bst)

        bst.add_child(5, 6)
        bst.add_siblings(5, [10, 11])
        print(bst)
Пример #8
0
if DEBUG:
    with Section('Set Abstract Data Type'):
        set_adt = SetADT()
        frozen_set_adt = FrozenSetADT([1, 2, 3, 4, True, False, 'A', 'B', 'C'])

        for n in range(6):
            set_adt[n] = rr(0, 10)
            set_adt[n] = ''.join(randchars(1))
            set_adt[n] = choice([True, False])
            try:
                frozen_set_adt[n] = rr(0, 10)
            except ImmutableSetError:
                print('Frozen set cannot be modified after creation.')

        print_h4('Set/Frozen set items', '')
        ppr(set_adt.items)
        ppr(frozen_set_adt.items)

        dynam_set = DynamicSet.create([1, 2, 3, 4], capacity=4)
        print('Capacity', dynam_set.set_capacity(4))
        print('Room left', dynam_set.room_left())
        dynam_set.add(range(100))

        print_h4('Multiset example', 'Allowing multiple items of the same')
        multiset = MultiSet()
        multiset['cat'] = {'name': 'lily', 'type': 'persian'}
        multiset['cat'] = {'name': 'radical', 'type': 'calico', 'age': 23}
        multiset['cat'] = {'name': 'jadore', 'type': 'siamese'}
        multiset['cat'] = {'name': 'tutu', 'type': 'abyssinian'}
Пример #9
0
        super(Word, self).__init__(value)


def update_animation(steps, func, instance):
    for _ in range(steps):
        sleep(0.05)
        instance.value = func(instance.value)


bin_inc = BaseDataType.increment
bin_dec = BaseDataType.decrement


if __name__ == '__main__':
    with Section('Computer organization - Data types'):
        print_h4('Bit', desc='The simplest unit of information.')
        bit = Bit('0')
        assert bit.get_max_binvals() == 2

        print_h3('Nibble', desc='4 bits = 1/2 byte.')
        nibble = Nibble('0000')
        print(nibble)
        assert nibble.get_max_binvals() == 24

        print_h3('Byte', desc='8 bits = one byte.')
        byte = Byte('00000000')
        print(byte)
        assert byte.get_max_binvals() == 40320

        orig = byte.value
        # Flip bits then reverse and check the value to test things
Пример #10
0
        tdpl.test_grammar(5, '1', **kwargs)
        wikipedia_kwargs = {
            'ruleset': {
                'S': 'AS/T',
                'T': 'BS/E',
                'A': 'a',
                'B': 'b',
                'E': '',  # Epsilon string
            }
        }
        tdpl.test_grammar(10, 'S', **wikipedia_kwargs)

        # NOTE: For simplicity, slashes are not implemented as fallbacks,
        # as seen in the example.
        for left, right in wikipedia_kwargs['ruleset'].iteritems():
            print_h4('Testing wikipedia example '
                     'with starting rule: {}'.format(left))
            tdpl.test_grammar(10, left, **wikipedia_kwargs)

        wikipedia_kwargs2 = {
            'ruleset': {
                'S': 'OT/E',
                'T': 'SU/F',
                'U': 'CS/F',
                'O': '{',
                'C': '}',
                'E': '',  # Epsilon string
                'F': 'f',
            }
        }
        for left, right in wikipedia_kwargs2['ruleset'].iteritems():
            print_h4('Testing wikipedia example 2 '
Пример #11
0
        """
        data = {
            0: {"edges": [1, 2], "is_root": True},
            1: {"edges": [3], "parent": 0},
            2: {"edges": [4, 5], "parent": 0},
            3: {"edges": [], "parent": 1},
            4: {"edges": [], "parent": 2},
            5: {"edges": [], "parent": 2},
        }
        btree = BinaryTree(data)
        print(btree)

        print_h4(
            "Binary trees",
            desc=(
                "They can have no more than two nodes, "
                "so adding new edges that do not conform"
                " should throw an error."
            ),
        )
        try:
            btree[6] = {"edges": [7, 8, 9], "parent": 3}
        except InvalidChildNodeCount:
            cmd_title("Error called successfully", newlines=False)

        bst = NaiveBinarySearchTree(data)
        print(bst)

        bst.add_child(5, 6)
        bst.add_siblings(5, [10, 11])
        print(bst)
Пример #12
0
    """A visualization of the powers of ten technique for a given `num`"""
    value = 0
    digits = list(reversed(unicode(num)))
    places = len(digits)
    values = []
    mapping = {}
    for index in reversed(range(places)):
        place_index = '1{}'.format('0' * index)
        place = int(digits[index]) * int(place_index)
        value += place
        values.append(place)
        mapping[place] = (int(digits[index]), int(place_index))
        print('{} * {} = {}'.format(digits[index], place_index, place, value))
    print('{} = {}'.format(' + '.join(map(unicode, values)), num))
    print('\n')
    return mapping


if DEBUG:
    with Section('Computer organization - Numerical encoding'):
        groups = {
            'General': genr,
            'Hexadecimal': hexa,
            'Octal': octa,
            'Binary': bina,
            'Decimal': deca,
        }
        for title, func in groups.iteritems():
            print_h4(title, desc='The {} encoding scheme.'.format(title))
            func()
Пример #13
0
        tdpl.test_grammar(5, '1', **kwargs)
        wikipedia_kwargs = {
            'ruleset': {
                'S': 'AS/T',
                'T': 'BS/E',
                'A': 'a',
                'B': 'b',
                'E': '',  # Epsilon string
            }
        }
        tdpl.test_grammar(10, 'S', **wikipedia_kwargs)

        # NOTE: For simplicity, slashes are not implemented as fallbacks,
        # as seen in the example.
        for left, right in wikipedia_kwargs['ruleset'].iteritems():
            print_h4('Testing wikipedia example '
                     'with starting rule: {}'.format(left))
            tdpl.test_grammar(10, left, **wikipedia_kwargs)

        wikipedia_kwargs2 = {
            'ruleset': {
                'S': 'OT/E',
                'T': 'SU/F',
                'U': 'CS/F',
                'O': '{',
                'C': '}',
                'E': '',  # Epsilon string
                'F': 'f',
            }
        }
        for left, right in wikipedia_kwargs2['ruleset'].iteritems():
            print_h4('Testing wikipedia example 2 '
Пример #14
0
    return a ** a


def g(b):
    return b * 2


def f_g(a, b, arg):
    return a(b(arg))


if DEBUG:
    with Section('Category Theory basics'):
        """Challenge ideas taken from bartoszmilewski.com/2014/11/04
            /category-the-essence-of-composition/ "Challenges" section."""
        print_h4('Identity function')
        for thing in ['cat', 1, 'dog', 2, range(0, 3), 0.03]:
            assert thing == id(thing)
            print(thing, id(thing))
        print_h4('Function composition')
        res = compose_hybrid('composition is neat!', f=dictify, g=listify)
        print(res)
        print_h4('Random funcs')
        print(listify('foo'))
        print(dictify('foo'))

        print_h4('Higher order function composition')
        f2 = compose_hybrid_hof(f=listify, g=dictify)
        print(f2('composition yay!'))

        print_h4('Function composition on a "stream" or incoming set')
Пример #15
0
@trials.test_speed
def trial_exp(func, max=10):
    print('Testing function: "{}"'.format(func.__name__))
    rounds = []
    for x in range(max):
        round = []
        for n in range(max):
            round.append(func(x, n))
        rounds.append(round)
    ppr(rounds)
    return rounds


def test_matrix_with_exp(matrix):
    """Test the exponentiation function with a bonafide matrix."""
    ppr(matrix)
    for row in matrix:
        for k in row:
            print(k, exp_by_squaring(k, 2))


if DEBUG:
    with Section('Matrix Processing algorithms'):
        print_h4('Trials with different squaring functions')
        res = trial_exp(exp_by_squaring)
        res2 = trial_exp(exp_by_convential)
        assert res == res2

        print_h4('Trials with squaring function on matrices')
        test_matrix_with_exp(random_matrix(rows=3, columns=3))
Пример #16
0
                result += '|'
            fives += 1
    print_h4('Base 1', desc='aka "tally"')
    print('{} base 1 = {}'.format(num, result))


if DEBUG:
    with Section('Numerical encoding: "N-ary" (positional) - extended'):

        """I thought I had the extent of the positional number systems,
        but much more exist, and many can be found at:
        http://www.calculand.com/unit-converter/zahlen.php"""

        print_h2('N to Decimal', desc='Conversion to decimal from a given base')

        for n in range(4):
            print_h4('Convert base {}'.format(n))
            n_to_dec(999, n)

        print_h2(
            'Decimal to N',
            desc='Conversion of numbers to any base with divide-by technique.')

        for base_info in BASES:
            base, title = base_info['base'], base_info['name']
            print_h4('Base {}'.format(base), desc='aka "{}"'.format(title))
            test_base(base_info)

        for num in [4, 256, 512]:
            dec_to_unary(num)
Пример #17
0
    for digit in str(num):
        binval = encoders.dec_to_bin(int(digit))
        binval = BaseDataType.add(str(binval), bias)
        binary += '{}{}'.format(binval, ' ' * (4 - len(binval) + 1))
        if len(binval) < 4:
            binval = binval.zfill(4)
        bcd += '{} '.format(binval)
        decimals += digit + (' ' * 4)
    _show_bcd(num, decimals, binary, bcd)
    return bcd


if DEBUG:
    with Section('Numerical encoding: Binary Coded Decimal (BCD)'):
        """More exist, but are not covered here.
        See books.google.com/books?id=0f-6diYBV0wC&lpg
            =PA48&ots=jG6NiHY3he&dq=bcd%207421&pg
            =PA51#v=onepage&q=bcd%207421&f=false For more examples."""

        print('D = Decimal, B = Binary, C = Binary Coded Decimal')
        nums = [
            1, 2, 4, 16, 32, 64, 128, 256, 512, 1024, 2048, 1234,
            12345, 123456, 1234567, 12345678, 123456789]
        print_h4('BCD', desc='8421 encoding')
        for num in nums:
            dec_to_bcd_8421(num)

        print_h4('BCD', desc='Excess-3 (bias) encoding')
        for num in nums:
            dec_to_bcd_excess3(num)
Пример #18
0
    """A visualization of the powers of ten technique for a given `num`"""
    value = 0
    digits = list(reversed(unicode(num)))
    places = len(digits)
    values = []
    mapping = {}
    for index in reversed(range(places)):
        place_index = '1{}'.format('0' * index)
        place = int(digits[index]) * int(place_index)
        value += place
        values.append(place)
        mapping[place] = (int(digits[index]), int(place_index))
        print('{} * {} = {}'.format(digits[index], place_index, place, value))
    print('{} = {}'.format(' + '.join(map(unicode, values)), num))
    print('\n')
    return mapping


if DEBUG:
    with Section('Computer organization - Numerical encoding'):
        groups = {
            'General': genr,
            'Hexadecimal': hexa,
            'Octal': octa,
            'Binary': bina,
            'Decimal': deca,
        }
        for title, func in groups.iteritems():
            print_h4(title, desc='The {} encoding scheme.'.format(title))
            func()