# codeeval_challenges / 038_StringList / string_list.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65``` ```#! /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() ```