0

I've done the exercise and it works. But I want to know if there a smarter way to do it. Thanks.

# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back

My code:

def front_back(a, b):
    if len(a) % 2 == 0:
    a_front = a[0:len(a) / 2]
    else:
    a_front = a[0:(len(a) / 2) + 1]
    if len(a) % 2 == 0:
    a_back = a[len(a) / 2:]
    else:
    a_back = a[(len(a) / 2) + 1:]
    if len(b) % 2 == 0:
    b_front = b[0:len(b) / 2]
    else:
    b_front = b[0:(len(b) / 2) + 1]
    if len(b) % 2 == 0:
    b_back = b[len(b) / 2:]
    else:
    b_back = b[(len(b) / 2) + 1:]
    return a_front + b_front + a_back + b_back

4 Answers4

2

You probably don't need all the if tests. Using substrings (as you use the slices in python), the following example in Java works.

public static String SplitMixCombine(String a, String b) {

    return a.substring(0, (a.length()+1)/2) + 
            b.substring(0, (b.length()+1)/2) + 
            a.substring((a.length()+1)/2, a.length()) + 
            b.substring((b.length()+1)/2, b.length()); 
}

Just got this to work in python:

>>> def mix_combine(a, b):
...     return a[0:int((len(a)+1)/2)] + b[0:int((len(b)+1)/2)] + a[int((len(a)+1)/2):] +b[int((len(b)+1)/2):]
...

>>> a = "abcd"
>>> b = "wxyz"
>>> mix_combine(a,b)
'abwxcdyz'
>>> a = "abcde"
>>> b = "vwxyz"
>>> mix_combine(a,b)
'abcvwxdeyz'
>>>
1

This is a lot cleaner code.

def front_back(a, b):
    print a, b
    a_indx = int((len(a)+1)/2)
    b_indx = int((len(b)+1)/2)

    print a[:a_indx] + b[:b_indx] + a[a_indx:] +b[b_indx:]
    print "\n"

front_back("ab", "cd")
front_back("abc", "de")
front_back("ab", "cde")
front_back("abc", "def")

Hope this helps !

doubleo
  • 4,389
  • 4
  • 16
  • 19
0

I wrote another one-liner for this:

def front_back(a, b):
  return a[:len(a) / 2 + len(a) % 2] + b[:len(b) / 2 + len(b) % 2] + a[-(len(a) / 2):] + b[-(len(b) / 2):]

An interesting thing to note is that in Python 5 / 2 yields 2, but -5 / 2 yields -3, you might expect to get -2. That's why I added the parenthesis. See Negative integer division surprising result

Community
  • 1
  • 1
Pawel Krakowiak
  • 9,940
  • 3
  • 37
  • 55
-1
def front_back(a, b):
return front_string(a)+front_string(b)+back_string(a)+back_string(b)

def front_string(s):
return  s[:int((len(s)+1)/2)]  

def back_string(s):
return  s[int((len(s)+1)/2):] 

# int((len(s)+1)/2) returns the correct index for both odd and even length strings
Nazik
  • 8,696
  • 27
  • 77
  • 123
Burnie
  • 1