Reputation: 87
I need to create a function without the use of itertools
which will create a permutation list of tuples with a given set of anything.
Example:
perm({1,2,3}, 2)
should return [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
This is what i got:
def permutacion(conjunto, k):
a, b = list(), list()
for i in conjunto:
if len(b) < k and i not in b:
b.append(i)
b = tuple(b)
a.append(b)
return a
I know this doesn't do anything, it will add the first combination and nothing else.
Upvotes: 1
Views: 9251
Reputation: 88148
As mentioned by @John in the comments, the code for itertools.permutations
is:
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
Which works with your example using no external imports or recursive calls:
for x in permutations([1,2,3],2):
print (x)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
Upvotes: 3
Reputation: 759
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
Upvotes: 1