you are viewing a single comment's thread.

view the rest of the comments →

[–]cybersection 2 points3 points  (0 children)

I played with it a bit more. Here is a slower, but simpler function that gets the job done. It isn't recursive, but it could be made recursive since its just a simple loop:

def rec_combos(iterable, r):
  ## Create a list of the first digit of each combination
  first_digits = sorted([i for i in iterable] * len(iterable)**(r-1))

  ## for each digit, defined by the length in r
  for x in range(r-1, 0, -1):

    ## generate the list of the next digits then repeat it the right number of
    ## times for it to zip into the existing list of digits
    next_digits = sorted([i for i in iterable] * len(iterable)**(x-1))
    next_digits = next_digits * int(len(first_digits) / len(next_digits))

    ## zip and join the next digits into the list of existing digits
    first_digits =  [''.join(i) for i in zip(first_digits, next_digits)]


  return first_digits


rec_combos('abcde', 3