wiki:Tutorial21

Evolution of a coding test, (when there is no time limit)

naive solution

import itertools

def take(n, xs):
    return list(itertools.islice(xs, n))

def drop(n, xs):
    return list(itertools.islice(xs, n, None))

def partition (n, xs):
    return take(n, xs), drop(n, xs)

def solution(xs):
    res = []
    for i,x in enumerate(xs):
        s1, s2 = partition(i, xs)
        if sum(s1) ==  sum(s2):
            res.append(x)
    return res

unnecessary wrapping into a list gives pretty printing for free

import itertools

def take(n, xs):
    return itertools.islice(xs, n)

def drop(n, xs):
    return itertools.islice(xs, n, None)

def partition (n, xs):
    return take(n, xs), drop(n, xs)

def solution(xs):
    ys = []
    for i,x in enumerate(xs):
        s1, s2 = partition(i, xs)
        if sum(s1) ==  sum(s2):
            ys.append(x)
    return ys

without imports

def take(n, xs):
    return iter(xs[:n])

def drop(n, xs):
    return iter(xs[n:])

def partition (n, xs):
    return take(n, xs), drop(n, xs)

def solution(xs):
    ys = []
    for i,x in enumerate(xs):
        s1, s2 = partition(i, xs)
        if sum(s1) ==  sum(s2):
            ys.append(x)
    return ys

idiomatic slicing

def solution(xs):
    ys = []
    for i,x in enumerate(xs):
        s1, s2 = xs[:i], xs[i:]
        if sum(s1) ==  sum(s2):
            ys.append(x)
    return ys

and finally list comprehensions

def solution(xs):
   return [x for i,x in enumerate(xs) if sum(xs[:i]) == sum(xs[i:])]

Last modified 4 years ago Last modified on Aug 12, 2016, 6:29:06 AM
Note: See TracWiki for help on using the wiki.