Many of this week's topics are covered in Introducing Python:
Chapter 7. Tuples and LIsts
Lists
Iterate Multiple Sequences with zip()
Chapter 9. Functions
Arguments and Parameters
Explode/Gather Postional Arguments with *
Generators
Generator Comprehensions
Chapter 14. Files and Directories
File Input and Output
File Operations
Directory Operations
Pathnames
Here are a few additional notes.
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)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))# 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