简体   繁体   English

返回两个不同长度的字符串中的交替字母

[英]Return Alternating Letters in Two Strings of Different Lengths

I currently have a code written that recursively takes the letters within two strings and returns the new word with alternating letters. 我目前编写的代码以递归方式接收两个字符串中的字母,并以交替的字母返回新单词。 I would like to optimize this code so that if the first or second word was longer it will still return the remaining letters in the longer string. 我想优化此代码,以便如果第一个或第二个单词较长,它仍将返回较长字符串中的其余字母。

def alt(s,t):
    if len(s) != len(t):
        return 
    elif s == '' and t == '':
        return ''
    else:
        return s[0] + t[0] + alt(s[1:], t[1:])

Desired Output: 所需输出:

>>> alt('hello','bye')
'hbeylelo'

Just test for s and t are empty and return the other value if one of them is: 只需测试st是否为空,如果其中一个为,则返回另一个值:

def alt(s, t):
    if not s:
        return t
    elif not t:
        return s
    else:
        return s[0] + t[0] + alt(s[1:], t[1:])

Even if both s and t are empty, the empty string is returned, which is a perfectly valid end-state. 即使st均为空,也将返回空字符串,这是一个完全有效的结束状态。

You could shorten this to: 您可以将其缩短为:

def alt(s, t):
    if not (s and t):
        return s + t
    return s[0] + t[0] + alt(s[1:], t[1:])

so the end-state is reached whenever either s or t is empty (or they both are). 因此,只要st为空(或两者都为空),就会达到最终状态。

This produces your desired output: 这将产生您想要的输出:

>>> alt('hello', 'bye')
'hbeylelo'

An iterative version would be: 迭代版本为:

from itertools import chain
try:
    # Python 2
    from itertools import izip_longest as zip_longest
except ImportError:
    # Python 3
    from itertools import zip_longest

def alt_iterative(s, t):
    return ''.join(chain.from_iterable(zip_longest(s, t, fillvalue='')))

This uses the itertools.zip_longest() function to do most of the work. 这使用itertools.zip_longest()函数来完成大部分工作。

The problem itself is not inherently recursive. 问题本身并不是天生的递归。 An iterative solution may be simpler in this case. 在这种情况下,迭代解决方案可能会更简单。

Python 2: Python 2:

from itertools import izip_longest
def alt(s, t):
    return ''.join(a + b for a, b in izip_longest(s, t, fillvalue=''))

Python 3: Python 3:

from itertools import zip_longest
def alt(s, t):
    return ''.join(a + b for a, b in zip_longest(s, t, fillvalue=''))

If you like a one-liner using itertools.chain and zip (or itertools.zip_longest / izip_longest ): 如果您喜欢使用itertools.chainzip (或itertools.zip_longest / izip_longest )的单线

# Python 2
return ''.join(chain(*zip(s, t))) + s[len(t):] + t[len(s):]
# or
return ''.join(chain(*izip_longest(s, t, fillvalue='')))

# Python 3
return ''.join(chain(*zip_longest(s, t, fillvalue='')))

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

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