def safe(q1, q2): (q1x, q1y) = q1 (q2x, q2y) = q2 return q1x != q2x and q1y != q2y and abs(q1x - q2x) != abs(q1y - q2y) def possible_positions(current, n): return ((*current, y) for y in range(n) if all(safe((len(current), y), q) for q in enumerate(current))) def solutions_r(current, n = 8): if len(current) == n: yield current return for pos in possible_positions(current, n): yield from solutions_r(pos, n) def solutions(n = 8): return solutions_r((), n)