Split
December 30, 2011
Today’s exercise comes from our file of interview questions:
Given a list, return the first half of the list as one list and the second half of the list as a second list. For instance, given the input list {1 2 3 4}, output the two lists {1 2} and {3 4}. If the input list has an odd number of items, the middle item can go to either list, so that the input list {1 2 3 4 5} can result in the output lists {1 2} and {3 4 5} or the output lists {1 2 3} and {4 5}.
Your task is to write the function that splits a list in two halves. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Simple enough in Python:
Even simpler in Haskell:
spl xs = splitAt (length xs `div` 2) xs
this isn’t one of perl’s more elegant applications.
as far as I know, perl does not allow you to return multiple lists. instead, we return a list of list references. this has the requirement of allocating our half-lists from the calling routine, and passing references to those half-lists to our hsplit routine:
whoops, no need for that return statement at the end of hsplit.
def split(aList):
cut = len(aList) / 2
firstH = aList[:cut]
secondH = aList[cut:]
return firstH,secondH
Oneliner solution in perl, basic tests included:
http://pastebin.com/GtduSYTg
or if you:
you can do
Oops, I meant to say it’s ruby… Another way with the second approach:
Another Perl solution. Works for empty and single-element lists as well.
Handles empty list and single element lists as well.
Clojure example:
(defn split [lst]
(let [half-count (int (/ (count lst) 2))]
[(take half-count lst) (drop half-count lst)]))
Python to split a pair chain with the slow and fast enumeration of the elements as in the reference problem and solution.
Pairs are (tail, head), so they look backwards when printed, but they match Python’s reduce which accumulates from left.
For testing, a mapping from Python lists to pair chains and back.
Sourcecode tag, please work.
C++ solution. A bit verbose, but well it’s c++ :) No need for the tortoise and hare solution, as the length of the list is already known.
One liner in Python.
ruby solution (http://codepad.org/C0JQX0rw)