使用排列生成单词

huangapple go评论65阅读模式
英文:

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]

Attempt This Online!

huangapple
  • 本文由 发表于 2023年6月15日 11:40:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定