I have a small trouble with one problem:
For example, we have string 'YXY00'
. Every 'X'
of 'Y'
may be replaced with 'Y'
or 'X'
respectively. In this example we have 2^3 = 8 options of replacement, like:
YXY00
YXX00
YYY00
YYX00
XXY00
XXX00
XYY00
XYX00
How can I get this replacements with Python 3.x?
You can use itertools.permutations()
to get the permutations of a string. Then by applying some substitution logic, you can end up with the following:
import itertools
def permutate(source, changeset):
count = sum(1 for char in source if char in changeset)
holder = ''.join('{}' if char in changeset else char for char in source)
for perm in set(itertools.permutations(changeset * count, count)):
print(holder.format(*perm))
permutate('XY000Y00', 'XY')
Result:
XY000X00
XX000Y00
XY000Y00
XX000X00
YX000X00
YY000Y00
YX000Y00
YY000X00
I refactored some more, now it is more readable:
def replace_at_index(string, index, replacement):
"""
Credit to: http://stackoverflow.com/users/95612/jochen-ritzel
>>> replace_at_index("abc", 1, "z")
'azc'
"""
return string[:index] + replacement + string[index + 1:]
def possible_replaces(string):
"""
>>> list(possible_replaces('YXY00'))
['XXY00', 'YXY00', 'YXY00', 'YYY00', 'YXX00', 'YXY00', 'YXY00', 'YXY00']
>>> list(possible_replaces('XYY000000'))
['XYY000000', 'YYY000000', 'XXY000000', 'XYY000000', 'XYX000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000']
"""
for index, char in enumerate(string):
if char in 'XY':
yield replace_at_index(string, index, 'X')
yield replace_at_index(string, index, 'Y')
else:
yield string
I also wrote a more general solution:
def possible_replaces(string, to_multipy_replace = 'XY'):
"""
Returns a list of strings where each member of `to_multipy_replace` is replaced
by each member of said set.
>>> list(possible_replaces('YXY00'))
['XXY00', 'YXY00', 'YXY00', 'YYY00', 'YXX00', 'YXY00', 'YXY00', 'YXY00']
>>> list(possible_replaces('XYY0'))
['XYY0', 'YYY0', 'XXY0', 'XYY0', 'XYX0', 'XYY0', 'XYY0']
"""
for index, char in enumerate(string):
if char in to_multipy_replace:
for replacement in to_multipy_replace:
yield replace_at_index(string, index, replacement)
else:
yield string
You are now not limited to 'XY' only but any charset that pleases you.
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.