Skip to content

Instantly share code, notes, and snippets.

@MattDiesel
Created November 26, 2019 13:40
Show Gist options
  • Save MattDiesel/6bb4ce685015b475dd0c985312cc7c6d to your computer and use it in GitHub Desktop.
Save MattDiesel/6bb4ce685015b475dd0c985312cc7c6d to your computer and use it in GitHub Desktop.
import random
peeps = {
'Matt': '',
'Al': '',
'Bebop': '',
'Mum': '',
'Dad': '',
'Gramps': ''
}
# Generate all permutations
def all_perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
ns = list(peeps.keys())
names = list(range(1,len(peeps)+1))
possible = list(all_perms(names))
# Take out any non-derangements
possible2 = filter(lambda perm: not any([i for i, j in zip(perm, names) if i == j]), possible)
# Take out any cycles
possible3 = filter(lambda perm: not any(i for i in perm if perm[perm[i-1]-1] == i), possible2)
# Take out any combinations where Grampa isn't buying for Mum
gramps = ns.index('Gramps')+1
mum = ns.index('Mum')+1
possible4 = filter(lambda perm: perm[gramps-1] == mum, possible3)
# Select one of them at random
choice = random.choice(list(possible4))
final_list = [ns[i-1] for i in choice]
for i, j in zip(ns, final_list):
print('{} = {}'.format(i, j))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment