I have an issue with @Hooked's answer...
Firstly I am a complete novice where py is concerned, but I was looking for something like the above code. I'm currently entering it over at Repl.it
My first issue was the argument
for x in permutations([1,2,3],2):
print x
which returned the following error
line 26
print x
^
SyntaxError: Missing parentheses in call to 'print'
I fixed this like so
for x in permutations([1,2,3],2):
print (x)
But now got the error:
line 25, in <module>
for x in permutations([1,2,3],2):
File "main.py", line 14, in permutations
cycles[i] -= 1
TypeError: 'range' object does not support item assignment
Now at this point I have no idea where to go to debug the code. However, I have seen many people point to itertools as having the code in it's documentation. I copied that and it works. This is the code:
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return