Skip to content

Instantly share code, notes, and snippets.

@Artanis
Created August 2, 2012 18:43
Show Gist options
  • Save Artanis/3239577 to your computer and use it in GitHub Desktop.
Save Artanis/3239577 to your computer and use it in GitHub Desktop.
Axiom of Choice?
import random
def choose(s, choice=None):
if choice is None:
choice = random.choice
if len(s) == 0:
raise KeyError("Cannot choose from empty set")
return choice(list(s))
def main(s):
if len(s) == 1:
print(choose(s))
else:
print(sorted(s))
if __name__ == "__main__":
import sys
main(frozenset(sys.argv[1:]))
import unittest
from operator import itemgetter
import axiom
class TestAxiom(unittest.TestCase):
def test_empty(self):
self.assertRaises(
KeyError,
axiom.choose, frozenset())
def test_errors(self):
s = frozenset({"a", "b", "c"})
self.assertRaises(
IndexError,
axiom.choose, s, itemgetter(4))
def test_chooser_pop(self):
s = frozenset({"a", "b", "c"})
self.assertEqual(
axiom.choose(s, list.pop),
list(s).pop())
def test_chooser_itemgetter(self):
s = frozenset({"a", "b", "c"})
self.assertEqual(
axiom.choose(s, itemgetter(1)),
list(s)[1])
def test_chooser_random(self):
s = frozenset({"a", "b", "c"})
self.assertTrue(
axiom.choose(s) in s)
@Artanis
Copy link
Author

Artanis commented Aug 4, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment