Anda di halaman 1dari 34

Computer Programming

Lecture 11 & 12

Lists

Lists

Topics to be covered today.

Introduction to Arrays and Lists

Using arrays and lists to store homogeneous data elements.

Predefined functions for lists

Dynamic Lists

Simple operations on lists

Sum and product

Maximum and Minimum

Lists as parameters to functions.

Multi-dimensional Lists and Matrix operations.

List and Arrays – A gentle Introduction

Lets assume we had to store 5 integers:

One option would be to use five variables and store the integers therein; If the integers were 5,2,-5,2,43, we could have:

A=5

B=2

C=-5

D=2

E=43

The above option would be operational but it is not a very efficient approach, because manipulating the variables would be a tedious task.

Arrays and Lists

Most if not all programming languages allow homogenous data (i.e. Data of the same type) to be stored in simple data structures. In some Programming Languages, these data structures are called arrays, in Python, they are called Lists.

'In computer science an array [1] is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type and the array occupies a contiguous area of storage.' (Wikipedia)

Using arrays/lists, it is possible to store multiple data items of the same type and access them using indexing (just as in strings).

Declaring Lists of Known Lengths and Known Elements

Using lists is very easy. All lists are enclosed within '[' and ']', and the individual elements are separated by a ','

Assuming we need to store the values 5,2,-5,2,43, We could achieve this by writing myList=[5,2,-5,2, 43], whereby

myList[0]=5

myList[1]=2

myList[2]=-5

myList[3]=2

myList[4]=43

Displaying Lists

myList=[5,2,-5,2, 43] To print the above list, we could have simply written

print myList

The output would be:

[5,2,-5,2, 43]

If we wanted to display the elements individually on a separate line, we could have used the codes below:

for i in range(5):

print myList[i] #i being used as the index

Manipulating List Elements

Since it is possible to access the individual elements, we can also manipulate these elements. Let's assume we wanted to display the square of all the elements in a list.

myList=[5,2,-5,2, 43] for i in range(5):

a= myList[i] #i is the index

b=a*a print b

Adding up two homogenous lists

listA=[1,5,3,2,3,1,3]

listB=[78,8,7,8,45,3,5]

for i in range(7):

a=listA[i] b=listB[i] c=a+b print c

#indexing the elements of listA #indexing the elements of listB #Adding each element

---------------------------------------------------------

We can also use some pre-defined functions with list, these functions include len, sort

List operations

List operations Source: Text Book- Python Programming: An Introduction to Computer Science (Pg 343) (Pdf -:

Source: Text Book- Python Programming: An Introduction to Computer Science (Pg 343) (Pdf -: Pg 180)

Lists of Unknown Sizes

The previous programs had one major limitation:

The size of the list had to be known beforehand. We could be faced with situations whereby we did not know the size of the list. Lets assume we needed to store a certain number of integers in a list. The first step would be be tell the interpreter that we need an empty list at the beginning. This is achieved by writing

myList = [] # myList is assigned to an empty list

Adding elements to the List

Lets assume we needed to store a list of positive numbers. The algorithm for such a program would be:

Step 1: Create an empty list

Step 2: Input a number

Step 3: If number is positive, Add/append number

to the list, Enter another number, repeat step 3

Step 4: Else, Display the list

Implementation

myList=[]

x=input(“Enter number to be appended”)

while x > 0:

#Initialise my list as an empty list

#Since our list is meant for +ve numbers, we

use a negative number as Sentinel Value

myList.append(x) #The append function adds the value of x to the end of the list

x=input(“Enter number to be appended”) print myList

---------------------------------------------------------------

Sum of each elements of two lists of equal but unknown sizes

Assuming we have two lists, A and B of equal but unknown sizes. If we need to add up those two list, we could use the following codes:

A=[1,34,43 ] B=[23,3,434 ] Since we do not know the sizes but we know they are equal in lengths, we could use the function len(A), or len(B) to return the length of the sequences

Implementations of Sum of List

def sumList(listA,listB):

c=[] for i in range(len(listA)):

c.append(listA[i] + listB[i]) return c

A=[1,34,43 ] B=[23,34,34 ] sum=sumList(A,B) print sum

------------------------------------------------------------

Notice that we can pass lists as parameters to functions, and that functions can also return lists

Program to find the Maximum value in a list

The Algorithm is:

Step 1. Assume the first element is the biggest, i.e. assign Max to the first element, Step 2. If we have not yet reached the end of the list, Proceed, else jump to Step 5 Step 3. Compare Max with the current element in the current Slot. If the element in the current slot is greater than Max, Do Step 4 Step 4. Assign the value in the current slot to Max Step 5. Current jumps to the next slot, increment i, repeat Step 2 Step 6. Print the Maximum element

The Codes

A=[1,5,8,44,8,4,5,45]

Max=A[0]

I=1

while I<len(A):

if A[I]>Max:

Max=A[I]

I=I+1

# Step 1

#Step 2 #Step 3 #Step 4 #Step 5

print “The biggest value in List ”,A,” is ”, Max #Step 6

Dry running the Codes!

I=0

Max=A[i]=A[0]=1

I=1

len(A)=8

A

I

I<len(A)

A[I]

Max

A[I]>Max

Max

[1,5,8,44,8,4,50,45]

1

No

5

1

Yes

5

[1,5,8,44,8,4,50,45]

2

No

8

5

Yes

8

[1,5,8,44,8,4,50,45]

3

No

44

8

Yes

44

[1,5,8,44,8,4,50,45]

4

No

8

44

No

44

[1,5,8,44,8,4,50,45]

5

No

4

44

No

44

[1,5,8,44,8,4,50,45]

6

No

50

44

Yes

50

[1,5,8,44,8,4,50,45]

7

No

45

50

No

50

 

8

Yes

       

Lists – Passed by reference

def changeList(listA):

listA[0]=3

A=[1,34,43]

changeList(A) print A

---------------------------------------------------------------

If we try to change individual values of a list, the changes are reflected where the function is called Lists are mutable, unlike strings

Python Lists v/s Conventional Arrays

There are some basic differences between Python Lists and Conventional Arrays.

The basic difference is that Python Lists are dynamic, i.e they can grow or shrink using (append and remove methods) Lists in Python also support heterogenous types. Conventional arrays usually store multiple data elements of the same type, whereas in Python we can have a list which stores data of several types, e.g myHetList=[1,2.31,'a',”well”], however special care must be taken while manipulating them

Multi-Dimensional Lists

So far, we have only considered one-dimensional lists (list of a certain number of rows), it is also possible to have multi-dimensional lists, i.e. made up of n rows by m columns. Do populate such a list, it is very easy and we can proceed using the following algorithm:

For each row, populate each column, this gives us the following implementation:

Populating a multi-dimensional List

num_Rows=input(“Enter number of rows”) num_Columns=input(“Enter number of Columns”)

my2dList=[]

for i in range(num_Rows):

Cols=[] for j in range(num_|Columns):

data=input(“Enter Data”) Cols.append(data)

my2dList.append(Cols)

The Codes - Explained!

my2dList=[]

for i in range(num_Rows): #Loop which goes through each row

Cols=[]

# Each time we are in a row, we start with an empty list

to store data in each column

for j in range(num_Columns):#In each Row, we need a

Loop which adds data pertaining to the columns

data=input(“Enter Data”)

Cols.append(data)# Appending Data to Cols for each

row

my2dList.append(Cols) #When we exit the inner loop we append Cols to the 2D List.

The Result

Consequently, the 2D list will be as follows, assuming we have 2 rows by 3 columns:

my2dList=[[a,b,c] , [d,e,f]] The elements in the list can be indexed as my2dlist[i] [j], where i and j are integers. If we want to display the 2d List, we can use:

print <list_name>, e.g. print my2dList, or be more 'geeky' and use:

for i in range(len(my2dList)):

for j in range (len(my2dList[0])):

print my2dList[i]][j],”--”, print

Matrix Operations using lists

Algorithm for the a program which adds up 2 matrices are as follows:

Input data to the first matrix, MatrixA Input data to the second matrix, MatrixB Initialise the Third Matrix, i.e. put all elements to Zero Add up each corresponding element in the 2 matrices and store in the third matrix, MatrixC.

Data Input to the matrices

num_Rows=input(“Enter number of rows”) num_Columns=input(“Enter number of Columns”) MatrixA=[] MatrixB= [] MatrixC=[] for i in range(num_Rows):

cols=[] for j in range(num_Columns):

data=input(“Enter Data”) cols.append(data) MatrixA.append(cols) for k in range(num_Rows):

cols=[] for l in range(num_|Columns):

data=input(“Enter Data”) cols.append(data) MatrixB.append(cols)

Avoiding Repetition

We can notice that the codes in 'red'

do

repeat, the wise option would be to use a function to minimise code repetition.

and 'purple'

The function could be as follows:

Def list_input(List, rws,cls):

for i in range(rws):

Cols=[] for j in range(cls):

data=input(“Enter Data”) Cols.append(data) List.append(Cols)

Adding up two lists

To add up the two lists, we will use the same logic as when we display, i.e. we will go through each slot in the third list, and instead of just printing out each element, we will only add up the element in the corresponding slots of the first and second list.

for i in range(rows):

for j in range (cols)):

MatrixC[i][j]=MatrixA[i][j]+MatrixB[i][j]

Printing the results

#printing MatrixA for i in range(rows):

for j in range (cols):

print MatrixA[i][j], print

#printing MatrixB for k in range(rows):

for l in range (cols):

print MatrixB[k][l], print

#printing MatrixC for m in range(rows):

for n in range (cols):

print MatrixC[m][n], print

Avoiding Repetition (Once Again!)

We can see from the previous slide that we do have repetition once again, we could use a function to display, whereby each array could be passed as parameter, along with the number of rows and number of columns.

def list_display(Matrix, rws, cls):

for m in range(rws):

for n in range (cls):

print Matrix[m][n],

print

Input and Display Function defs.

Def list_display(Matrix, rws, cls):

for m in range(rws):

for n in range (cls):

print Matrix[m][n], print

def list_input(List, rws,cls):

for i in range(rws):

Cols=[] for j in range(cls):

data=input(“Enter Data”) Cols.append(data) List.append(Cols)

Initialise MatrixC

def init_list(List, rws,cls):

for a in range(rws):

Cols=[] for b in range(cls):

Cols.append(0)

List.append(Cols)

The Whole Program

num_Rows=input(“Enter number of rows”) num_Columns=input(“Enter number of Columns”) MatrixA=[] MatrixB=[] MatrixC=[] list_input(MatrixA, num_rows, num_Columns) list_input(MatrixB, num_rows, num_Columns) init_list(MatrixC, num_rows, num_Columns) for i in range(rows):

for j in range (cols)):

MatrixC[i][j]=MatrixA[i][j]+MatrixB[i][j]

print list_display(MatrixA, num_rows, num_columns) list_display(MatrixB, num_rows, num_columns) list_display(MatrixC, num_rows, num_columns)

A Challenge!

Write

the

necessary

multiplication

codes

to

allow

matrix

For the Multiplication of Two Matrices A and B to be defined, the two matrices must be conformant, i.e. The number of Columns in the first one should be equal to the number of Rows in the second one.

For this question, simply assume that both matrices are of the same order, i.e they have the same number of Rows and Columns

The Solution

for i in range(num_Rows):

for j in range (num_Columns):

for k in range(num_Rows):

MatrixC[i][j]+=MatrixA[i][k]*MatrixB[k][j]