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

python - How to get all possible combinations of characters in a String

So I have a string like this:

"abc"

I would need:

"abc"
"acb"
"bca"
"bac"
"cab"
"cba"

I tried:

string = "abc"

combinations = []
for i in range(len(string)):
    acc = string[i]
    for ii in range(i+1,i+len(string)):
            acc += string[ii%len(string)]
             
    combinations.append(acc)
    combinations.append(acc[::-1])
            
print(combinations)

If works for string of size 3, but I believe it is very inefficient and also doesn't work for "abcd". Is there a better approach?

Update: I would like to solve by providing an algorithm. Actually currently working in a recursive way to solve it. Would prefer a solution that is not a python function solving the problem for me

question from:https://stackoverflow.com/questions/65840793/how-to-get-all-possible-combinations-of-characters-in-a-string

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

1 Reply

0 votes
by (71.8m points)

Try itertools.permutations:

from itertools import permutations
print('
'.join(map(''.join, list(permutations("abc", 3)))))

Output:

abc
acb
bac
bca
cab
cba

edit:

For an algorithm:

string = "abc"
def combinations(head, tail=''):
    if len(head) == 0:
        print(tail)
    else:
        for i in range(len(head)):
            combinations(head[:i] + head[i+1:], tail + head[i])
combinations(string)

Output:

abc
acb
bac
bca
cab
cba

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

...