Only 30 lines of Python code are used to demonstrate the X algorithm and 30 lines of python

Source: Internet
Author: User

Only 30 lines of Python code are used to demonstrate the X algorithm and 30 lines of python

If you are interested in the sudoku solution, you may have heard of the exact coverage problem. Given the collection Y of the complete set X and the subset Y of X, there is a subset Y * of Y, which makes Y * a split of X.

Here is an example of Python writing.
 

X = {1, 2, 3, 4, 5, 6, 7}Y = {  'A': [1, 4, 7],  'B': [1, 4],  'C': [4, 5, 7],  'D': [3, 5, 6],  'E': [2, 3, 6, 7],  'F': [2, 7]}

The only solution for this example is ['B', 'D', 'F'].

Exact coverage is NP-complete ). The X algorithm was invented and implemented by Daniel Gartner. He proposed an efficient implementation technology called Dance chain, which uses a two-way linked list to represent the matrix of the problem.

However, the implementation of dance chains may be cumbersome and difficult to write correctly. Next is the time to show the Python miracle! One day I decided to write the X Algorithm in Python, and I came up with an interesting dance chain variant.
Algorithm

The main idea is to use a dictionary instead of a two-way linked list to represent a matrix. We already have Y. From it, we can quickly access the column elements of each row. Now we need to generate a reverse table of rows. In other words, we can quickly access row elements from columns. To achieve this goal, we convert X into a dictionary. In the above example, it should be written
 

X = {  1: {'A', 'B'},  2: {'E', 'F'},  3: {'D', 'E'},  4: {'A', 'B', 'C'},  5: {'C', 'D'},  6: {'D', 'E'},  7: {'A', 'C', 'E', 'F'}}

Readers with sharp eyes can notice that this is slightly different from Y's representation. In fact, we need to be able to quickly delete and Add rows to each column, which is why we use a set. On the other hand, Gartner did not mention this. In fact, all rows in the entire algorithm remain unchanged.

The following is the algorithm code.
 

def solve(X, Y, solution=[]):  if not X:    yield list(solution)  else:    c = min(X, key=lambda c: len(X[c]))    for r in list(X[c]):      solution.append(r)      cols = select(X, Y, r)      for s in solve(X, Y, solution):        yield s      deselect(X, Y, r, cols)      solution.pop() def select(X, Y, r):  cols = []  for j in Y[r]:    for i in X[j]:      for k in Y[i]:        if k != j:          X[k].remove(i)    cols.append(X.pop(j))  return cols def deselect(X, Y, r, cols):  for j in reversed(Y[r]):    X[j] = cols.pop()    for i in X[j]:      for k in Y[i]:        if k != j:          X[k].add(i)

There are only 30 rows!
Format input

Before solving the problem, we need to convert the input to the format described above. Easy to handle

X = {j: set(filter(lambda i: j in Y[i], Y)) for j in X}

But this is too slow. If X is m and Y is n, the number of iterations is m * n. In this example, the size of the sudoku lattice is N, which requires N ^ 5 times. We have a better solution.
 

X = {j: set() for j in X}for i in Y:  for j in Y[i]:    X[j].add(i)

This is the complexity of O (m * n), but it is the worst case. On average, it performs much better because it does not need to traverse all spaces. In the example of DT alone, there are exactly four entries in each row in the matrix, regardless of the size, so it has the complexity of N ^ 3.
Advantages

  • Simple: you do not need to construct complex data structures. All the structures used in Python are provided.
  • Readability: the first example above is directly copied from the Wikipedia example!
  • Flexibility: it can be easily expanded to solve the problem of data independence.

Solving Sudoku

What we need to do is to describe the uniqueness as accurate coverage. There is a complete Sudoku solution code, which can handle any size, 3 × 3, 5 × 5, even 2 × 3, all code is less than 100 lines, and contains doctest! (Thanks to Winfried Plappert and David Goodger for their comments and suggestions)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.