#1
  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]

    please suggest modification
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,709
    Rep Power
    480
    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>
    Please follow the link at my signature and fix your post.

    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')]
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo