15-112 Fundamentals of Programming

Notes - Lecture 3.1


Content

  1. Wrapping up 1d lists
    1. Swapping Elements
    2. Copying lists
    3. List comprehension
    4. Converting Between Lists and Strings
    5. 1d list CT
    6. Worked example 1: Anagrams
    7. Worked example 2: The Sieve of Eratosthenes
  2. 2d lists
    1. 2d lists
    2. 2d lists CT
    3. Example 1: isMagicSquare

Wrapping up 1d lists

1. Swapping elements

Failed swap
a = [ 2, 3, 5, 7 ]
print("a =", a)

a[0] = a[1]
a[1] = a[0]
print("After failed swap of a[0] and a[1]:")
print("   a=",a)

Swap with a temp variable
a = [ 2, 3, 5, 7 ]
print("a =", a)

temp = a[0]
a[0] = a[1]
a[1] = temp
print("After swapping a[0] and a[1]:")
print("   a=",a)

Swap with parallel (tuple) assignment
a = [ 2, 3, 5, 7 ]
print("a =", a)

a[0],a[1] = a[1],a[0]
print("After swapping a[0] and a[1]:")
print("   a=",a)

2. Copying lists

Copy vs Alias
import copy

# Create a list
a = [ 2, 3 ]

# Try to copy it
b = a             # Error!  Not a copy, but an alias
c = copy.copy(a)  # Ok

# At first, things seem ok
print("At first...")
print("   a =", a)
print("   b =", b)
print("   c =", c)

# Now modify a[0]
a[0] = 42
print("But after a[0] = 42")
print("   a =", a)
print("   b =", b)
print("   c =", c)

Other ways to copy
import copy

a = [2, 3]
b = copy.copy(a)
c = a[:]
d = a + [ ]
e = list(a)
f = copy.deepcopy(a)
g = sorted(a)

a[0] = 42
print(a, b, c, d, e, f, g)

3. List comprehension

a = [i for i in range(10)]
print(a)

a = [(i*100) for i in range(20) if i%5 == 0]
print(a)

4. Converting between Lists and Strings

# use list(s) to convert a string to a list of characters
a = list("wahoo!")
print(a)  # prints: ['w', 'a', 'h', 'o', 'o', '!']

# use s1.split(s2) to convert a string to a list of strings delimited by s2
a = "How are you doing today?".split(" ")
print(a) # prints ['How', 'are', 'you', 'doing', 'today?']

# use "".join(a) to convert a list of characters to a single string
s = "".join(a)
print(s)  # prints: wahoo!

# "".join(a) also works on a list of strings (not just single characters)
a = ["parsley", " ", "is", " ", "gharsley"] # by Ogden Nash!
s = "".join(a)
print(s)  # prints: parsley is gharsley

5. 1d List CT

import copy

def ct1(a):
    (b, c) = (a, copy.copy(a))
    a[0] = 3
    b[0] = 4
    c[0] = 5
    print(a[0], b[0], c[0], end = " ")
    a = c
    a[0] = 6
    b[0] = 7
    c[0] = 8
    print (a[0], b[0], c[0], end = " ")              

a = [1, 2]
ct1(a)
print(a[0])


6. Worked example 1: Anagrams

def letterCounts(s):
    counts = [0] * 26
    for ch in s.upper():
        if ((ch >= "A") and (ch <= "Z")):
            counts[ord(ch) - ord("A")] += 1
    return counts

def isAnagram(s1, s2):
    # First approach: same #'s of each letter
    return (letterCounts(s1) == letterCounts(s2))

def isAnagram(s1, s2):
    # Second approach: sorted strings must match!
    return sorted(list(s1.upper())) == sorted(list(s2.upper()))

def testIsAnagram():
    print("Testing isAnagram()...", end="")
    assert(isAnagram("", "") == True)
    assert(isAnagram("abCdabCd", "abcdabcd") == True)
    assert(isAnagram("abcdaBcD", "AAbbcddc") == True)
    assert(isAnagram("abcdaabcd", "aabbcddcb") == False)
    print("Passed!")

testIsAnagram()

7. Worked example 2: The Sieve of Eratosthenes

# Sieve of Eratosthenes

# This function returns a list of prime numbers
# up to n (inclusive), using the Sieve of Eratosthenes.
# See http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

def sieve(n):
    isPrime = [ True ] * (n+1) # assume all are prime to start
    isPrime[0] = isPrime[1] = False # except 0 and 1, of course
    primes = [ ]
    for prime in range(n+1):
        if (isPrime[prime] == True):
            # we found a prime, so add it to our result
            primes.append(prime)
            # and mark all its multiples as not prime
            for multiple in range(2*prime, n+1, prime):
                isPrime[multiple] = False
    return primes

print(sieve(100))



2d Lists

1. 2d lists

See here.

2. 2d lists CT

import copy

def ct1(L):
    a = L
    b = copy.copy(L)
    c = copy.deepcopy(L)
    b[0] = a[1] * a[1][0]
    a[0][0] += a.pop()[0]
    b[1] = c[0]
    return  b

L = [[1],[2],[3]]
print(ct1(L))
print(L)

3. Example 1: isMagicSquare(a)

See here.

Valid CSS! Valid XHTML 1.0 Strict