473,394 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Quesion on class.attributes assignment

Hi,

I am reading a python program now but I just cannot understand how the
values of class attributes are assigned and changed. Here is the original
code url:
http://agolb.blogspot.com/2006/01/su...in-python.html
Here I am concerned is how attribute matrix.rows is changed. Through pdb
debugging, I can see in line 97, once "self.solutions = set((val,))" is
executed, cell.row and matrix.rows will be updated. But I did not see any
assignment codes here. How could this change happen then? Thanks a lot!

John

# http://agolb.blogspot.com/2006/01/su...in-python.html
#!/usr/bin/env python
#
# sudoku-solver version 3
#
# Some ideas ripped-off from:
# http://www.linuxjournal.com/article/8729
# http://aspn.activestate.com/ASPN/Coo.../Recipe/440542
# Pavol solver in
#
http://groups.google.com/group/comp....87890f4c5e770d
#
# Copyright 2005 Ago,
# But you are free to copy, reuse, modify and distribute the code as you see
fit

from copy import deepcopy
class DeadEnd(Exception): pass
class Matrix:
def __init__(self, input):
self.rows = [[] for i in range(9)]
self.cols = [[] for i in range(9)]
self.submatrices = [[] for i in range(9)]
self.cells = [Cell(i,self) for i in range(81)]
self.subdiagonals = [self.rows[i][j+i%3] for i in range(9) for j in
[0,3,6]]
input = [s not in '-*' and int(s) or 0 for s in input if s in
'0123456789-*']
for cell,val in zip(self.cells, input):
if val: cell.setSolution(val)

def solve(self): #Brute-force solver
self.solveByReduction()
lensols=[(len(c.solutions),c.index) for c in self.cells if not
c.solved]
if not lensols: return True
unsolved = min(lensols)[1]
solutions = list(self.cells[unsolved].solutions)
for s in solutions:
tmpmatrix = deepcopy(self)
try:
tmpmatrix.cells[unsolved].setSolution(s)
if tmpmatrix.solve():
self.update(tmpmatrix)
return True
except DeadEnd: pass

def solveByReduction(self):
while True:
self.changed = False
for c in self.cells: c.solve()
for c in self.subdiagonals: c.skim()
if not self.changed: break

def update(self, m):
self.rows, self.cols, self.submatrices, self.cells,
self.subdiagonals=\
m.rows, m.cols, m.submatrices, m.cells, m.subdiagonals

def __str__(self):
return "\n".join(str([c for c in row ])[1:-1] for row in self.rows)
class Cell:
def __init__(self, index, matrix):
self.solved = False
self.matrix = matrix
self.index = index
self.row = matrix.rows[index/9]
self.col = matrix.cols[index%9]
self.submatrix = matrix.submatrices[((index/9)/3)*3+(index%9)/3]
self.row.append(self)
self.col.append(self)
self.submatrix.append(self)
self.solutions = set(range(1,10))

def solve(self):
if self.solved: return
if len(self.solutions) == 1:
self.setSolution(self.solutions.pop())
else:
sol = set()
for cells in [self.row, self.col, self.submatrix]:
otherSolutions = self.cells2sols(cells, self)
sol |= (self.solutions - otherSolutions)
if len(sol) 1: raise DeadEnd()
if sol: self.setSolution(sol.pop())

def skim(self):
submatrix = set(self.submatrix)
for r in (set(self.row), set(self.col)):
subset1 = submatrix - r
subset2 = r - submatrix
solsNotIn1 = set(range(1,10)) - self.cells2sols(subset2)
solsNotIn2 = set(range(1,10)) - self.cells2sols(subset1)
for c in subset1: c.delSolutions(solsNotIn1)
for c in subset2: c.delSolutions(solsNotIn2)

def setSolution(self, val):
self.solved = True
self.solutions = set((val,))
self.matrix.changed = True
for other in self.row+self.col+self.submatrix:
if other is self: continue
if other.solutions == self.solutions: raise DeadEnd()
other.delSolutions(self.solutions)

def delSolutions(self, val):
if not self.solved and val & self.solutions:
self.solutions -= val
self.matrix.changed = True
if not self.solutions: raise DeadEnd()

def __repr__(self):
return str(self.solved and list(self.solutions)[0] or
list(self.solutions))

@staticmethod
def cells2sols(cells, exclude=None):
return set(s for c in cells for s in c.solutions if c is not
exclude)
if __name__ == "__main__":
input ='''
1,0,0,0,0,0,0,0,2
0,9,0,4,0,0,0,5,0
0,0,6,0,0,0,7,0,0
0,5,0,9,0,3,0,0,0
0,0,0,0,7,0,0,0,0
0,0,0,8,5,0,0,4,0
7,0,0,0,0,0,6,0,0
0,3,0,0,0,9,0,8,0
0,0,2,0,0,0,0,0,1
'''
matrix = Matrix(input)
matrix.solve()
print matrix

Jul 25 '08 #1
0 809

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Kerry Neilson | last post by:
Hi, Really hung up on this one. I'm trying to get all the fields of a dictionary to be unique for each class: class A { my_dict = dict_entry = { 'key1':0, 'key2':0 } __init__(self): for...
8
by: Mark English | last post by:
I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window...
166
by: Graham | last post by:
This has to do with class variables and instances variables. Given the following: <code> class _class: var = 0 #rest of the class
27
by: guoliang | last post by:
help: #include<stdio.h> int main(void) { int a; char b; printf("int=");
5
by: Bob B. | last post by:
I've been playing with descriptors lately. I'm having one problem I can't seem to find the answer to. I want to assign a descriptor to a list of attributes. I know I should be able to add these...
13
by: globalrev | last post by:
wassup here? 7 Traceback (most recent call last): File "C:\Python25\myPrograms\netflix\netflix.py", line 22, in <module> print cust1.getID() AttributeError: 'NoneType' object has no...
13
by: John Dann | last post by:
A Python newbie, but some basic understanding of how classes, objects etc work in eg VB.Net. However, I'm struggling a little to translate this knowledge into the Python context. I'm trying to...
0
by: Terry Reedy | last post by:
John Hanks wrote: Newsreaders do not typically have line counters. I presume you are referring to def setSolution(self, val): self.solved = True self.solutions = set((val,))...
11
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.