-4

Given a list like alist = [1, 3, 2, 20, 10, 13], I wanna write a function find_group_f, which can generate all possible combination of elements in alist and meanwhile I can dynamically control the number k of element in each group. For instance, if the number k is 2, the function is equal to:

for e1 in alist:
    for e2 in alist[alist.index(e1)+1:]:
        print (e1, e2)

While the number k is 3, it would be like:

for e1 in alist:
    for e2 in alist[alist.index(e1)+1:]:
        for e3 in alist[alist.index(e2)+1:]:
            print (e1, e2, e3)

I wonder how can I implement like this? Thanks in advance!

southdoor
  • 431
  • 1
  • 8
  • 22
  • 2
    There's a stdlib function for that: https://docs.python.org/3/library/itertools.html#itertools.combinations. – skovorodkin Oct 04 '16 at 18:19
  • 3
    Use recursion: http://stackoverflow.com/questions/7186518/function-with-varying-number-of-for-loops-python – Rafael Oct 04 '16 at 18:19

1 Answers1

0

to quote:

function Recurse (y, number) 
   if (number > 1)
      Recurse ( y, number - 1 )
   else
      for x in range (y)
      whatever()

Don't actually know how to quote, so here's a link: Function with varying number of For Loops (python)

Community
  • 1
  • 1
Rafael
  • 3,096
  • 1
  • 23
  • 61