# Lecture 16 - Exercises

### 16A - `split` and `join`

1. What does the following print?

   ```python
   print("_".join("88r4if4r462".split("r4")))
   ```

### 16B - Reading and Writing Files

2. Suppose the file `rick.txt` contains:

   ```
   Never gonna give you up
   ```

   What is the output of the following code?

   ```python
   print(open("rick.txt", "r").read(5).split("e"))
   ```

3. Assume a file called `fin.txt` exists in the same directory as the program below, and has the following contents:

   ```
   Start: 4pm
   End: 7pm
   3h
   ```

   What does the following program print?

   ```python
   fin = open("fin.txt", 'r')
   fot = open("fot.txt", 'w')
   
   for line in fin:
       fl = line.strip().split(': ')
   
       fot.write(fl[-1])
       fot.write(fl[0])
      
   fot.close()
   fin.close()
   
   fot = open("fot.txt", 'r')
   a = fot.read(3)
   fot.seek(8)
   print(a, fot.read())
   fot.close()
   ```


### Problems

1. Implement the following function:

   ```python
   def split_address(addr_line):
       """ Split the postal address in address_line into its
       component pieces. Return a tuple of strings containing:
           (number, street, city, state, zip).
       Precondition: the address matches the following format:
           "<number> <street>, <city> <state> <zip>"
       Example: split_address("516 High St, Bellingham WA 98225")
       => ("516", "High St", "Bellingham", "WA", "98225") """
   ```

2. Download [test.txt](code/test.txt). Write a program that counts and prints the number of **unique** lines in the file. Be sure that the text file and your Python program are saved in the same directory.

3. Implement the following function:

   ```python
   def grep(string, filename):
       """ Print all lines of the file filename that contain the given string.
       Precondition: the file exists. """
   ```

4. Download [AboutYou.csv](code/AboutYou.csv). Write a Python program to calculate the average number of quarters at Western among each of three groups of students:

   * students who are planning to major in CS
   * students who are considering a CS major
   * students who are not planning to major in CS
   
5. Implement the following function:

   ```python
   def spellcheck(in_filename, out_filename wordlist):
       """ Write a spellchecked version of in_filename to
       out_filename. For each word in the input file, write
       it as-is to the output file if it is in the wordlist;
       otherwise, write it to the output file in ALLCAPS to
       indicate that it's not in the wordlist. """
   ```