Home > Net >  Python recursion systematic ordering
Python recursion systematic ordering

Time:01-27

I wrote my code and it's working perfectly but the output doesn't really look good. I was it to look more presentable/systematic. How do I do that? This is the kind of result I'm currently getting:

enter image description here

and this is the type of result I want:

enter image description here

This code is basically to find permutations of whatever is inputted.

def permutations(aSet):
  if len(aSet) <= 1: return aSet

  all_perms = []

  first_element = aSet[0:1]
  subset = aSet[1:]

  partial = permutations(subset)
  for permutation in partial:
    for index in range(len(aSet)):
      new_perm = list(permutation[:index])
      new_perm.extend(first_element)
      new_perm.extend(permutation[index:])
      all_perms.append(new_perm)

  return all_perms

I can't figure out what to try.

CodePudding user response:

You can sort the output array with a custom key function. Here keyFunc converts a permutaiton (list of characters) into a single string to perform lexicographic sorting.

from pprint import pprint

# insert your function here

def keyFunc(char_list):
  return ''.join(char_list)

chars = list('dog')
permutation = permutations(chars)
permutation.sort(key=keyFunc)

pprint(permutation)

Output:

[['d', 'g', 'o'],
 ['d', 'o', 'g'],
 ['g', 'd', 'o'],
 ['g', 'o', 'd'],
 ['o', 'd', 'g'],
 ['o', 'g', 'd']]

CodePudding user response:

Here's a way to order the permutations differently: for each item in the input array, take it out of the array, find all permutations of the remaining subarray, then prepend this item to each permutation of this subarray. This has the effect of placing permutations with similar prefixes together.

from pprint import pprint

def permutations2(chars):
    if len(chars) <= 1: return [chars]
    all_perms = []
    for idx, char in enumerate(chars):
        subarr = chars[:idx]   chars[idx 1:]
        subperms = permutations2(subarr)
        for subperm in subperms:
            new_perm = [char]   subperm
            all_perms.append(new_perm)
    return all_perms

chars = list('dog')
pprint(permutations2(chars))

Result:

[['d', 'o', 'g'],
 ['d', 'g', 'o'],
 ['o', 'd', 'g'],
 ['o', 'g', 'd'],
 ['g', 'd', 'o'],
 ['g', 'o', 'd']]
  • Related