Completed
from itertools import combinations
import numpy as np
import string
def get_maxhappiness(results):
max_happiness = max(results)
index = results.index(max_happiness)
#Printing the result! (There may be more than one best result, but this will only show 1)
print "Optimal Groups: Point value of",max_happiness,"\n",groups[index],"\n", anti_groups[index]
results[index] = 0
return results
def calculateHappiness(points,group):
happiness = 0
for i in range(len(group)):
person_prefs = points[group[i]]
others = group[i:] + group[:i]
for other in others:
happiness += person_prefs[other]
return happiness
if __name__ == "__main__":
people = string.letters[26:44]
groups = list(combinations(people,9))
anti_groups = [tuple(set(people).difference(set(x))) for x in groups]
#Making fake results
survey_results = dict()
for person in people:
results = dict(zip(people,np.random.randint(0,10,size=(len(people)))))
results[person] = 0
survey_results[person] = results
#Printing Survey Results
for name,values in survey_results.items():
print "Student:", name, "has preferences:", values
#Calculating happiness for every group
results = []
for i in range(len(groups)):
results.append(calculateHappiness(survey_results,groups[i])+calculateHappiness(survey_results,anti_groups[i]))
#Finding the largest happiness value
top_n = 5
while top_n > 0:
results = get_maxhappiness(results)
top_n -= 1
Yields:
...
Student: N has preferences: {'A': 5, 'C': 5, 'B': 0, 'E': 0, 'D': 3, 'G': 6, 'F'
: 8, 'I': 8, 'H': 3, 'K': 1, 'J': 4, 'M': 4, 'L': 9, 'O': 0, 'N': 0, 'Q': 3, 'P'
: 2, 'R': 2}
Student: Q has preferences: {'A': 9, 'C': 0, 'B': 3, 'E': 4, 'D': 3, 'G': 2, 'F'
: 2, 'I': 7, 'H': 5, 'K': 2, 'J': 3, 'M': 0, 'L': 9, 'O': 2, 'N': 5, 'Q': 0, 'P'
: 2, 'R': 0}
Student: P has preferences: {'A': 2, 'C': 3, 'B': 0, 'E': 9, 'D': 3, 'G': 6, 'F'
: 7, 'I': 1, 'H': 7, 'K': 9, 'J': 7, 'M': 4, 'L': 8, 'O': 2, 'N': 6, 'Q': 5, 'P'
: 0, 'R': 7}
Student: R has preferences: {'A': 5, 'C': 3, 'B': 7, 'E': 1, 'D': 5, 'G': 6, 'F'
: 1, 'I': 6, 'H': 9, 'K': 9, 'J': 3, 'M': 6, 'L': 8, 'O': 8, 'N': 5, 'Q': 1, 'P'
: 3, 'R': 0}
Optimal Groups: Point value of 709
('A', 'B', 'F', 'G', 'J', 'K', 'O', 'Q', 'R')
('C', 'E', 'D', 'I', 'H', 'M', 'L', 'N', 'P')
(x4)