Programming 1
Week 9: Notes

Many of this week's topics are covered in Introducing Python:

Here are a few additional notes.

Vector class

Here is the Vector class we saw in the lecture. It demonstrates various Python features we've learned recently including comprehensionsm, zip, and variable numbers of arguments.

# an n-dimensional vector
class Vector:
    def __init__(self, *x):
        self.a = x
    
    def __repr__(self):
        s = ' '.join(str(x) for x in self.a)
        return '[' + s + ']'
        
    def length(self):
        return sqrt(sum(x * x for x in self.a))

    def __add__(self, v):
        l = [x + y for x, y in zip(self.a, v.a)]
        return Vector(*l)

isPrime

We can write isPrime using a generator comprehension:

def isPrime(n):
    return not any(n % i == 0 for i in range(2, int(sqrt(n)) + 1))

searching a directory tree

# Count the number of files in a directory and its subdirectories.
def dirCount(d):
    count = 0
    for f in os.listdir(d):
        p = path.join(d, f)
        if path.isfile(p):
            count += 1
        elif path.isdir(p):
            count += dirCount(p)
    return count

# Find a file with the given name in a directory and its subdirectories.
# Return the pathname of the file, or None if not found.
def find(d, name):
    for f in os.listdir(d):
        p = path.join(d, f)
        if f == name:
            return p
        if path.isdir(p):
            q = find(p, name)
            if q != None:
                return q
    return None