Sorting It Out

A solution to Sorting It Out kata described at CodeKata.

Solution

""" sorting_it_out.py """


class Rack():
    """ simulate lotto """
    def __init__(self, size=60):
        self.size = size
        self.drawn = [False for _ in range(self.size)]

    def add(self, ball):
        """ add drawn ball """
        self.drawn[ball] = True

    def balls(self):
        """ output a Rack """
        return [i for i in range(self.size) if self.drawn[i]]


def sorted_characters(text):
    """ convert text to sorted lowercase characters """
    frequency = [0 for _ in range(26)]
    for character in text:
        i = character.lower()
        if 'a' <= i <= 'z':
            frequency[ord(i) - ord('a')] += 1
    output = [j * chr(i + ord('a')) for i, j in enumerate(frequency) if j != 0]
    return ''.join(output)


if __name__ == '__main__':

    rack = Rack()

    assert rack.balls() == []
    rack.add(20)
    assert rack.balls() == [20]
    rack.add(10)
    assert rack.balls() == [10, 20]
    rack.add(30)
    assert rack.balls() == [10, 20, 30]

    words = 'When not studying nuclear physics, Bambi likes to play beach volleyball.'
    answer = 'aaaaabbbbcccdeeeeeghhhiiiiklllllllmnnnnooopprsssstttuuvwyyyy'
    assert sorted_characters(words) == answer

    print('tests passed')