python - 在 Python 中按字典顺序生成字符串
问题描述
如何编写一个 Python 生成器,它可以懒惰地生成由不超过一定长度1的小写英文字母组成的所有字符串?
我已经编写了自己的解决方案(作为答案发布在下面),但我想看看是否有更优雅/高效/有趣的解决方案。
1无限迭代器将毫无用处,因为它只会生成仅由字符组成的字符串a
。这是因为字符串的字典顺序不是很好的;它可以被认为是由无限嵌套序列的无限序列组成:( a
, ( aa
, ...), ( ab
, ...), ...), ( b
, ( ba
, ...), ( bb
, .. .), ...), ...生成器永远不会到达ab
,因为它有无限数量的前辈。
解决方案
这是我的解决方案:
import string
def lexstrings(max_length: int, alphabet=string.ascii_lowercase):
yield ""
if max_length == 0: return
for first in alphabet:
for suffix in lexstrings(max_length - 1, alphabet=alphabet):
yield first + suffix
例子:
>>> g = lexstrings(max_length=3, alphabet="ab")
>>> list(g)
['',
'a',
'aa',
'aaa',
'aab',
'ab',
'aba',
'abb',
'b',
'ba',
'baa',
'bab',
'bb',
'bba',
'bbb']
This might not be the best solution because it involves recursion and using the +
operator m
times to generate a string of length m
, which isn't efficient because Python generates copies of the intermediate results (since strings are immutable).
This implementation also "supports" the infinite version:
>>> g = lexstrings(-1)
>>> next(g)
''
>>> next(g)
'a'
>>> next(g)
'aa'
>>> next(g)
'aaa'
...
推荐阅读
- javascript - 当错误来自另一个函数时无法捕获错误
- java - 即使在 pow.xml 中添加依赖项后,junit 也不会出现
- android - 尝试分享音频:android.content.ActivityNotFoundException: No Activity found to handle Intent
- python - Python 正则表达式阻塞模式
- python - SPOTIFY API - 抓取多位艺术家
- python - 使用python在缺失数据之间进行插值
- r - 在闪亮的应用程序中使用 2 个动作按钮在 3 个绘图之间切换
- python - 当期权值不断变化时,如何使用硒通过下拉列表进行封闭式?
- python - 更改硒驱动程序时区
- reactjs - How to get context from higher order component in constructor of child component?