-2

All I have been taught and read on the web is shuffle and other methods. I was figuring if there is another method with simple forms like while or for.

I'm new at this if someone can help me please

Rodrigo Villalta
  • 29
  • 1
  • 1
  • 2
  • shuffle is easier than any loop based solution. It's slightly confusing because it doesn't return the list you're shuffling - it changes it in place. see this answer: http://stackoverflow.com/questions/976882/shuffling-a-list-of-objects-in-python – theodox Sep 12 '13 at 05:24
  • i know but i just want to know how a loop form looks like – Rodrigo Villalta Sep 12 '13 at 05:33
  • What do you mean by "do permutations"? Do you need to do something with permutations of a given list, or do you just want to understand the algorithms that can be used to generate them? – Blckknght Sep 12 '13 at 05:39
  • Both will be good, im trying to learn so both will be good – Rodrigo Villalta Sep 12 '13 at 05:50

2 Answers2

2

You should be looking at combinations.

from itertools import combinations

my_list = [1, 2, 3, 4]
list(combinations(my_list, 3))

# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
Yossi
  • 11,778
  • 2
  • 53
  • 66
1

It's not entirely clear what you're asking for. If you just want a quick way to get at the permutations of a list, use itertools.permutations:

for perm in itertools.permutations(sequence):
    # do something with permutation "perm"

If you want to understand how to produce permutations yourself, then it's a bit more complicated. There are a variety of ways to go, and often different algorithms are chosen in order to produce permutations in a specific order. Here's the algorithm described in Wikipedia, which generates the permutations of a sequence in lexicographic order (same as itertools):

def permutations(seq):
    perm = sorted(seq) # the first permutation is the sequence in sorted order
    while True:
        yield perm

        # find largest index k such that perm[k] < perm[k+1]
        for k in range(len(perm)-2, -1, -1):
            if perm[k] < perm[k+1]:
                break
        else: # if none was found, we've already found the last permutation
            return

        # find the largest index l such that perm[k] < perm[l] (always exists)
        for l in range(len(perm)-1, -1, -1):
            if p[k] < p[l]:
                break

        # Build the next permutation. This is equivalent to copying perm,
        # swapping the values at indexes `k` and `l`, then reversing the values
        # from index `k+1` to the end.
        perm = perm[:k]+perm[l:l+1]+perm[-1:l:-1]+perm[k:k+1]+perm[l-1:k:-1]
Blckknght
  • 100,903
  • 11
  • 120
  • 169