CS211 - Data Structure and Algorithms
Arrays and Lists
Lecture # 2
Nasir Uddin
1
Nasir Uddin
CS211 - Data Structure and Algorithms
Arrays
• A one-dimensional array is composed of multiple sequential elements
stored in contiguous bytes of memory and allows for random access
to the individual elements.
• Array contains fixed number of elements
• Individual elements within the array can be accessed directly form
their index values.
• Occupy less memory as compared to python list
• Internal processing is faster than python lists
2
Nasir Uddin
CS211 - Data Structure and Algorithms
Array ADT
3
Nasir Uddin
CS211 - Data Structure and Algorithms
Array Class in Python
# Fill a 1-D array with random values, then print them, one per line.
from array import Array
import random
# The constructor is called to create the array.
valueList = Array( 100 )
# Fill the array with random floating-point values.
for i in range( len( valueList ) ) :
valueList[ i ] = random.random()
# Print the values, one per line.
for value in valueList :
print( value )
4
Nasir Uddin
CS211 - Data Structure and Algorithms
Array Class in Python
#Count the number of occurrences of each letter in a text file.
from array import Array
# Create an array for the counters and initialize each element to 0.
theCounters = Array( 127 )
theCounters.clear( 0 )
# Open the text file for reading and extract each line from the file
# and iterate over each character in the line.
theFile = open( 'atextfile.txt', 'r' )
for line in theFile :
for letter in line :
code = ord( letter )
theCounters[code] += 1
# Close the file
theFile.close()
# Print the results. The uppercase letters have ASCII values in the
# range 65..90 and the lowercase letters are in the range 97..122.
for i in range( 26 ) :
print( "%c - %4d %c - %4d" % \
(chr(65+i), theCounters[65+i], chr(97+i), theCounters[97+i]) )
5
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the Array
6
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the Array
7
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the Array
8
Nasir Uddin
CS211 - Data Structure and Algorithms
Using the Array
import random
myarray = Array(10)
print("myarray legth is: ",len(myarray))
for i in range(len(myarray)):
item =random.random()
print("{} --> {:.2f}".format(i,item))
myarray[i]=item
print ("myarray initialized upto {} values".format(len(myarray)))
aindex = int(input("Enter the index value of array element: "))
print("The array index '{}' contains item {:.2f}".format(aindex,myarray[aindex]))
9
Nasir Uddin
CS211 - Data Structure and Algorithms
Using the Array - output
myarray length is: 10
0 --> 0.26
1 --> 0.21
2 --> 0.12
3 --> 0.12
4 --> 0.76
5 --> 0.73
6 --> 0.74
7 --> 0.86
8 --> 1.00
9 --> 0.48
myarray is initialized upto 10 values
Enter the index value of array element: 9
The array index '9' contains item 0.48
10
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List
• Python's list structure is a
mutable sequence container
that can change size as items are
added or removed.
• It is an abstract data type that is
implemented using an array
structure to store the items
contained in the list.
• For example
• pyList = [ 4, 12, 2, 34, 17 ]
11
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List – Appending item
• Appending an item
• pyList.append( 50 )
• Appending more items
• pyList.append( 18 )
• pyList.append( 64 )
• pyList.append( 6 )
• when the third statement is
executed, the array will have to be
expanded to make room for value 6.
• To allow for the expansion of the
list, the following steps have to be
performed:
12
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List – Appending item
• To allow for the expansion of the
list, the following steps have to
be performed:
1. a new array is created with
additional capacity,
2. the items from the original array
are copied to the new array,
3. the new larger array is set as the
data structure for the list, and
4. The original smaller array is
destroyed.
13
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List – Extending list
• A list can be appended to a
second list using the extend()
method as shown in the
following example:
• pyListA = [ 34, 12 ]
• pyListB = [ 4, 6, 31, 9 ]
• pyListA.extend( pyListB )
14
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List – Inserting items
• An item can be inserted anywhere
within the list using the insert()
method. In the following example:
• pyList.insert( 3, 79 )
a) the array elements are shifted to
the right one at a time, traversing
from right to left,
b) the new value is then inserted into
the array at the given position,
c) the result after inserting the item.
15
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List – Removing items
• An item can be removed from
any position within the list using
the pop() method.
• pyList.pop( 0 ) # remove the first item
a) a copy of the item is saved;
b) the array elements are shifted
to the left one at a time,
traversing left to right and
c) the size of the list is
decremented by one.
16
Nasir Uddin
CS211 - Data Structure and Algorithms
The Python List - List Slice
• Slicing is an operation that
creates a new list consisting of a
contiguous subset of elements
from the original list.
• The original list is not modified by
this operation.
• Instead, references to the
corresponding elements are
copied and stored in the new list.
• aSlice = pyList[2:3]
17
Nasir Uddin
CS211 - Data Structure and Algorithms
Two-Dimensional Arrays
• Two-dimensional array arrange
data in rows and columns.
• The individual elements are
accessed by specifying two
indices, one for the row and one
for the column, [i,j].
18
Nasir Uddin
CS211 - Data Structure and Algorithms
Two-Dimensional Arrays - ADT
19
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the 2-D Array
• an array of arrays to store the
elements of a 2-D array.
• Store each row of the 2-D array
within its own 1-D array.
• Then, another 1-D array is used
to store references to each of
the arrays used to store the row
elements.
20
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the 2-D Array
from myarray import Array
class Array2D:
def __init__(self, numRows, numCols):
self._theRows = Array(numRows)
for i in range(numRows):
self._theRows[i] = Array(numCols)
def numRows(self):
return len(self._theRows)
def numCols(self):
return len(self._theRows[0])
def clear(self, value):
for row in range(self.numRows()):
self._theRows[row].clear(value)
21
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the 2-D Array
def __getitem__(self, ndxTuple):
assert len(ndxTuple)==2, "Invalid number of array subscripts"
row = ndxTuple[0]
col = ndxTuple[1]
assert row >= 0 and row < self.numRows() \
and col >= 0 and col < self.numCols(),\
"Array subscript out of range"
the1dArray = self._theRows[row]
return the1dArray[col]
def __setitem__(self, ndxTuple, value):
assert len(ndxTuple)==2, "Invalid no of array subscripts"
row = ndxTuple[0]
col = ndxTuple[1]
assert row >=0 and row < self.numRows() \
and col >= 0 and col < self.numCols(), \
"Array subscript out of range."
the1dArray = self._theRows[row]
the1dArray[col] = value 22
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the 2-D Array
##-------------------------------------
## Implementation
##-------------------------------------
twoDArray = Array2D(3,3)
twoDArray.clear(0)
for i in range(twoDArray.numRows()):
print('')
for j in range(twoDArray.numCols()):
twoDArray[i,j] = int(input('enter value %d,%d = '%(i,j)))
print(‘Your 2D-Array is here:')
for i in range(twoDArray.numRows()):
print('')
for j in range(twoDArray.numCols()):
print(twoDArray[i,j],end =" ")
23
Nasir Uddin
CS211 - Data Structure and Algorithms
The Matrix Abstract Data Type
• a matrix is an rectangular grid or table of numerical values divided
into rows and columns.
24
Nasir Uddin
CS211 - Data Structure and Algorithms
The Matrix Abstract Data Type
• a matrix is an rectangular grid or table of numerical values divided
into rows and columns.
25
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the Matrix
26
Nasir Uddin
CS211 - Data Structure and Algorithms
Implementing the Matrix
27
Nasir Uddin
CS211 - Data Structure and Algorithms
Application: The Game of Life
1. If a cell is alive and has either two or three live neighbors, the cell remains alive
in the next generation. The neighbors are the eight cells immediately
surrounding a cell: vertically, horizontally, and diagonally.
2. A living cell that has no live neighbors or a single live neighbor dies from
isolation in the next generation.
3. A living cell that has four or more live neighbors dies from overpopulation in
the next generation.
4. A dead cell with exactly three live neighbors results in a birth and becomes
alive in the next generation. All other dead cells remain dead in the next
generation.
28
Nasir Uddin
CS211 - Data Structure and Algorithms
Application: The Game of Life
29
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Designing a Solution
30
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Designing a Solution
31
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Designing a Solution
32
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Designing a Solution
33
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Designing a Solution
34
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Implementation
35
Nasir Uddin
CS211 - Data Structure and Algorithms
The Game of Life - Implementation
36
Nasir Uddin
CS211 - Data Structure and Algorithms
Assignment – 1
1. Implement Matrix class that can perform following operations,
• Addition
• Subtraction
• Scaling
• Transpose
• Multiplication
• Inverse of Matrix
37
Nasir Uddin
CS211 - Data Structure and Algorithms
Assignment – 1
2. Implement the numLiveNeighbors() method of the
LifeGrid class.
3. Complete the implementation of the gameoflife.py program by
implementing the draw() function. The output should look
similar to the following, where dead cells are indicated using a
period and live cells are indicated using the @ symbol.
4. Modify the gameoflife.py program to prompt the user for the grid
size and the number of generations to evolve.
Due Date:
Submission: Microsoft Teams
38
Nasir Uddin