Skip to content

Instantly share code, notes, and snippets.

@jeetsukumaran
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeetsukumaran/77f88dfe7242afd8fe33 to your computer and use it in GitHub Desktop.
Save jeetsukumaran/77f88dfe7242afd8fe33 to your computer and use it in GitHub Desktop.
Exactly One Matching Element
#! /usr/bin/env python
"""
Python Golf
An expression that takes predicate function object and an iterable,
and returns True if the predicate function evaluates True once and exactly once
when applied to all the elements in the iterable.
Expression with the minimum number of non-whitespace characters wins.
Anything in the standard library is fair game, but that 'import' statement is
going to cost you (not to mention that you will also be forced to construct a
function body to host the import and that 'def fn(a,b):' is also going to cost
you.
If you are going to go the function body route, then the function name will
only count as 1 character no matter how long it is (allows you to name the
function long enough to be useful and distinguishable).
Third-party libraries are out.
"""
predicate_fn = lambda x: x is not None
not_none = object()
one_notnone = [not_none if i == 5 else None for i in range(10)]
all_notnone = [not_none for i in range(10)]
all_none = [None for i in range(10)]
one_none = [None if i ==7 else not_none for i in range(10)]
mixed = [not_none if (i%2) else None for i in range(10)]
def test(candidate_fn):
f = lambda x: candidate_fn(predicate_fn, x)
assert f(one_notnone) is True
assert f(all_notnone) is False
assert f(all_none) is False
assert f(one_none) is False
assert f(mixed) is False
print("Success!")
# 70 non-whitespace chars (and counting function name as 1 char)
def f1(p, v):
import itertools
return len(list(itertools.ifilter(p, v))) == 1
test(f1)
# 37 non-whitespace chars (counting function name as 1 char)
f2 = lambda p, v: len([i for i in v if p(i)]) == 1
test(f2)
# Derrick Zwickl, 2013-03-02: 33!!
f3 = lambda p, v: sum([p(i) for i in v]) == 1
test(f3)
# Derrick Zwickl, 2013-03-03: 31!!
f4 = lambda p, v: sum(p(i) for i in v) == 1
test(f4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment