简体   繁体   中英

How to get all combinations of strings with characters removed

I have the following strings:

'aa-df-bvc'
'hj-j-klegt-dew'

I want to get all the combinations of removing 1 to all of the '-'. The output I want is the following:

{'aadf-bvc','aa-dfbvc','aadfbvc'}
{'hjj-klegt-dew','hj-jklegt-dew','hj-j-klegtdew','hjjklegt-dew','hj-jklegtdew', 'hjj-klegtdew', 'hjjklegtdew'}

I tried to solve it whit a for-loop with the number of times '-' appear and a while loop inside, but my logic was a bit off so the code didn't do what I wanted.

One possible variant.
Use itertools.product to easily get all combinations of ("-", "") in a sequence of n elements, for example:

>>> print(list(product(("-", ""), repeat=2)))
[('-', '-'), ('-', ''), ('', '-'), ('', '')]

And for every combo join all pieces of your string according to the sequence of "-" and "" (I remove the combination with all "-" since you don't want it).

Code:

from itertools import product


def get_all_combinations(s, sep="-"):
    results = []
    sep_no = s.count(sep)
    s_pieces = s.split(sep)
    for c in product((sep, ""), repeat=sep_no):
        results.append("".join(sum(zip(s_pieces, c + ("",)), ())))
    results.remove(s)  # if you don't want the all-"-" combo
    return results


s = 'aa-df-bvc'
t = 'hj-j-klegt-dew'
>>> print(get_all_combinations(s))
>>> print(get_all_combinations(t))

Output:

['aa-dfbvc', 'aadf-bvc', 'aadfbvc']
['hj-j-klegtdew', 'hj-jklegt-dew', 'hj-jklegtdew', 'hjj-klegt-dew', 'hjj-klegtdew', 'hjjklegt-dew', 'hjjklegtdew']

I was able to solve it :-)

Here is my code:

def getAllCombinations(w):
    to_return = [w]
    for number_to_remove in range(1,w.count('-')):
        offs = -1
        counter = w.count('-')
        while True:
            if number_to_remove > counter:
                break
            else:
                offs = w.find('-', offs + 1)
                counter -= 1
                if offs == -1:
                    break
                removed = w[0: offs] + w[offs:].replace('-', '', number_to_remove)

                to_return.append(removed)
    return to_return

Maybe there is a better way of doing this?

A simpler version:

a = 'aa-df-bvc'
a = a.split("-")
before = ""
for i in range(len(a)):
    if i+1 != len(a):
        result = ""
        for string in a[i:]:
            before = before + string
            result = before + "-"
            break
        result = result + "".join(a[i+1:])
    else:
        result = "".join(a)
    print("result: {0}".format(result))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM