繁体   English   中英

交错两个字符串的所有可能方法

[英]All possible ways to interleave two strings

我试图生成所有可能的方法来交错Python中的任意两个任意字符串。

例如:如果两个字符串是'ab''cd' ,我希望获得的输出是:

['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']

看到a总是在b之前(和c之前的d )。 我正在努力寻找解决方案。 我尝试过如下所示的itertools:

import itertools

def shuffle(s,t):
    string = s+t
    for i in itertools.permutations(string):
        print(''.join(i))

shuffle('ab','cd')

但正如预期的那样,这将返回所有可能的排列,而忽略ab (以及cd )的顺序。

想法

让你想要交错的两个字符串是st 我们将使用递归来生成交错这两个字符串的所有可能方法。

如果在任何时间点我们已经交织的第一i的字符s和第一j的字符t创造一些字符串res ,那么我们有两种方式交错他们的下一个步骤-

  1. si+1个字符附加到res
  2. tj+1个字符附加到res

我们将继续这个递归,直到两个字符串的所有字符已被使用,然后我们在字符串列表这个结果存储lis如下面的代码。

代码

def interleave(s, t, res, i, j, lis):
    if i == len(s) and j == len(t):
        lis.append(res)
        return
    if i < len(s):
        interleave(s, t, res + s[i], i + 1, j, lis)
    if j < len(t):
        interleave(s, t, res + t[j], i, j + 1, lis)

l = []
s = "ab"
t = "cd"
interleave(s, t, "", 0, 0, l)
print l

产量

['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']

这个实现和我们可以获得的效率一样高(至少渐近),因为我们从不生成两次相同的字符串。

已经发布了其他几个解决方案,但是大多数解决方案都会在内存中生成交错字符串(或其等价物)的完整列表,从而使其内存使用量随输入长度呈指数增长。 当然必须有更好的方法。

枚举所有的方式分别对交织长度ab的两个序列,是基本相同枚举所有A + B位整数设定exably b个比特。 每个这样的整数对应于交错序列的不同方式,通过用第一序列的元素替换每0位而获得,并且每1位用第二序列的元素替换。

方便的是,有一种聪明而有效的方法来计算具有相同位数的下一个整数 ,我们可以使用它来生成所有这样的整数。 所以我们先做到这一点:

def bit_patterns(m, n):
    """Generate all m-bit numbers with exactly n bits set, in ascending order.
    See http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
    """
    patt = (1 << int(n)) - 1
    if patt == 0: yield 0; return  # loop below assumes patt has at least one bit set!
    while (patt >> m) == 0:
        yield patt
        lowb = patt & -patt  # extract the lowest bit of the pattern
        incr = patt + lowb   # increment the lowest bit
        diff = patt ^ incr   # extract the bits flipped by the increment
        patt = incr + ((diff // lowb) >> 2)  # restore bit count after increment

现在我们可以使用这个生成器生成交错任意两个序列的所有方法:

def interleave(a, b):
    """Generate all possible ways to interleave two sequences."""
    m = len(a) + len(b)
    n = len(a)
    for pattern in bit_patterns(m, n):
        seq = []
        i = j = 0
        for k in range(m):
            bit = pattern & 1
            pattern >>= 1
            seq.append(a[i] if bit else b[j])
            i += bit
            j += 1-bit
        yield seq

请注意,为了尝试尽可能通用,此代码采用任意序列类型并返回列表。 字符串是Python中的序列,因此您可以很好地传递它们; 要将生成的列表转换回字符串,您可以连接它们的元素,例如"".join() ,如下所示:

foo = "ABCD"
bar = "1234"
for seq in interleave(foo, bar):
    print("".join(seq))

我们去了:一个完全非递归有效的基于生成器的解决方案,即使对于长输入也只使用很少的内存,并且只生成一次输出(因此不需要低效的重复消除步骤)。 它甚至适用于Python 2和3。

效率极低但工作:

def shuffle(s,t):
    if s=="":
        return [t]
    elif t=="":
        return [s]
    else:
        leftShuffle=[s[0]+val for val in shuffle(s[1:],t)]
        rightShuffle=[t[0]+val for val in shuffle(s,t[1:])]
        leftShuffle.extend(rightShuffle)
        return leftShuffle

print(shuffle("ab","cd"))

您只需要比较abc的索引到d然后过滤掉那些a索引大于b索引并且c索引大于d索引的元素。

def interleave(s, t):
    mystring = s + t
    return [el for el in [''.join(item) for item in permutations(mystring) if  item.index('a') < item.index('b') and item.index('c') < item.index('d')]]

演示:

>>> from itertools import permutations
>>> s = 'ab'
>>> t = 'cd'
>>> [el for  el in [''.join(item) for item in permutations(s+t) if item.index('a') < item.index('b') and item.index('c') < item.index('d')]]
['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']

只是为了运动

没有显式条件或谓词的解决方案

(即,没有任何if关键字):

from itertools import chain, repeat, permutations
from copy import deepcopy


def shuffle(*strings):
    # Treat the strings as pools from which to draw elements in order.
    # Convert the strings to lists, so that drawn items can be removed:
    pools = (list(string) for string in strings)

    # From each pool, we have to draw as many times as it has items:
    pools_to_draw_from = chain.from_iterable(
        repeat(pool, len(pool)) for pool in pools
    )

    # Because itertools.permutations treats elements as unique based on their
    # position, not on their value and because pools_to_draw_from has repeated
    # repeated items, we would get repeated permutations, if we would not
    # filter them out with `unique`.
    possible_drawing_orders = unique(permutations(pools_to_draw_from))

    # For each drawing order, we want to draw (and thus remove) items from our
    # pools. Subsequent draws within the same drawing order should get the
    # respective next item in the pool, i.e., see the modified pool. But we don't
    # want the pools to be exhausted after processing the first drawing ordering.
    #
    # Deepcopy preserves internal repetition and thus does exactly what we need.
    possible_drawing_orders = (deepcopy(pdo) for pdo in possible_drawing_orders)

    # Draw from the pools for each possible order,
    # build strings and return them in a list:
    return [''.join(_draw(p)) for p in possible_drawing_orders]


def _draw(drawing_order):
    return (pool_to_draw_from.pop(0) for pool_to_draw_from in drawing_order)

我们需要一个辅助函数:

from operator import itemgetter
from itertools import groupby

def unique(iterable, key=None):
    # Other than unique_everseen from
    # https://docs.python.org/3/library/itertools.html#itertools-recipes, this
    # works for iterables of non-hashable elements, too.
    return unique_justseen(sorted(iterable, key=key), key)


def unique_justseen(iterable, key=None):
    """
    List unique elements, preserving order. Remember only the element just seen.
    """
    # from https://docs.python.org/3/library/itertools.html#itertools-recipes
    return map(next, map(itemgetter(1), groupby(iterable, key)))

如果非唯一排列的数量很大,由于调用sorted ,这可能是相当低效的。 有关获取非唯一值的唯一排列的替代方法,请参阅具有唯一值的排列

TL; DR?

没问题。 我们可以将这种方法归结为这种令人厌恶的:

from itertools import chain, repeat, permutations
from copy import deepcopy

def shuffle(*strings):
    return list({''.join(l.pop(0) for l in deepcopy(p)) for p in permutations(chain.from_iterable(repeat(list(s), len(s)) for s in strings))})

(对结果使用集合理解而不是更早地确保唯一性。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM