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
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
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)]
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]