生成所有可能的三个字母的字符串的最佳方法是什么?[重复]
- 2025-03-05 09:15:00
- admin 原创
- 58
问题描述:
我正在生成所有可能的三个字母的关键字,e.g. aaa, aab, aac.... zzy, zzz
下面是我的代码:
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
keywords = []
for alpha1 in alphabets:
for alpha2 in alphabets:
for alpha3 in alphabets:
keywords.append(alpha1+alpha2+alpha3)
是否可以以更简洁、更高效的方式实现此功能?
解决方案 1:
keywords = itertools.product(alphabets, repeat = 3)
请参阅文档itertools.product
。如果您需要字符串列表,只需使用
keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)]
alphabets
也不需要是一个列表,它可以只是一个字符串,例如:
from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]
如果您只想要小写的 ASCII 字母,则可以。
解决方案 2:
您也可以使用 map 代替列表推导(这是 map 仍然比 LC 更快的情况之一)
>>> from itertools import product
>>> from string import ascii_lowercase
>>> keywords = map(''.join, product(ascii_lowercase, repeat=3))
这种列表推导的变体也比使用''.join
>>> keywords = [a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]
解决方案 3:
from itertools import combinations_with_replacement
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for (a,b,c) in combinations_with_replacement(alphabets, 3):
print a+b+c
解决方案 4:
您也可以通过简单的计算来实现此目的,无需任何外部模块。
这PermutationIterator
就是您要搜索的内容。
def permutation_atindex(_int, _set, length):
"""
Return the permutation at index '_int' for itemgetter '_set'
with length 'length'.
"""
items = []
strLength = len(_set)
index = _int % strLength
items.append(_set[index])
for n in xrange(1,length, 1):
_int //= strLength
index = _int % strLength
items.append(_set[index])
return items
class PermutationIterator:
"""
A class that can iterate over possible permuations
of the given 'iterable' and 'length' argument.
"""
def __init__(self, iterable, length):
self.length = length
self.current = 0
self.max = len(iterable) ** length
self.iterable = iterable
def __iter__(self):
return self
def __next__(self):
if self.current >= self.max:
raise StopIteration
try:
return permutation_atindex(self.current, self.iterable, self.length)
finally:
self.current += 1
给它一个可迭代对象和一个整数作为输出长度。
from string import ascii_lowercase
for e in PermutationIterator(ascii_lowercase, 3):
print "".join(e)
这将从“aaa”开始,以“zzz”结束。
解决方案 5:
chars = range(ord('a'), ord('z')+1);
print [chr(a) + chr(b) +chr(c) for a in chars for b in chars for c in chars]
解决方案 6:
我们可以不使用 itertools 而是利用两个函数定义来解决这个问题:
def combos(alphas, k):
l = len(alphas)
kRecur(alphas, "", l, k)
def KRecur(alphas, prfx, l, k):
if k==0:
print(prfx)
else:
for i in range(l):
newPrfx = prfx + alphas[i]
KRecur(alphas, newPrfx, l, k-1)
它使用两个函数来避免重置 alpha 的长度,第二个函数自我迭代直到达到 ak 0 以返回该 i 循环的 k-mer。
采纳自 Abhinav Ramana 在 Geeks4Geeks 上的解决方案
解决方案 7:
好吧,我在思考如何涵盖该主题时想到了这个解决方案:
import random
s = "aei"
b = []
lenght=len(s)
for _ in range(10):
for _ in range(length):
password = ("".join(random.sample(s,length)))
if password not in b:
b.append("".join(password))
print(b)
print(len(b))
请让我描述一下里面发生的事情:
导入随机,
创建一个包含我们想要使用的字母的字符串
创建一个空列表,我们将用它来放置我们的组合
现在我们使用范围(我输入了 10,但是对于 3 位数字来说可以更小)
接下来使用带有列表和列表长度的 random.sample 我们创建字母组合并将其连接起来。
在接下来的步骤中,我们将检查 b 列表中是否有该组合 - 如果有,则不会将其添加到 b 列表中。如果当前组合不在列表中,我们将把它添加到列表中。(我们正在比较最终加入的组合)。
最后一步是打印包含所有组合的列表 b,并打印可能的组合数。也许这不是最清晰和最有效的代码,但我认为它有效...
解决方案 8:
print([a+b+c for a in alphabets for b in alphabets for c in alphabets if a !=b and b!=c and c!= a])
这将删除一个字符串中的重复字符
扫码咨询,免费领取项目管理大礼包!