### Thread: python program for generatig all permutation

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2012
Posts
1
Rep Power
0

#### python program for generatig all permutation

a=[1,2,3,4]
r=[[]]
for x in a:
s=[]
p=[]
s=[]
t=[ i + [x] for i in r if i<>[x]]
if t not in r:
if len(t)<=4:
r=r+t
#print r
p=[ [x] + i for i in r if i<>[x]]

if p not in r:
r=r+p
s=[ i + [x] + j for i in r for j in r if j<>i and j<>[x] and i<>[x]]

if s not in r:
#len(s)<=4:
r=r+s
for y in r:
if len(y) == 4:
if y not in temp:
temp=temp+[y]
temp.sort()
for w in temp:
print w

I am not getting required o/p
I am getting
[1, 2, 3, 4]
[2, 1, 2, 3]
[2, 1, 2, 4]
[2, 1, 3, 4]
[3, 1, 2, 3]
[3, 1, 2, 4]
[3, 1, 3, 4]
[3, 2, 1, 2]
[3, 2, 1, 3]
[3, 2, 1, 4]
[3, 2, 3, 4]
[4, 1, 2, 3]
[4, 1, 2, 4]
[4, 1, 3, 4]
[4, 2, 1, 2]
[4, 2, 1, 3]
[4, 2, 1, 4]
[4, 2, 3, 4]
[4, 3, 1, 2]
[4, 3, 1, 3]
[4, 3, 1, 4]
[4, 3, 2, 1]
[4, 3, 2, 3]
[4, 3, 2, 4]

2. Which version of python are you using? When I run your code it gives the IndentationError I expect.
Code:
```...   File "<stdin>", line 2
s=[]
^
IndentationError: expected an indented block
Traceback (most recent call last):
File "<stdin>", line 1, in <module>```

Meanwhile, I suggest you use itertools:
Code:
```>>> import pprint
>>> import itertools
>>> pprint.pprint(list(itertools.permutations('abcd')))
[('a', 'b', 'c', 'd'),
('a', 'b', 'd', 'c'),
('a', 'c', 'b', 'd'),
('a', 'c', 'd', 'b'),
('a', 'd', 'b', 'c'),
('a', 'd', 'c', 'b'),
('b', 'a', 'c', 'd'),
('b', 'a', 'd', 'c'),
('b', 'c', 'a', 'd'),
('b', 'c', 'd', 'a'),
('b', 'd', 'a', 'c'),
('b', 'd', 'c', 'a'),
('c', 'a', 'b', 'd'),
('c', 'a', 'd', 'b'),
('c', 'b', 'a', 'd'),
('c', 'b', 'd', 'a'),
('c', 'd', 'a', 'b'),
('c', 'd', 'b', 'a'),
('d', 'a', 'b', 'c'),
('d', 'a', 'c', 'b'),
('d', 'b', 'a', 'c'),
('d', 'b', 'c', 'a'),
('d', 'c', 'a', 'b'),
('d', 'c', 'b', 'a')]```