penmas penmas - 8 months ago 32
Python Question

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):
elif s == '' and t == '':
return ''
return s[0] + t[0] + alt(s[1:], t[1:])

Desired Output:

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


Just test for s and t are empty and return the other value if one of them is:

def alt(s, t):
    if not s:
        return t
    elif not t:
        return s
        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.

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).

This produces your desired output:

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

An iterative version would be:

from itertools import chain
    # 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.