Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

list - How to run a i<j loop in Python, and not repeat (j,i) if (i,j) has already been done?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...