Source

codeeval_challenges / 038_StringList / string_list.py

#! /usr/bin/env python
""" This module provides a function to generate ALL permutations according to
    a given alphabet and a length for the permutations.

    Examples:
        >>> generate_permutations(['a'], 1)
        ['a']
        >>> generate_permutations(['p', 'o'], 2)
        ['oo', 'op', 'po', 'pp']
"""

import sys
from optparse import OptionParser

def generate_permutations(alphabet, length, bases=None):
    """ This function generates all permutations of the characters in 
        alphabet. A permuation can consist only of on character in the
        alphabet, e.g. 'aaa' for length 3. The size of permutation 
        strings is defined by length which has to be an integer. Bases 
        is a list of generated permutations as that passed in recursive 
        calls of the method. 

        Returns a list of permutation strings of length.
    """
    if bases is None:
        bases = alphabet 

    if length == 1:
        return sorted(bases)

    new_bases = []
    for char in alphabet:
        for base in bases:
            new_bases.append(base + char)

    return generate_permutations(alphabet, length-1, new_bases)

def main():

    parser = OptionParser('%s testcase.txt' % __file__)
    options, args = parser.parse_args()

    if len(args) < 1:
        parser.error("No input file provided.")

    test_cases = open(sys.argv[1], 'r')

    for test in test_cases:
        test = test.strip()

        if test != '':
            length, chars = test.split(',')
            length = int(length)
            chars = set(chars)

            permutations = generate_permutations(chars, length)
            print ",".join(permutations)

    test_cases.close()


if __name__ == "__main__":
    main()