英文:
Using permutations to generate words
问题
I am tyring to generate words after replacing the characters found in replacements dict. If x string is given...
x = 'sap'
return the possible words like...
x_result = ['sap', 'saq', 'sbp', 'sbq']
The replacement table is:
replacements = {'a':'b', 'b':'a', 'm':'n', 'n':'m', 'p':'q', 'q':'p'}
Here is another example:
y = 'map'
y_result = ['map', 'maq', 'mbp', 'mbq', 'nap', 'naq', 'nbp', 'nbq']
英文:
I am tyring to generate words after replacing the characters found in replacements dict. If x string is given...
x = 'sap'
return the possible words like...
x_result = ['sap', 'saq', 'sbp', 'sbq']
The replacement table is:
replacements = {'a':'b', 'b':'a', 'm':'n', 'n':'m', 'p':'q', 'q':'p'}
Here is another example:
y = 'map'
y_result = ['map', 'maq', 'mbp', 'mbq', 'nap', 'naq', 'nbp', 'nbq']
答案1
得分: 3
我会首先确定字符串中每个位置的选项,代码如下:
x = "sap"
replacements = {"a": "b", "b": "a", "m": "n", "n": "m", "p": "q", "q": "p"}
# 使用集合来消除重复...
subs = [{_x, replacements.get(_x, _x)} for _x in x]
print(subs) # [{"s"}, {"a", "b"}, {"p", "q"}]
这基本上表示:
- 位置0的选项只有 "s"
- 位置1的选项为 "a" 或 "b"
- 位置2的选项为 "p" 或 "q"
然后,你可以简单地使用内置的 itertools 来获取这些列表的乘积:
import itertools
print(["".join(s) for s in itertools.product(*subs)])
# ['sbp', 'sbq', 'sap', 'saq']
英文:
I would approach this by determining first the options for each position in the string
x = "sap"
replacements = {"a":"b","b":"a","m":"n","n":"m","p":"q","q":"p"}
# use a set to eliminate duplicates...
subs = [{_x,replacements.get(_x,_x)} for _x in x]
print(subs) # [{'s'}, {'a', 'b'}, {'p', 'q'}]
this basically says
- the options for position0 is only "s"
- the options for position1 is "a", or "b"
- the options for position2 is "p", or "q"
then you can simply use the builtin itertools to get the product of these lists
import itertools
print(["".join(s) for s in itertools.product(*subs)])
#['sbp', 'sbq', 'sap', 'saq']
</details>
# 答案2
**得分**: 2
以下是代码部分的翻译:
```python
x_result = [x]
for i, c in enumerate(x):
if d := replacements.get(c):
x_result += [w[:i] + d + w[i+1:] for w in x_result]
英文:
Going through the word, applying each letter's replacement (if any):
x_result = [x]
for i, c in enumerate(x):
if d := replacements.get(c):
x_result += [w[:i] + d + w[i+1:] for w in x_result]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论