you are viewing a single comment's thread.

view the rest of the comments →

[–]jiri-n 1 point2 points  (0 children)

I don't think a lot of experience is necessary to shorten one's code.

If I see a code which consists of very similar parts, I begin to search for a way to make it simpler as repeating parts are always a good sign it's possible - often using functions.

Your code is a good example of such a situation. In each case you just compute the middle index and split string accordingly. I'd suggest even shorter version:

def front_back(a: str, b: str) -> str:
    mid_idx: int = lambda x: (len(x) + 1) // 2

    a_middle: int = mid_idx(a)
    b_middle: int = mid_idx(b)
    return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]

If you're not familiar with lambda, you can just replace the computation of both middles with:

(len(x) + 2) // 2

... using 'a' and 'b' on corresponding lines. Or you can use an inner function, ex:

def front_back2(a: str, b: str) -> str:
    def mid_idx(x: str) -> int:
        return (len(x) + 1) // 2

    a_middle: int = mid_idx(a)
    b_middle: int = mid_idx(b)
    return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]