codeeval_challenges / 038_StringList /

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

        >>> generate_permutations(['a'], 1)
        >>> 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)


if __name__ == "__main__":
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.