python:获取所有可能的字母表达到给定的长度

标签 python

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

got = permutations(getAllTheLetters(),4)
cnt = 0
for i in got:
    cnt += 1
    print ''.join(i)

print cnt

上面没有给出“zzzz”或“zzz”
我需要如下所示的内容: A B C D.. aa、ab、ac、.. 啊啊啊啊……

但是 do_perm() 被硬编码为循环四次,这是我不想做的。

def getAllTheLetters(begin='a', end='z'):
    beginNum = ord(begin)
    endNum = ord(end)
    yield ''
    for number in xrange(beginNum, endNum+1):
        yield chr(number)

def do_perm(l):
    s = set()
    for a in getAllTheLetters():
        for b in getAllTheLetters():
            for c in getAllTheLetters():
                for d in getAllTheLetters():
                    to_add = "%s%s%s%s" % (a,b,c,d)
                    if to_add != "":
                        s.add(to_add)

    return s

got = do_perm(1)
cnt = 0
for i in sorted(got):
    cnt +=1
    print i
print cnt

最佳答案

您可以简单地使用 itertools.product ,像这样

from itertools import product

def get_strings(letters, max_length):
    for i in range(1, max_length + 1):
        for value in product(letters, repeat=i):
            yield "".join(value)

当你像这样调用它时

print(list(get_strings("ab", 2)))

你会得到

['a', 'b', 'aa', 'ab', 'ba', 'bb']

如果你想获取从az的所有值,你可以调用get_strings,就像这样

from string import ascii_lowercase
print(list(get_strings(ascii_lowercase, 4)))

注意:这将创建大量字符串,因此您的计算机可能会停止响应。如果您只想遍历字符串,请使用 for 循环和 get_strings 如下所示,并且不要创建列表。

for current_string in get_strings(ascii_lowercase, 4):
    # Process the current_string

关于python:获取所有可能的字母表达到给定的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666239/

相关文章:

没有 __dict__ 的 Python 打印属性

python - 解决 SQL 中的三向循环引用 (Django)

python - 减去两个包含 datetime.time 的 numpy 数组

python - 如何安全地将密码发送到 REST 服务?

python - python argparse中的多行帮助显示

python - Python-eve Rest Api 框架中的用户相关资源过滤器

python - argmax 用于沿某个轴的多维数组

python - Pandas 数据框 - 使用 np.clip() 设置边界并从列中的特定值中减去值

python - gcc 编译器无法识别 -fno-plt 选项

python - 根据最终 excel 文件中特定列中的空/空白值删除一行 - Pandas Data frame