-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixins.py
68 lines (40 loc) · 1.62 KB
/
mixins.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class BacktrackingMixin:
"""
Mixing to use backtracking algorithm to solve the queens problem borrowed from this site https://goo.gl/5ZWtrh and refactorized with OOP.
Also, I created the get_positions() functions, in order to return a list of tuples printable by the parents print_solutions() function
# """
def solve_backtracking(self, n):
"""
n = Integer
Receive a number of queens and returns a list of tuples printable by the parent's respective function.
"""
solutions = [[]]
for row in range(n):
solutions = (solution+[i+1] for solution in solutions for i in range(n) if not self.under_attack(i+1, solution))
return self.get_positions(solutions)
def under_attack(self, col, queens):
return col in queens or \
any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))
def get_positions(self, answers):
"""
For the sake of this problem I created this function in order to make this mixin compatible with the print function of the parent class
"""
results = []
final_results = []
while True:
try:
result = list(enumerate(next(answers),start=1))
results.append(result)
except:
break
for result in results:
new_set = tuple(result[i][1]-1 for i in range(len(result)))
final_results.append(new_set)
return final_results
def print_solutions(self):
N=self.size
solutions = self.solutions
for solution in solutions:
sol = solutions.index(solution) + 1
print('Solution {}: {} \n'.format(sol, solution))
print("\n".join(' o ' * i + ' X ' + ' o ' * (N-i-1) for i in solution) + "\n\n")