问题是打印两个给定字符串的所有可能的交错。所以我用Python编写了一个工作代码,运行方式如下:
def inter(arr1,arr2,p1,p2,arr):
thisarr = copy(arr)
if p1 == len(arr1) and p2 == len(arr2):
printarr(thisarr)
elif p1 == len(arr1):
thisarr.extend(arr2[p2:])
printarr(thisarr)
elif p2 == len(arr2):
thisarr.extend(arr1[p1:])
printarr(thisarr)
else:
thisarr.append(arr1[p1])
inter(arr1,arr2,p1+1,p2,thisarr)
del thisarr[-1]
thisarr.append(arr2[p2])
inter(arr1,arr2,p1,p2+1,thisarr)
return
它来自字符串中的每个点,然后对于一个递归调用,它将当前元素视为属于第一个数组,并在下一个调用中认为属于另一个数组。因此,如果输入字符串为ab
和cd
,则会打印出abcd
,acbd
,cdab
,cabd
等。{{1和p1
是指向数组的指针(因为Python字符串是不可变的,我使用数组!)。任何人都可以告诉我,这段代码的复杂程度是什么,是否可以改进?我编写了一个类似的代码来打印给定数组中p2
长度的所有组合:
k
这也是基于同样的原则。那么一般来说,如何找到这些函数的复杂性,以及如何优化它们? DP可以做到这些吗?第一个问题的输入输出示例:
def kcomb(arr,i,thisarr,k):
thisarr = copy(thisarr)
j,n = len(thisarr),len(arr)
if n-i<k-j or j >k:
return
if j==k:
printarr(thisarr)
return
if i == n:
return
thisarr.append(arr[i])
kcomb(arr,i+1,thisarr,k)
del thisarr[-1]
kcomb(arr,i+1,thisarr,k)
return
答案 0 :(得分:20)
您的问题可以简化为创建特定列表的所有唯一排列的问题。说A
和B
分别是字符串arr1
和arr2
的长度。然后构建一个这样的列表:
[0] * A + [1] * B
从该列表的唯一排列到两个字符串arr1
和arr2
的所有可能交错存在一对一的对应关系(双射)。我们的想法是让排列的每个值指定从哪个字符串中取出下一个字符。这是一个示例实现,展示了如何从置换构造交错:
>>> def make_interleave(arr1, arr2, permutation):
... iters = [iter(arr1), iter(arr2)]
... return "".join(iters[i].next() for i in permutation)
...
>>> make_interleave("ab", "cde", [1, 0, 0, 1, 1])
'cabde'
我在python邮件列表中找到了this问题,询问如何以有效的方式解决这个问题。答案建议使用Knuth的计算机编程艺术,第4卷,分册2:生成所有排列中描述的算法。我找到了here草案的在线pdf。该算法也在此wikipedia article中进行了描述。
这是我自己的next_permutation
算法的注释实现,作为python生成器函数。
def unique_permutations(seq):
"""
Yield only unique permutations of seq in an efficient way.
A python implementation of Knuth's "Algorithm L", also known from the
std::next_permutation function of C++, and as the permutation algorithm
of Narayana Pandita.
"""
# Precalculate the indices we'll be iterating over for speed
i_indices = range(len(seq) - 1, -1, -1)
k_indices = i_indices[1:]
# The algorithm specifies to start with a sorted version
seq = sorted(seq)
while True:
yield seq
# Working backwards from the last-but-one index, k
# we find the index of the first decrease in value. 0 0 1 0 1 1 1 0
for k in k_indices:
if seq[k] < seq[k + 1]:
break
else:
# Introducing the slightly unknown python for-else syntax:
# else is executed only if the break statement was never reached.
# If this is the case, seq is weakly decreasing, and we're done.
return
# Get item from sequence only once, for speed
k_val = seq[k]
# Working backwards starting with the last item, k i
# find the first one greater than the one at k 0 0 1 0 1 1 1 0
for i in i_indices:
if k_val < seq[i]:
break
# Swap them in the most efficient way
(seq[k], seq[i]) = (seq[i], seq[k]) # k i
# 0 0 1 1 1 1 0 0
# Reverse the part after but not k
# including k, also efficiently. 0 0 1 1 0 0 1 1
seq[k + 1:] = seq[-1:k:-1]
根据this问题,算法的每个产量都具有O(1)的摊销复杂度,但根据下面评论的rici,只有所有数字都是唯一的,它们肯定是唯一的情况。不是在这种情况下。
在任何情况下,产量的数量都为时间复杂度提供了一个下限,它由
给出(A + B)! / (A! * B!)
然后,为了找到实时复杂度,我们需要将每个产量的平均复杂度与基于排列构造结果字符串的复杂性相加。如果我们将这个总和乘以上面的公式,我们得到总的时间复杂度。
答案 1 :(得分:1)
好的,经过一些工作,并从其他答案中获取建议。主要是lazyr。 (现在已将其转换为类)__all_perms来自:https://stackoverflow.com/a/104436/1561176
class Interleave():
def __init__(self, A, B):
self.A = A
self.B = B
self.results = list(self.__interleave())
# from https://stackoverflow.com/a/104436/1561176
def __all_perms(self, elements):
if len(elements) <=1:
yield elements
else:
for perm in self.__all_perms(elements[1:]):
for i in range(len(elements)):
#nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
def __sequences(self):
return list( sorted( set(
["".join(x) for x in self.__all_perms(['a'] * len(self.A) + ['b'] * len(self.B))] ) ) )
def __interleave(self):
for sequence in self.__sequences():
result = ""
a = 0
b = 0
for item in sequence:
if item == 'a':
result+=self.A[a]
a+=1
else:
result+=self.B[b]
b+=1
yield result
def __str__(self):
return str(self.results)
def __repr__(self):
return repr(self.results)
以下是用法:
>>> A = ['a', 'b', 'c']
>>> B = ['d', 'e', 'f']
>>> Interleave(A, B)
['abcdef', 'abdcef', 'abdecf', 'abdefc', 'adbcef', 'adbecf', 'adbefc', 'adebcf', 'adebfc', 'adefbc', 'dabcef', 'dabecf', 'dabefc', 'daebcf', 'daebfc', 'daefbc', 'deabcf', 'deabfc', 'deafbc', 'defabc']
另外,您可以访问类成员,如:
>>> inter = Interleave(A, B)
>>> inter.results
['abcdef', 'abdcef', 'abdecf', 'abdefc', 'adbcef', 'adbecf', 'adbefc', 'adebcf', 'adebfc', 'adefbc', 'dabcef', 'dabecf', 'dabefc', 'daebcf', 'daebfc', 'daefbc', 'deabcf', 'deabfc', 'deafbc', 'defabc']
>>> inter.A
['a', 'b', 'c']
>>> inter.B
['d', 'e', 'f']
答案 2 :(得分:0)
permutations
适合您吗?或者,这是编码实践吗?
>>> from itertools import permutations
>>> s1 = "ab"
>>> s2 = "cd"
>>> all_values = [c for c in s1 + s2]
>>> ["".join(r) for r in permutations(all_values)]
['abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba']
答案 3 :(得分:0)
我认为你正在尝试这样做:
from itertools import product, chain
def interleave(a, b):
if len(b) > len(a):
a, b = b, a
boolean = (True, False)
for z in range(len(a) - len(b) + 1):
pairs = list(zip(a[z:], b))
for vector in product(*[boolean] * max(map(len, (a, b)))):
permutation = (pair if i else reversed(pair)
for i, pair in zip(vector, pairs))
yield a[:z] + ''.join(chain.from_iterable(permutation))