Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python every possible combination of a string

Hi so I'm working with python and I'm trying to write a method where given a string, it would find every combination of that string and append it to a list. I'll give the string and show the outcome that I want.

string: x = 'god'

outcome:

lst = ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']

A letter can only be used by the number of times it appears on the string given, so if our string is 'god', 'gg' or 'goo' etc. cannot be appended. If this could be done using recursion that would be great!

like image 660
Gary Liton Avatar asked Jan 29 '26 03:01

Gary Liton


1 Answers

Use permutations:

from itertools import permutations

x = 'god'


perms = []

for i in range(1, len(x)+1):
    for c in permutations(x, i):
        perms.append("".join(c))

print(perms) 
# ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']
like image 116
Marcin Avatar answered Jan 31 '26 18:01

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!