Computer Programming 150

(April 9, 2008)

 

Coding for List Methods

 

1.             <list>.append(x):  appends x to end of list

 

      list + [x]

 

2.             <list>.sort()

 

def minIndex(n , list):

    #

    #  returns index of smallest value in the slice list[n:]

    #

    currMinIndex = n

    for i in range(n+1, len(list)):

        if (list[i] < list[currMinIndex]):

            currMinIndex = i

    return currMinIndex

 

def selectionSort(list):

    #

    #  selection sort - returns list in ascending order

    #

    for n in range(len(list)-1):

        k = minIndex(n, list)               # get index of smallest element in list[n:]

        list[k], list[n] = list[n], list[k] # swap with list[n]   

        print n, k, list   # trace

    return list   

 

3.             <list>..reverse()

 

def reverse(list):

    #

    #  reverses items in list

    #

    n = len(list)

    for i in range(n/2):                              # half the list

        list[i], list[n-1-i] = list[n-1-i], list[i]   # swap items

 

4.             <list>.index(x):  returns index of x in list

 

def index(x, list):

    #

    #  returns location of value x in list

    #  if not found returns length of list

    #

    i = 0;

    while (i < len(list) and x != list[i]):  # “standard” search loop

        i = i + 1

    return i

 

5.             <list>.insert(i, x) : inserts x into list at location i

 

def insert(i, x, list):

    #

    #  inserts x at location i

    #

    list = list + [0]           # add zero to end

    n = len(list)-1

    while (n > i):                # shift values to right

        list[n] = list[n-1]

        n = n - 1

    list[i] = x                 # insert x in open slot

    return list

 

6.             <list>.count(x): counts number of occurrences of x in list

 

def count(x, list):

    #

    #  counts occurrences of x in list

    #

    cnt = 0;

    for i in list:

        if (i == x):

            cnt = cnt + 1

    return cnt       

 

7.             <list>.remove(x): moves item x from list

 

def remove(x, list):

    #

    #  deletes first occurrence of x in list

    #

    i = 0

    while (i < len(list) and x != list[i]):     # “standard” search loop

        i = i + 1

    return list[:i] + list[i+1:]    # concatenate slices where i is position of x

 

8.             <list>.pop(i): removes and returns item at location i

 

def pop(i, list):

    #

    #  deletes and returns ith component of list

    #

    x = list[i]

    list = list[:i] + list[i+1:]    # concatenates slices

    return x, list