penmas - 7 months ago 22

Python Question

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'

Answer

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

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