Created
December 30, 2018 21:36
-
-
Save cepe/2257f2d519442f8bc730a914d8188f69 to your computer and use it in GitHub Desktop.
Rozwiązanie łamigłówki: https://penszko.blog.polityka.pl/2018/12/28/kwadrat-z-kwadratami/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import math | |
| def without_zeros(nums): | |
| return [num for num in nums if "0" not in num] | |
| def squares(n): | |
| beginning = int(math.ceil(math.sqrt(10 ** (n - 1)))) | |
| ending = int(math.ceil(math.sqrt(10 ** n - 1))) | |
| return without_zeros([str(i * i) for i in xrange(beginning, ending)]) | |
| def squares_starting_on(l, sqs): | |
| return [s for s in sqs if s.startswith(l)] | |
| class Solver(object): | |
| def __init__(self, size): | |
| self.size = size | |
| self.sqs = squares(size) | |
| def solve(self): | |
| return self.solve_rec(1) | |
| def solve_rec(self, i, starting_at='', solution=None): | |
| if solution is None: | |
| solution = [] | |
| for s in squares_starting_on(starting_at, self.sqs): | |
| if i != self.size: | |
| new_solution = solution + [s] | |
| new_starting_at = "".join([num[i] for num in new_solution]) | |
| for sol in self.solve_rec(i + 1, new_starting_at, new_solution): | |
| yield sol | |
| else: | |
| yield solution + [s] | |
| def print_solution(self): | |
| for sol in self.solve(): | |
| print "-".join(sol) | |
| for problem_size in xrange(3, 10): | |
| print "Solving problem of size {}:".format(problem_size) | |
| Solver(problem_size).print_solution() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment