Array structure is the most basic structure to store data. In this section we will learn the basics of Arrays and implement an array structure for a one-dimensional array. Then we will create two dimensional array.
Array structure is very similar to Python's list structure, however there are two major differences between the array and the list.
Array is best usable when the number of elements are known up front.
Array structure found in most programming languages as primitive type. Now we will define Array ADT to represent a one-dimensional array for use in Python that works similarly to arrays found in other languages.
Array ADT Definition:
Array(size)
: Create one-dimensional array consisting of size
elements with each element initially set to None. size
must be greater than zero. length()
: Returns the length or number of elements in the arraygetitem(index)
: Returns the value stored in the array at element position index
.(Must be in valid range.)setitem(index, value)
: Modifies the contents of the array element at position index
to contain value
. clearing(value)
: Clears the array by setting every element to value
iterator()
: Creates and returns an iterator that can be used to traverse the elements of the array.In our ADT definition we used basic hardware level implementation and made it more abstract by adding iterator and optain size, set value, etc.
Now we created our ADT in file called array.py
, let's use it to fill our array with random values and print them one per line.
In [ ]:
from array_class import Array1D
import random
# Array valueList created with size of 100
valueList = Array1D(100)
# Filling 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)
Now our Array ADT is working like charm let's use it with somewhat better implementation. Let's count the number of occurrences of each letter in a text file using Array ADT:
In [3]:
from array_class import Array1D
# Array theCounters created with size of 127 (ASCII characters)
theCounters = Array1D(127)
# theCounters elements initialized to 0
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('textfile.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
# 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]))
To implement our array ADT we will use built-in module called ctypes
which will give us an opportunity to implement hardware-supported array structure.
The ctypes
module provides a tecnique for creating arrays that can store References to Python objects.
In [7]:
import ctypes
ArrayType = ctypes.py_object * 5
slots = ArrayType()
slots[0]
Now if we want to print the value of the first item in the recently created array slots, we get ValueError, which says we don't have value for referenced position. But if we assign values...
In [8]:
slots[1] = 12
slots[3] = 44
slots[4] = 59
slots[3] = None
In [12]:
print slots[1]
In [11]:
print slots[3]
In [13]:
print slots[2]
The size of the array never change which is really useful when you know the size of the array you will need. For class definition of array ADT check: array_class.py
Some problems require us to make more then 1 dimensions, in this case two-dimensional arrays are handy.
We will define Array2D ADT for creating 2-D arrays, we will use some of the features directly from Array1D ADT.
You can find the implementation in array_class.py
file.
Now let's talk about the usage of 2D arrays. Following snippets shows how to read text file and store the grades of students in the 2-D array.
In [5]:
from array_class import Array2D
filename = "StudentGrades.txt"
# Open the text file for reading.
gradeFile = open(filename, "r")
# Extract the first two values which indicate the size of the array.
numStudents = int(gradeFile.readline())
numExams = int(gradeFile.readline())
# Create the 2-D array to store the grades.
examGrades = Array2D(numStudents, numExams)
# Extract the grades from the remaining lines.
i = 0
for student in gradeFile:
grades = student.split()
# print grades
for j in range(numExams):
examGrades[i,j] = int(grades[j])
i += 1
# Close the text file.
gradeFile.close()
# Compute each student's average exam grade.
for i in range(numStudents):
# Tally the exam grades for the ith student.
total = 0
for j in range(numExams):
total += examGrades[i,j]
# Computer average for the ith student.
examAvg = total / numExams
print("%2d: %6.2f" % (i+1, examAvg))
Matrix is an m x n rectangular grid or table of numerical values divided into m rows and n columns. Matrices are important tool in arease such as linear algebra and computer graphics, are used in a number of applications, including representing and solving systems of linear equations.
A number of operations can be performed on matrices.
Matrix Addition
Matrix Substraction
Matrix Scaling
Matrix Multiplication
Transpose of Matrix
You can see the Matrix ADT implementation in matrix_class.py
script.
In [ ]: