f | from itertools import permutations, combinations_with_replacement | f | from itertools import permutations, combinations_with_replacement |
| | | |
| def empty_box(box): | | def empty_box(box): |
| for car, student in box: | | for car, student in box: |
| car.remove_student(student) | | car.remove_student(student) |
n | | n | |
| def check_satisfiablity(students): | | |
| for student in students: | | |
| if not student.is_comfy(): | | |
| return False | | |
| return True | | |
| | | |
| def organize(cars, students): | | def organize(cars, students): |
| #generate a sequence of students positions to be tested | | #generate a sequence of students positions to be tested |
| for config in list(permutations(students)): | | for config in list(permutations(students)): |
| # for this sequence generate a distribution of the number of students in each car | | # for this sequence generate a distribution of the number of students in each car |
| # x1 +x2+....+xk=n assuming len(cars)=k,len(students)=n | | # x1 +x2+....+xk=n assuming len(cars)=k,len(students)=n |
| for combo in combinations_with_replacement(range(len(cars)), len(students)): | | for combo in combinations_with_replacement(range(len(cars)), len(students)): |
| box = [] | | box = [] |
| std_pos = 0 | | std_pos = 0 |
n | | n | works = True |
| # go through the generated car positions and distribute students | | # go through the generated car positions and distribute students |
| for car_pos in combo: | | for car_pos in combo: |
| try: | | try: |
| cars[car_pos].add_student(students[config[std_pos]]) | | cars[car_pos].add_student(students[config[std_pos]]) |
| except EnvironmentError: | | except EnvironmentError: |
| # if reached here the combo is not a solution | | # if reached here the combo is not a solution |
| empty_box(box) | | empty_box(box) |
n | | n | works = False |
| break | | break |
| else: | | else: |
n | | n | # if student is not OK then just stop the exploration |
| | | if not students[config[std_pos]].is_comfy(): |
| | | empty_box(box) |
| | | works = False |
| | | break |
| box.append((cars[car_pos], students[config[std_pos]])) | | box.append((cars[car_pos], students[config[std_pos]])) |
| std_pos += 1 | | std_pos += 1 |
t | # when done check the combo | t | if works: |
| if check_satisfiablity(students): | | |
| return True | | return True |
| return False | | return False |