Home > OS >  How to interleave items from 2 lists backward
How to interleave items from 2 lists backward

Time:07-24

Word Problem:

Create a function to interleave the letters of two strings (starting with the first string from right to left) and return the resultant string.

def interleave(s1: str, s2: str) -> str:

I was able to solve this word problem but I need help putting it in a function

def interleave(s1: str, s2: str) -> str:
    string1 = s1[::-1]
    string2 = s2[::-1]

    for i in range(len(string1)):
        print(string2[i]   string1[i], end = "")
    
    return print

print(interleave("1234", "5678"))

CodePudding user response:

I can't tell from your question what should happen when the strings are unequal in length. My basic solution would be

def interleave(str1, str2):
    return ''.join(c1   c2 for c1, c2 in zip(str1, str2))

but this will stop with the shortest of the two input strings.

CodePudding user response:

Right now, the function prints the results. Instead store the results in a variable, which you return when done.

Like so:

#!/usr/bin/python3

def interleave(s1: str, s2: str) -> str:
    string1 = s1[::-1]
    string2 = s2[::-1]
    interleaved_string = ''

    for i in range(len(string1)):
        interleaved_string  = string2[i]   string1[i]

    return interleaved_string

print(interleave("1234", "5678"))

CodePudding user response:

Your whole loop can be made into a one-liner using zip and map (or a generator comprehension):

def interleave(str1: str, str2: str) -> str:
    assert len(str1) == len(str2), "Strings must be equal in length."  # Alternatively, consider itertools.zip_longest
    return ''.join(map(''.join, zip(str1[::-1], str2[::-1])))

Input:

joined_str = interleave("1234", "5678")
print(joined_str)

Output:

'48372615'

CodePudding user response:

You can try this snippet: (try to follow your logic first)

It's convenient to take two characters (digit) at the same time by using zip and glue them into final answer output.

Another note to make is that for sequence type, it's better to extract the items directly and avoid using the index as much as possible. (A habit inherit from other language mostly....)

This solution will ONLY work if 2 strings are the same size, otherwise this has to be modified to account for that. (but that's easy)

The original code did not return the final "output". It should.

def interleave(s1: str, s2: str) -> str:
    rs1 = s1[::-1]
    rs2 = s2[::-1]
    out = ''

    for a, b in zip(rs2, rs1):
        out  = (a b)
    return out


print(interleave("1234", "5678"))   # 84736251

If you're open to fancier solution, looking for more_itertool

from more_itertools import roundrobin

S, T = "1234",  "5678"

print(''.join(roundrobin(T[::-1], S[::-1]))) # you can put it to func...
'84736251'

# It can handle unequal sizes situation: 
TT = '56789'
print(''.join(roundrobin(TT[::-1], S[::-1])))
'948372615'
  • Related