Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. #! /usr/bin/python
  2.  
  3. # "secret santa" gift pairs: sets of spouses, who buys for who?
  4. # can't have a spouse buying for spouse, and can't have person
  5. # buy for self.
  6. # brute force algorithm below is probably easiest. With only
  7. # a few values, performance doesn't matter, so this worked ok,
  8. # but I think that probably setting them up as disjoint sets or
  9. # just a dictionary/mapping with a key for each user and
  10. # possible matchups as a list as the value and then just
  11. # randomizing would be faster.
  12.  
  13. import pprint, random
  14.  
  15. pairs = (('joe', 'sandy'),
  16.  ('michael', 'cheryl'),
  17.  ('jamieson', 'jennifer'),
  18.  ('matthew', 'dannii'))
  19. # convert to straight list
  20. all = " ".join([" ".join(pair) for pair in pairs]).split()
  21.  
  22. def randomize_sample(sample):
  23.     while True:
  24.         newsample = zip(random.sample(sample, len(sample)),random.sample(sample,len(sample)))
  25.         if [(a,b) for a,b in newsample if a==b]:
  26.             # skip this matchup, someone is buying for themselves
  27.             continue
  28.         if [pair for pair in newsample if pair in pairs]:
  29.             # skip this matchup, someone has their spouse
  30.             continue
  31.         if [(a,b) for (a,b) in newsample if (b,a) in pairs]:
  32.             # skip this matchup, someone has their spouse (reversed pair)
  33.             continue
  34.         # we made it this far, this sample is ok!
  35.         break
  36.     return newsample
  37.  
  38. for i in xrange(10):
  39.     sample = randomize_sample(all)
  40.     print "\n%s:\n" % (i+1) +  "\n".join([": ".join(pair) for pair in sample])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement