【发布时间】:2019-01-21 08:31:55
【问题描述】:
我正在尝试找到解决此问题的最有效方法。目前,我有一个解决方案,在该解决方案中,我创建了字符串与其字符串长度的映射,然后使用辅助函数将字符拼接在一起,并在执行过程中递减映射列表。当当前值减为 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 -
澄清:我不是在寻找一个图书馆来完成这个。相反,我试图了解如何自己实现这种算法。这里的目标是了解此类问题背后的算法技术。也许删除python标签?以为我会在那里添加它,因为我的实现是在 Python 中
-
您已经在混合基数系统中实现了从最大值
total_combos到零的计数(其中第 k 个数字的基数是第 k 个字符串的长度)。这是相当有效的方法。也确实存在简单的递归方式(适用于不是很长的项目)。恕我直言,最好删除 Python 标记
标签: algorithm combinations computer-science