Skip to content

Commit ba9ea75

Browse files
committed
rearranged
0 parents  commit ba9ea75

9 files changed

+802
-0
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
data_structure_and_algorithm_using_python
2+
=========================================
3+
4+
code in book "data structure and algorithm using python"

gameoflife.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Program for playing the game of Life.
2+
from life import LifeGrid
3+
4+
# Define the initial configuration of live cells.
5+
INIT_CONFIG = [ (1, 2), (2, 1), (2, 2), (2, 3) ]
6+
7+
# Set the size of the grid.
8+
GRID_WIDTH = 5
9+
GRID_HEIGHT = 5
10+
11+
# Indicate the number of generations.
12+
NUM_GENS = 8
13+
14+
def main():
15+
# Construct the game grid and confiture it.
16+
grid = LifeGrid( GRID_WIDTH, GRID_HEIGHT)
17+
grid.configure( INIT_CONFIG )
18+
19+
# Play the game.
20+
draw( grid )
21+
for i in range( NUM_GENS ):
22+
evolve( grid )
23+
draw( grid )
24+
25+
# Generates the next generation of organisms.
26+
def evolve( grid ):
27+
# List for storing the live cells of the next generation.
28+
liveCells = list()
29+
30+
# Iterate over the elements of the grid.
31+
for i in range( grid.numRows() ):
32+
for j in range( grid.numCols() ):
33+
34+
#print '( ' + str(i) + ', ' + str(j) + ' )',
35+
36+
# Determine the number of live neighbors for this cell.
37+
neighbors = grid.numLiveNeighbors( i, j )
38+
39+
#print neighbors
40+
41+
# Add the (i, j) tuple to liveCells if this cell contains
42+
# a live organisms in the next generation.
43+
if (neighbors == 2 and grid.isLiveCell(i, j)) or (neighbors == 3):
44+
liveCells.append( (i, j) )
45+
46+
# Reconfigure the grid using the liveCells coord list.
47+
grid.configure( liveCells )
48+
49+
# Prints a text-based representation of the game grid.
50+
def draw( grid ):
51+
grid.print_config()
52+
print ""
53+
54+
# Executes the main routine
55+
main()

life.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Implements the LifeGrid ADT for the use with the game of Life.
2+
from myarray import myArray2D
3+
4+
class LifeGrid:
5+
# Defines constants to represent the cell states.
6+
DEAD_CELL = 0
7+
LIVE_CELL = 1
8+
9+
# Creates the game grid and initializes the cells to dead.
10+
def __init__( self, numRows, numCols ):
11+
# Allocate the 2-D array for the grid.
12+
self._grid = myArray2D( numRows, numCols )
13+
# Clear the grid and set all cells to dead.
14+
self.configure( list() )
15+
16+
# Returns the number of rows in the grid.
17+
def numRows( self ):
18+
return self._grid.numRows()
19+
20+
# Returns the number of columns in the grid.
21+
def numCols( self ):
22+
return self._grid.numCols()
23+
24+
# Configures the grid to contain the given live cells.
25+
def configure( self, coordList ):
26+
# Clear the game grid.
27+
for i in range( self.numRows() ):
28+
for j in range( self.numCols() ):
29+
self.clearCell(i, j)
30+
31+
# Set the indicated cells to be alive
32+
for coord in coordList:
33+
self.setCell( coord[0], coord[1])
34+
35+
# Does the indicated cell contain a live organism?
36+
def isLiveCell( self, row, col ):
37+
return self._grid[row, col] == self.LIVE_CELL
38+
39+
# Clears the indicated cell by setting it to dead.
40+
def clearCell( self, row, col ):
41+
self._grid[row, col] = self.DEAD_CELL
42+
43+
def setCell( self, row, col ):
44+
self._grid[row, col] = self.LIVE_CELL
45+
46+
# Returns the number of live neighbors for the given cell.
47+
def numLiveNeighbors( self, row, col ):
48+
#print str(row) + ' , ' + str(col)
49+
alive_cnt = 0
50+
for i in [-1, 0, 1]:
51+
for j in [-1, 0, 1]:
52+
if row + i >= 0 and row + i < self.numRows() and col + j >= 0 and col + j < self.numCols():
53+
if self.isLiveCell(row+i, col+j):
54+
alive_cnt += 1
55+
#print '( ' + str(row+i) + ', ' + str(col+j) + ' ): ' + 'YES'
56+
return alive_cnt - self.isLiveCell(row, col)
57+
58+
# Prints the current configure
59+
def print_config( self ):
60+
for i in range( self.numRows() ):
61+
for j in range( self.numCols() ):
62+
print self._grid[i, j],
63+
print ""
64+
65+
if __name__ == '__main__':
66+
init_grid = LifeGrid(5, 5)
67+
init_grid.print_config()
68+
69+
print ""
70+
71+
#for i in range( init_config.numRows() ):
72+
# for j in range( init_config.numRows() ):
73+
# init_config.setCell(i, j)
74+
init_grid.configure([ (1, 2), (2, 1), (2, 2), (2, 3) ])
75+
init_grid.print_config()
76+
print init_grid.numLiveNeighbors(1, 2)
77+
#for i in range(5):
78+
# for j in range(5):
79+
# print '( ' + str(i) + ', ' + str(j) + ' )',
80+
# print init_grid.numLiveNeighbors(i, j)
81+
82+

linearmap.py

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Implementation of Map ADT using a single list.
2+
class myMap:
3+
# Creates an empty map instance.
4+
def __init__( self ):
5+
self._entryList = list()
6+
7+
# Returns the number of entries in the map.
8+
def __len__( self ):
9+
return len( self._entryList )
10+
11+
# Determines if the map contains the given key.
12+
def __contains__( self, key ):
13+
ndx = self._findPosition( key )
14+
return ndx is not None
15+
16+
# Adds a new entry to the map if the key does exist. Otherwise, the
17+
# new value replaces the current value assocaited with the key.
18+
def add( self, key, value ):
19+
ndx = self._findPosition( key )
20+
if ndx is not None:
21+
self._entryList[ndx].value = value
22+
return False
23+
else:
24+
entry = _MapEntry( key, value )
25+
self._entryList.append( entry )
26+
return True
27+
28+
# Returns the value associated with the key.
29+
def Valueof( self, key ):
30+
ndx = self._findPosition( key )
31+
assert ndx is not None, "Invalid map key. "
32+
return self._entryList[ndx].value
33+
34+
# Removes the entry associated with the key.
35+
def remove( self, key ):
36+
ndx = self._findPosition( key )
37+
assert ndx is not None, "Invalid map key. "
38+
self._entryList.pop( ndx )
39+
40+
# Returns an iterator for traversing the keys in the map.
41+
def __iter__( self ):
42+
return _MapIterator( self._entryList )
43+
44+
# Helper method used to find the index position of a category. If the
45+
# key is not found, None is returned.
46+
def _findPosition( self, key ):
47+
for i in range( len(self) ):
48+
if self._entryList[i].key == key:
49+
return i
50+
return None
51+
52+
# Storage class for holding the key/value pairs.
53+
class _MapEntry:
54+
def __init__( self, key, value ):
55+
self.key = key
56+
self.value = value
57+
58+
# An iterator for the Map ADT
59+
class _MapIterator:
60+
def __init__( self, theEntryList ):
61+
self._entryItems = theEntryList
62+
self._curItem = 0
63+
64+
def __iter__( self ):
65+
return self
66+
67+
def next( self ):
68+
if self._curItem < len( self._entryItems ):
69+
entry = self._entryItems[ self._curItem ]
70+
self._curItem += 1
71+
return entry
72+
else:
73+
raise StopIteration
74+
75+
76+
if __name__ == '__main__':
77+
StuMap = myMap()
78+
print StuMap
79+
80+
StuMap.add('0301', 'Bell')
81+
StuMap.add('0302', 'Tang')
82+
StuMap.add('0303', 'Liu')
83+
StuMap.add('0304', 'James')
84+
print StuMap
85+
86+
for entry in StuMap:
87+
print entry.key,
88+
print entry.value
89+
print ""
90+
91+
StuMap.add('0303', 'Ronadol')
92+
for entry in StuMap:
93+
print entry.key,
94+
print entry.value
95+
print ""

linearset.py

+139
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# Implementation of the Set ADT container using a Python list
2+
class mySet:
3+
# Creates an empty set instance
4+
def __init__( self ):
5+
self._theElements = list()
6+
7+
# Returns the number of items in the set.
8+
def __len__( self ):
9+
return len( self._theElements )
10+
11+
# Determines if an element is in the set.
12+
def __contains__( self, element ):
13+
return element in self._theElements
14+
15+
# Adds a new unique element to the set.
16+
def add( self, element ):
17+
if element not in self:
18+
self._theElements.append( element )
19+
20+
# Removes an element from the set.
21+
def remove( self, element ):
22+
assert element in self, "The element must be in the set."
23+
self._theElements.remove( item )
24+
25+
# Determins if two sets are equal.
26+
def __eq__( self, setB):
27+
if len( self ) != len( setB ):
28+
return False
29+
else:
30+
return self.isSubsetOf( setB )
31+
32+
# Determins if this set is a subset of setB.
33+
def isSubsetOf( self, setB ):
34+
for element in self:
35+
if element not in setB:
36+
return False
37+
return True
38+
39+
# Creates a new set from the union of this set and setB
40+
def union( self, setB ):
41+
newSet = mySet()
42+
newSet._theElements.extend( self._theElements )
43+
for element in setB:
44+
if element not in self :
45+
newSet._theElements.append( element )
46+
return newSet
47+
48+
# Creates a new set from the intersection: self set and setB.
49+
def interset( self, setB ):
50+
newSet = mySet()
51+
for element in self:
52+
if element in setB:
53+
newSet._theElements.append( element )
54+
return newSet
55+
56+
# Creates a new set from the difference: self set and setB.
57+
def difference( self, setB ):
58+
newSet = mySet()
59+
for element in self:
60+
if element not in setB:
61+
newSet._theElements.append( element )
62+
return newSet
63+
64+
# Returns an iterator for traversing the list of items.
65+
def __iter__( self ):
66+
return _SetIterator( self._theElements )
67+
68+
# An iterator for the Set ADT.
69+
class _SetIterator:
70+
def __init__( self, theSet ):
71+
self._setRef = theSet
72+
self._curNdx = 0
73+
74+
def __iter__( self ):
75+
return self
76+
77+
def next( self ):
78+
if self._curNdx < len( self._setRef ):
79+
entry = self._setRef[ self._curNdx ]
80+
self._curNdx += 1
81+
return entry
82+
else:
83+
raise StopIteration
84+
85+
86+
if __name__ == '__main__':
87+
mySetA = mySet()
88+
mySetA.add(6)
89+
mySetA.add(3)
90+
mySetA.add(2)
91+
mySetA.add(1)
92+
mySetA.add(3)
93+
print "Set A: "
94+
for ele in mySetA:
95+
print ele,
96+
print ""
97+
98+
mySetB = mySet()
99+
mySetB.add(4)
100+
mySetB.add(1)
101+
mySetB.add(7)
102+
mySetB.add(2)
103+
print "Set B: "
104+
for ele in mySetB:
105+
print ele,
106+
print ""
107+
108+
# Set Union
109+
mySetC = mySetA.union(mySetB)
110+
print "A + B: "
111+
for ele in mySetC:
112+
print ele,
113+
print ""
114+
115+
# Set Interset
116+
mySetD = mySetA.interset(mySetB)
117+
print "interset(A, B)"
118+
for ele in mySetD:
119+
print ele,
120+
print ""
121+
122+
mySetE = mySetB.interset(mySetA)
123+
print "interset(B, A)"
124+
for ele in mySetE:
125+
print ele,
126+
print ""
127+
128+
# Set difference
129+
mySetF = mySetA.difference(mySetB)
130+
print "A - B: "
131+
for ele in mySetF:
132+
print ele,
133+
print ""
134+
135+
mySetG = mySetB.difference(mySetA)
136+
print "B - A: "
137+
for ele in mySetG:
138+
print ele,
139+
print ""

0 commit comments

Comments
 (0)