Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to implement an "i not equal to j" (i<j) loop, which skips cases where i = j, but I would further like to make the additional requirement that the loop does not repeat the permutation of (j,i), if (i,j) has already been done (since, due to symmetry, these two cases give the same solution).

First Attempt

In the code to follow, I make the i<j loop by iterating through the following lists, where the second list is just the first list rolled ahead 1:

mylist = ['a', 'b', 'c']
np.roll(mylist,2).tolist() = ['b', 'c', 'a']

The sequence generated by the code below turns out to not be what I want:

import numpy as np

mylist = ['a', 'b', 'c']
for i in mylist:
    for j in np.roll(mylist,2).tolist():
        print(i,j)

since it returns a duplicate a a and has repeated permutations a b and b a:

a b
a c
a a
b b
b c
b a
c b
c c
c a

The desired sequence should instead be the pair-wise combinations of the elements in mylist, since for N=3 elements, there should only be N*(N-1)/2 = 3 pairs to loop through:

a b
a c
b c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
487 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use list.insert to help with left shift and right shift.

list.pop, removes the element from the original list and returns it as well. list.insert adds the returned element into the list at given index (0 or -1 in this case). NOTE: this operation is in place!

#Left shift
mylist = ['apples', 'guitar', 'shirt']
mylist.insert(-1,mylist.pop(0))
mylist

### ['guitar', 'apples', 'shirt']
#Right shift
mylist = ['apples', 'guitar', 'shirt']
mylist.insert(0,mylist.pop(-1))
mylist

### ['shirt', 'apples', 'guitar']

A better way to do this is with collections.deque. This will allow you to work with multiple shifts and has some other neat queue functions available as well.

from collections import deque

mylist = ['apples', 'guitar', 'shirt']
q = deque(mylist)
q.rotate(1)       # Right shift ['shirt', 'apples', 'guitar']
q.rotate(-1)      # Left shift ['guitar', 'shirt', 'apples']
q.rotate(3)       #Right shift of 3 ['apples', 'guitar', 'shirt']

EDIT: Based on your comments, you are trying to get permutations -

from itertools import product
[i for i in product(l, repeat=2) if len(set(i))>1]
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

OR

out = []
for i in l:
    for j in l:
        if len(set([i,j]))>1:
               print(i,j)
a b
a c
b a
b c
c a
c b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...