gpt4 book ai didi

algorithm - 给定一个字符串列表,打印所有字符串组合,从每个字符串中选择一个字符

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:38:43 25 4
gpt4 key购买 nike

我正在尝试找到解决此问题的最有效方法。目前,我有一个解决方案,我在其中创建字符串到它们的字符串长度的映射,然后使用辅助函数将字符拼接在一起并在我进行时递减映射列表。当前值递减为 0 时,其左侧的数字递减 1,然后该数字 + 其右侧的数字重置为其长度 1。其实现如下所示:

def printCombinations(s):
data_lens = []
s = [x for x in s if x]
for idx,val in enumerate(s): #create string length mapping list
if len(val) == 0:
s = s[0:idx]+s[idx+1:] #remove empty strings
idx = idx -1
else:
data_lens.append(len(s[idx])-1)
total_combos = 1
for i in data_lens:
total_combos = total_combos * (i+1) #total combos = lengths of the strings multiplied by each other
current_index = len(s)-1

while total_combos > 0:
data_lens_copy = data_lens[:]
if data_lens[current_index] >= 0: #if current number >= 0
print(generateString(data_lens_copy, s))
data_lens[current_index] -= 1
total_combos -=1
else:
if current_index > 0:
while data_lens[current_index] <= 0: #shift left while <= 0
current_index -= 1

if data_lens[current_index] >= 0:
data_lens[current_index] -= 1
for i in range(current_index+1,len(s)):
data_lens[i] = len(s[i])-1
current_index = len(s)-1

def generateString(indices, strings):
resultStr = ""
for i in range(len(indices)-1,-1,-1):
current_str = strings[i]
current_index = indices[i]
if current_str != "":
resultStr = current_str[current_index] + resultStr
indices[i] -= 1
return resultStr

虽然这个解决方案完成了工作,但它创建了一个大小相等的映射列表,并在数字达到 0 时迭代地将映射值重置为右侧。打印出包含 1 个字符的所有字符串组合的更有效方法是什么来自每个字符串元素?

ex: ["dog","cat"] -> dc,da,dt,oc,oa,ot,gc,ga,gt

最佳答案

如果您不想使用 itertools.product 并且希望了解算法,一种方法是定义递归算法。它比原始代码快(大约 16 倍),但与涉及的 print 的比较是不确定的。

def product(item,*args):
# termination condition: if only one string, yield the characters.
if not args:
yield from item
else:
# Recursion, yield the character for each item,
# combined with the results of the remaining strings
for c in item:
for d in product(*args):
yield c + d

print(list(product('dog','cat')))
print(list(product('ab','cd','def')))

输出:

['dc', 'da', 'dt', 'oc', 'oa', 'ot', 'gc', 'ga', 'gt']
['acd', 'ace', 'acf', 'add', 'ade', 'adf', 'bcd', 'bce', 'bcf', 'bdd', 'bde', 'bdf']

关于algorithm - 给定一个字符串列表,打印所有字符串组合,从每个字符串中选择一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com