I have a string from which I want to remove all possible combinations till the end. I tried this:
combinations = ['XY', 'ZU', 'YY']
lst_matched = list(filter(lambda val: val in mystring, combinations))
for i in matches:
if len(mystring) > 0:
mystring = mystring.replace(i,'')
print('after', mystring)
If I use this with a mystring
like ZXYUYY
, it will identify lst_matched
as [XY, YY]
and my function will correctly remove these substrings from mystering
.
However, after removing these substrings, the updated string now has ZU
which is also another combination to check for.
How can I modify my code such that it searches for all possible combinations till there's no match left? Recurssion could be used but not sure how.
CodePudding user response:
Try this:
def replace(mystring, combinations):
val = next((val for val in combinations if val in mystring), None)
while val is not None:
mystring = mystring.replace(val, '')
val = next((val for val in combinations if val in mystring), None)
return mystring
Basically you find the first combination that can be found in mystring
(this can be done with next((val for val in combinations if val in mystring), None)
). If no such a combination can be found then val
will be None
.
Then you replace that specific combination with ''
. And you repeat. You stop when such combination cannot be found anymore (i.e., when val
is None
).
Examples:
>>> replace('ZXYUYY', ['XY', 'ZU', 'YY'])
''
>>> replace('ZXYUYY', ['XY', 'YY'])
'ZU'
>>> replace('AZXYUYY', ['XY', 'ZU', 'YY'])
'A'
>>> replace('AZBXYUYY', ['XY', 'ZU', 'YY'])
'AZBU'
CodePudding user response:
Just repeat the replacement until the resulting string is the same as the original string:
combinations = ['XY', 'YY', 'ZU']
mystring = 'ZXYUYY'
while True:
new_string = mystring
for combination in combinations:
new_string = new_string.replace(combination, '')
if new_string == mystring:
break
mystring = new_string
print(mystring)
Or more simply using a regular expression:
import re
regex = re.compile('XY|YY|ZU')
mystring = 'ZXYUYY'
while True:
mystring, substitutions = regex.subn(mystring, '')
if not substitutions:
break
print(mystring)
CodePudding user response:
You can loop over the permutations of your "combination":
from itertools import permutations
mystring = "ZXYUYY"
combinations = ['ZU', 'XY', 'YY']
for p in permutations(combinations, len(combinations)):
for c in p:
mystring = mystring.replace(c, "")
print('after', mystring)
print(mystring)
CodePudding user response:
Create an "infinite" loop that exits once the string has no occurrences of the strings from remove_list
(i.e. your combinations
list)
remove_list = ['XY', 'YY', 'ZU']
s = "ZXYUYY"
while True:
if any(i in s for i in remove_list):
for j in remove_list:
s = s.replace(j, "")
break
print(s)