Skip to content

Instantly share code, notes, and snippets.

@benjamingeiger
Last active August 29, 2015 14:19
Show Gist options
  • Save benjamingeiger/f2d8840346b75146fccd to your computer and use it in GitHub Desktop.
Save benjamingeiger/f2d8840346b75146fccd to your computer and use it in GitHub Desktop.
Solution to the "Cheryl's Birthday" problem in Python.
#!/usr/bin/python
#
# Copyright (c) 2015 Benjamin Geiger <begeiger@mail.usf.edu>
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from collections import defaultdict
def unique(candidates, key=lambda x: x[0]):
options = defaultdict(set)
for c in candidates:
options[key(c)].add(c)
results = set()
for k in options.keys():
if len(options[k]) == 1:
results |= options[k]
return results
def main():
candidates = set([("May", 15), ("May", 16), ("May", 19),
("June", 17), ("June", 18),
("July", 14), ("July", 16),
("August", 14), ("August", 15), ("August", 17)])
# Albert: "I don't know when your birthday is, but I know Bernard doesn't know, either."
uniquemonths = [m for m, d in unique(candidates, key=lambda x: x[1])]
candidates = {c for c in candidates if c[0] not in uniquemonths}
# Bernard: "I didn't know originally, but now I do."
uniquedays = [d for m, d in unique(candidates, key=lambda x: x[1])]
candidates = {c for c in candidates if c[1] in uniquedays}
# Albert: "Well, now I know, too!"
uniquemonths = [m for m, d in unique(candidates, key=lambda x: x[0])]
candidates = {c for c in candidates if c[0] in uniquemonths}
if len(candidates) != 1:
print("We dun goof'd.")
else:
print(candidates.pop())
if __name__ == "__main__":
main()
# vim: set et sw=4 ts=4:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment