4 ms·
8-queen puzzle in 1 line of Python with pretty print _=[__import__('sys').stdout.write("\n".join('.' * i + 'Q' + '.' * (8-i-1) for i in vec) + "\n===\n") for v
by est 11y ago
8-queen puzzle in 1 line of Python with pretty print
_=[__import__('sys').stdout.write("\n".join('.' * i + 'Q' + '.' * (8-i-1) for i in vec) + "\n===\n") for vec in __import__('itertools').permutations(xrange(8)) if 8 == len(set(vec[i]+i for i in xrange(8))) == len(set(vec[i]-i for i in xrange(8)))]
- JoeAltmaier 11y agoAh! That's similar to the solution I used in 1980 to solve this problem for a Byte Magazine contest. Except I trimmed the search tree by aborting the permutation recursion each time the condition failed in a previous step. It took 21 minutes to find and print all the solutions, if I remember right. But that was in Basic on a machine that ran at 10MHz.
- e12e 11y agoI tried to make that a little more readable, and converted it to py3 -- This one produces the same output with python3, as your one-liner with python2: #!/usr/bin/env python3 from itertools import permutations as p for vec in p(range(8)): if 8 == len(set(vec[i]+i for i in range(8))) \ == len(set(vec[i]-i for i in range(8))): print("\n".join( '.' * i + 'Q' + '.' * (8-i-1) for i in vec), end="\n===\n") The string construction could/should probably also be refactored a bit, but at least this version I have a hope of following the logic... :-)