[英]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 '-'. 我想将所有“-”都删除1的所有组合。 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. 我试图用for循环来解决它,出现次数为“-”,里面有一个while循环,但是我的逻辑有点不对劲,所以代码没有实现我想要的功能。
One possible variant. 一种可能的变体。
Use itertools.product
to easily get all combinations of ("-", "")
in a sequence of n elements, for example: 使用itertools.product
可以轻松获得n个元素序列中("-", "")
所有组合,例如:
>>> 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.