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
329 views
in Technique[技术] by (71.8m points)

string - Combinations without repetition (python)

I want to make the following combinations:

string.1 string.1
string.2 string.2 string.1
string.3 string.3 string.2 string.1
string.4 string.4 string.3 string.2
string.4 string.1

Each item should be combined with every other one, but the order does not matter, i.e. string.4 string.1 is the same as string.1 string.4. Also, there should be a maximum of 4 combinations per line. Each item in the first column is combined with each one in the other columns. For example in line 2, there are the combinations string.2-string.2 & string.2-string.1.

This is my code:

import itertools
BLOCKS=4
DB="string"
getiter = lambda : itertools.chain( range(1, BLOCKS+1))
for i in getiter():
    for j in range(1, BLOCKS, 4):
            emit = f"{DB}.{i}"
            for k in range(4):
                    if j + k > BLOCKS:
                            break
                    emit += " {}.{}".format(DB, j+k)
            print(emit)

And this is my current output:

string.1 string.1 string.2 string.3 string.4
string.2 string.1 string.2 string.3 string.4
string.3 string.1 string.2 string.3 string.4
string.4 string.1 string.2 string.3 string.4

Here, there are combinations that are superfluous. How do I get rid of those?

question from:https://stackoverflow.com/questions/65845420/combinations-without-repetition-python

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

1 Reply

0 votes
by (71.8m points)

Maybe something like that :

import itertools
BLOCKS=4
DB="string"
getiter = lambda : itertools.chain( range(1, BLOCKS+1))
for i in getiter():
    emit = f"{DB}.{i}"
    for k in range(1, BLOCKS+1):
        if k > BLOCKS: break
        else if k == i: continue #<========== Added
        emit += " {}.{}".format(DB, k)
    print(emit)

(Note that the second loop (j) seems useless so I did remove it)

Output :

string.1 string.2 string.3 string.4
string.2 string.1 string.3 string.4
string.3 string.1 string.2 string.4
string.4 string.1 string.2 string.3

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

...