1

So I have a function that takes two string inputs - it slices them so that if of even length, the length of the front segment is the same as that of the back, and if of odd length, the middle character goes to the front segment (i.e. hello -> hel , lo). And then you mix and match the resulting front and back segments of the two string to produce the final output.

I want to be able to do this all under one function and what I came up with is ugly as all heck:

def front_back(a, b):
    if len(a) % 2 == 0:
        front_a = a[:len(a)/2]
        back_a = a[len(a)/2:]
    elif len(a) % 2 != 0:
        front_a = a[:(len(a)/2)+1]
        back_a = a[(len(a)/2)+1:]
    if len(b) % 2 == 0:
        front_b = b[:len(b)/2]
        back_b = b[len(b)/2:]
    elif len(b) % 2 != 0:
        front_b = b[:(len(b)/2)+1]
        back_b = b[(len(b)/2)+1:]

    print front_a + front_b + back_a + back_b

front_back('Kitten', 'Donut') ---> KitDontenut

Is there a more pythonic/elegant way?

I couldn't figure out how to use lambdas (they can't process the if statement necessary to deal with even and odd length cases... i think?) if that's the way to go...

UPDATE: thanks for the great suggestions everyone. just one more question:

when i try a version with lamdbas, based off a suggestion (for practice), I get a NameError that global name 's' isn't defined. What's wrong with how I wrote the lambda?

def front_back(a, b):
    divideString = lambda s: s[:((1+len(s))//2)], s[((1+len(s))//2):]
    a1, a2 = divideString(a)
    b1, b2 = divideString(b)
    print a1 + b1 + a2 + b2
front_back("hello","cookies")
4
  • your lambda is parsed as (lambda s: s[:((1+len(s))//2)]), s[((1+len(s))//2):]. You should write lambda s: (s[:((1+len(s))//2)], s[((1+len(s))//2):]) Jun 9, 2015 at 21:55
  • @JohnLaRooy what do you mean? Jun 9, 2015 at 21:56
  • The lambda ends at the ,. You need to add parens to force the second part to be included Jun 9, 2015 at 21:57
  • @JohnLaRooy oh wow, how silly. thanks man. Jun 9, 2015 at 21:59

5 Answers 5

12

You are making it more complicated than it needs to be:

def front_back(a, b):
    mid_a, mid_b = (len(a) + 1) // 2, (len(b) + 1) // 2
    front_a, back_a = a[:mid_a], a[mid_a:]
    front_b, back_b = b[:mid_b], b[mid_b:]
    print front_a + front_b + back_a + back_b

By adding 1 before dividing by 2 (floor division), you round up.

Demo:

>>> def front_back(a, b):
...     mid_a, mid_b = (len(a) + 1) // 2, (len(b) + 1) // 2
...     front_a, back_a = a[:mid_a], a[mid_a:]
...     front_b, back_b = b[:mid_b], b[mid_b:]
...     print front_a + front_b + back_a + back_b
... 
>>> front_back('Kitten', 'Donut')
KitDontenut

You could inline the slicing even:

def front_back(a, b):
    mid_a, mid_b = (len(a) + 1) // 2, (len(b) + 1) // 2
    print a[:mid_a] + b[:mid_b] + a[mid_a:] + b[mid_b:]
2
  • 1
    This is a good answer, but I can't see a good reason for using the tuple assignment in preference to an extra line. Jun 9, 2015 at 21:31
  • @JohnLaRooy: Agreed. If the calculations for mid_a and mid_b were vertically aligned it would take a split second less to see that they are the identical calculation. Jun 9, 2015 at 21:33
6
def divideString(myString):
    sliceHere = ( (1 + len(myString)) // 2)
    return myString[:sliceHere], myString[sliceHere:]

def front_back(a, b):
    a1, a2 = divideString(a)
    b1, b2 = divideString(b)
    return a1 + b1 + a2 + b2
5
  • good stuff, but i specified id prefer it all done under one function Jun 9, 2015 at 21:12
  • 2
    @SpicyClubSauce: That's a silly restriction. Putting the code in a function avoids repetition and gives the idea a name. But if you must have it all in one function you can move the function definition inside of front_back. And if you don't want a def you can make it a lambda. Like so: divideString = lambda s: s[:((1+len(s))//2)], s[((1+len(s))//2):] Jun 9, 2015 at 21:18
  • I think it would be easier to read if you factor out ((1+len(myString))//2). It's a good idea to keep divideString as a separate function as you can then test it separately Jun 9, 2015 at 21:34
  • nice suggestion, i added it just now
    – Dleep
    Jun 9, 2015 at 21:38
  • @StevenRumbalski tried your lamdba suggestion, why is it giving me a name error for just the variable i'm using for the lambda function? def front_back(a, b): divideString = lambda s: s[:((1+len(s))//2)], s[((1+len(s))//2):] a1, a2 = divideString(a) b1, b2 = divideString(b) print a1 + b1 + a2 + b2 front_back("hello","cookies") Jun 9, 2015 at 21:43
0
def front_back(a, b):
    return "".join([a[:(len(a)+1)/2]], b[:(len(b)+1)/2], \
        a[(len(a)+1)/2]:], b[:(len(b)+1)/2]])
2
  • return a[:(len(a)+1)/2]] + b[:(len(b)+1)/2] + a[(len(a)+1)/2]:] + b[:(len(b)+1)/2] -- I like it better without "".join(...). I would also prefer the calculations not be done twice. That just seems a bit verbose. Your one-liner is so long it needs two lines so you may as well break it more logically and shorten it to boot (like in the last two lines of Martijn Pieters's answer). Jun 9, 2015 at 21:29
  • The join is there since AFAIK, it's a faster way of merging strings. As for the dual computation, assigning a new variable would probably also take longer. Then again, the function surely won't be the bootleneck anyway and I think everyone has their preferences on things like these.
    – hajtos
    Jun 9, 2015 at 22:19
0

You could also add the result of length % 2 to the fronts:

def front_back(a, b):
    ln_a, ln_b = len(a), len(b)
    a1 = a2 = ln_a // 2
    b1 = b2 = ln_b // 2
    a1 += ln_a % 2
    b1 += ln_b % 2
    return a[:a1] + b[:b1] + a[-a2:] + b[-b2:]

print(front_back('Kitten', 'Donut'))
0

There are a some good answers here already, but for the sake of diversity, since you seem to be interested in multiple possibilities, here's a different way of looking at it:

import itertools

def front_back(a,b):
    words = [a,b]
    output = [[],[]]
    for word in words:
        if len(word) % 2 == 0:
            output[0].append(word[:len(word)//2])
            output[1].append(word[len(word)//2:])

        else:
            output[0].append(word[:len(word)//2+1])
            output[1].append(word[(len(word)//2)+1:])

    return "".join(output[0]) + "".join(output[1])

print(front_back('Kitten', 'Donut'))

Interpret with Python 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.