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.
if len(s) != len(t):
elif s == '' and t == '':
return s + t + alt(s[1:], t[1:])
Just test for
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 else: return s + t + alt(s[1:], t[1:])
Even if both
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 + t + alt(s[1:], t[1:])
so the end-state is reached whenever either
t is empty (or they both are).
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.