Splitting two strings in halves and joining them in a more Pythonic way. Using lambda expression?

Viewed 45

Consider splitting a string into two halves. If the length is even, the front and back half are the same size. If the length is odd, the extra character is in the front half.

Example: 'abcde', the front half is 'abc' and the back half is 'de'.

Finally, given two strings a and b, return a string of the form: a-front + b-front + a-back + b-back

So if a = 'abcde' and b = 'vwxyz', then the returned form is abcvwxdeyz

this is the most pythonic I've got:

def front_back(a, b):
    import math
    half_a = math.ceil(len(a)/2)
    half_b = math.ceil(len(b)/2)
    return a[:half_a]+b[:half_b]+a[half_a:]+b[half_b:]

Would there be a pythonic way to go more efficient or with less lines here? Gratitude.

2 Answers

Some suggestions of answers:

def front_back(a, b):
        """ Resposta 1 """
        # half_a = math.ceil(len(a) / 2)
        # half_b = math.ceil(len(b) / 2)
        # return a[:half_a] + b[:half_b] + a[half_a:] + b[half_b:]
    
        """ Resposta 2 """
        # half_a, half_b = map(math.ceil, (len(a) / 2, len(b) / 2))
        # return "".join([a[:half_a], b[:half_b], a[half_a:], b[half_b:]])
    
        """ Resposta 3 """
        # def half(string, last_part=False):
        #     middle = math.ceil(len(string) / 2)
        #     return string[middle:] if last_part else string[:middle]
    
        # last_half = lambda s : half(s, last_part=True)
        # return "".join([half(a), half(b), last_half(a), last_half(b)])
    
        """ Resposta 4 """
        def split(string):
            middle = math.ceil(len(string) / 2)
            return (string[:middle], string[middle:])
        
        def mix(tuple1, tuple2):
            return tuple1[0], tuple2[0], tuple1[1], tuple2[1]
    
        return "".join(mix(split(a), split(b)))

try (pure python, no additional packges/modules needed):

def f(x)
    if (len(x) % 2) == 0: #even
        part1 = x[:len(x)/2]
        part2 = x[len(x)/2:]
    else: #odd
        part1 = x[:len(x)/2+1]
        part2 = x[len(x)/2+1:]

    return [part1, part2]

def g(i, j):
    return f(i)[0] + f(j)[0] + f(i)[1] + f(j)[1] 

a = 'abcde' #f(a) return ['abc', 'dc']
b = 'vwxyz' #f(b) return ['vwx', 'yz'] 

front_back = g(a, b)

print(front_back)
# 'abcvwxdcyz'


     
Related