Today: list functions: sorted, min, max, sum. List foreach patterns, state-machine. File reading. Look at word-count program.

1. sorted()

>>> sorted([45, 100, 2, 12])               # numeric
[2, 12, 45, 100]
>>> 
>>> sorted([45, 100, 2, 12], reverse=True)
[100, 45, 12, 2]
>>> 
>>> sorted(['banana', 'apple', 'donut'])   # alphabetic
['apple', 'banana', 'donut']
>>>
>>> sorted(['45', '100', '2', '12'])       # wrong-looking
['100', '12', '2', '45']
>>> 
>>> sorted(['45', '100', '2', '12', 13])
TypeError: '<' not supported between instances of 'int' and 'str'

2. min(), max()

>>> min(1, 3, 2)
1
>>> max(1, 3, 2)
3
>>> min([1, 3, 2])  # lists work
1
>>> min([1])        # len-1 works
1
>>> min([])         # len-0 is an error
ValueError: min() arg is an empty sequence
>>> min(['banana', 'apple', 'zebra'])  # strs work too
'apple'
>>> max(['banana', 'apple', 'zebra'])
'zebra'

sum()

Compute the sum of a collection of ints or floats, like +.

>>> nums = [1, 2, 1, 5]
>>> sum(nums)
9

List Code Patterns

> List Pattern Exercises

Many times, parts of your program are familiar patterns that you have written in other programs. It's handy to recognize and practice these patterns. The familiarity makes them easy to write, easy to read.

1. Foreach "map" Pattern

doubled()

Doubled: Given a list of int values, return a new list of their values doubled. Basic mapping pattern example. Solve with a foreach loop.

Solution Code

def doubled(nums):
    result = []
    for num in nums:
        result.append(num * 2)
    return result

2 - "filter" Pattern

dstart()

dstart(strs): Given a list of strings, return a new list of only the strings that start with a digit. Basic filtering example. Solve with a foreach loop + if.

Solution Code

def dstart(strs):
    result = []
    for s in strs:
        if len(s) > 0 and s[0].isdigit():
            result.append(s)
    return result

Map/Filter Example: shouting()

shouting(strs): Given a list of strings, return a new list where each original string that ends with a '!' is converted to upper case, and all other strings are omitted. So ['cats!', 'and', 'dogs!'] returns ['CATS!', 'DOGS!']

3 - State-Machine Pattern

"count" Strategy

count_target()

count_target(): Given a list of ints and a target int, return the int count number of times the target appears in the list. Solve with a foreach + "count" variable.

Solution Code

def count_target(nums, target):
    count = 0
    for num in nums:
        if num == target:
            count += 1
    return count

State-Machine Exercise: min()

Style note: we have Python built-in functions like min() max() len() list(). Avoid creating a variable with the same name as an important function, like "min" or "list". This is whey our solution uses "best" as the variable to keep track of the smallest value seen so far instead of "min".

Slice note: one odd thing in this solution is that it use element [0] as the best initially, and then the loop will uselessly < compare best to [0] on its first iteration. Could iterate over nums[1:] to avoid this useless comparison. But that would copy the entire list to avoid a single comparison, a bad tradeoff. Therefore it's better to just write the loop the nice standard way. Also, we prefer code with the correct answer that is readable, and our solution is good at both of those.

Solution

def min(nums):
    # best tracks smallest value seen so far.
    # Compare each element to it.
    best = nums[0]
    for num in nums:  # could slice off [0] here
        if num < best:
            best = num
    return best

State-Machine - "previous" Technique

count_dups()

count_dups(): Given a list of numbers, count how many "duplicates" there are in the list - a number the same as the value immediately before it in the list. Use a "previous" variable

Solution

def count_dups(nums):
    count = 0
    previous = None      # init
    for num in nums:
        if num == previous:
            count += 1
        previous = num   # set for next loop
    return count
    # Could write as
    # if previous != None and previous == num:
    # but in this case the None comparison is not
    # needed

Optional State Challenge - hat_decode()

A neat example of a state-machine approach.

The "hat" code is very simple. The string s is mostly made of garbage chars to ignore. However, '^' marks the beginning of actual message chars, and '.' marks their end. So the decode of 'xx^Ya.xx^y!.bb' is 'Yay!'

Solve using a loop over s, using a state-variable "copying" which tracks True/False if chars are to be copied or ignored. There is a subtle order to check for '^' and '.' in the loop so that those chars are not themselves included in the output.


Some Notes About Hardware

See lecture-17 for some details, we skipped it at the time

File Reading

See guide: Python File

with open(filename) as f:
    # use f in here

Or may see this form, equivalent to above since 'r' is the default, meaning read the file. 'w' means write the file from RAM to the file system. See the guide above for sample code.

with open(filename, 'r') as f:
    # use f in here

Can specify encoding (default depends on your machine / locale). Encoding 'utf-8' is what many files use. Add this if you get a UnciodeDecodeError

with open(filename, encoding='utf-8') as f:
    # use f

Older way to open() a file (use in interpreter)

f = open(filename)
# use f
# f.close() when done

File Loop

Most common, process 1 line at a time. Uses the least memory.

for line in f:
    # process each line

Alternatives: f.read(), r.readlines()

read() - whole file into one string. Can only a read bit of text from a file once. Doing a second read returns the empty string. readlines() - return list of line strings, can do slices etc. to access lines in a custom order.

>>> f = open('poem.txt')  # alternative to with, use in interpreter
>>> s = f.read()          # whole file in string
>>> s
'Roses are red\nViolets are blue\n"RED" BLUE.\n'
>>> 
>>> >>> f.read()          # reading again gets nothing
''
>>>
>>>
>>> f = open('poem.txt')
>>> lines = f.readlines()
>>> lines
['Roses are red\n', 'Violets are blue\n', '"RED" BLUE.\n']
>>> 
>>>lines[1:]   # slice to grab subset of lines
['Violets are blue\n', '"RED" BLUE.\n']
>>>

WordCount Example - Rosetta Stone!

A sort or Rosetta stone of coding - it's a working demonstration of many important features of a computer program: strings, dicts, loops, parameters, return, decomposition, testing, sorting, files, and main().

We'll look at this program to see Python features in action, and the complete source code is included at the end of this doc. Today we'll look at a little.

wordcount.zip

Sample Run

Note how words are cleaned up

$ cat poem.txt
Roses are red
Violets are blue
"RED" BLUE.
$
$ python3 wordcount.py poem.txt 
are 2
blue 2
red 2
roses 1
violets 1

WordCount Example Code

#!/usr/bin/env python3

"""
CS106A WordCount Example
Nick Parlante

Counting the words in a text file is a sort
of Rosetta-stone of programming - it uses files, dicts, functions,
logic, decomposition, testing, command line in main().
Trace the flow of data starting with main().
There is a sorted/lambda exercise below.

Basic code is provided, alphabetical output
$ python3 wordcount.py somefile.txt
aardvark 12
anvil 3
boat 4
...

**Exercise**

Implement code in print_top() to print the N most common words,
using sorted/lambda/items.

Then command line -top N feature calls print_top(), output like..
$ python3 wordcount.py -top 10 alice-book.txt
the 1639
and 866
to 725
a 631
she 541
it 530
of 511
said 462
i 410
alice 386
"""

import sys


def clean(s):
    """
    Given string s, returns a clean version of s where all non-alpha
    chars are removed from beginning and end, so '@@x^^' yields 'x'.
    The resulting string will be empty if there are no alpha chars.
    >>> clean('$abc^')      # basic
    'abc'
    >>> clean('abc$$')
    'abc'
    >>> clean('^x^')        # short (debug)
    'x'
    >>> clean('abc')        # edge cases
    'abc'
    >>> clean('$$$')
    ''
    >>> clean('')
    ''
    """
    # Examples below of an inline comment: explain
    # the *goal* of the lines, not repeating the line mechanics.
    # Lines of code written for teaching often have more inline
    # comments like this than regular production code.

    # Move begin rightwards, past non-alpha punctuation
    begin = 0
    while begin < len(s) and not s[begin].isalpha():
        begin += 1

    # Move end leftwards, past non-alpha
    end = len(s) - 1
    while end >= begin and not s[end].isalpha():
        end -= 1

    # begin/end cross each other -> nothing left
    if end < begin:
        return ''
    return s[begin:end + 1]


def read_counts(filename):
    """
    Given filename, reads its text, splits it into words.
    Returns a "counts" dict where each word
    is the key and its value is the int count
    number of times it appears in the text.
    Converts each word to a "clean", lowercase
    version of that word.
    The Doctests use little files like "test1.txt" in
    this same folder.
    >>> read_counts('test1.txt')
    {'a': 2, 'b': 2}
    >>> read_counts('test2.txt')    # Q: why is b first here?
    {'b': 1, 'a': 2}
    >>> read_counts('test3.txt')
    {'bob': 1}
    """
    with open(filename) as f:
        text = f.read()   # demo reading whole string vs line/in/f way
    # once done reading - do not need to be indented within open()
    counts = {}
    words = text.split()

    # Style idea - compute clean() once, decomp by var to store it,
    # use on later lines. More readable and runs faster.
    for word in words:
        word = word.lower()
        cleaned = clean(word)
        if cleaned != '':  # cleaning may leave only ''
            if cleaned not in counts:
                counts[cleaned] = 0
            counts[cleaned] += 1
    return counts
    # Style comparison: this is what it looks like without "cleaned" var
    # for word in words:
    #     word = word.lower()
    #     if clean(word) != '':
    #         if clean(word) not in counts:
    #             counts[clean(word)] = 0
    #         counts[clean(word)] += 1


def print_counts(counts):
    """
    Given counts dict, print out each word and count
    one per line in alphabetical order, like this
    aardvark 1
    apple 13
    ...
    """
    for word in sorted(counts.keys()):
        print(word, counts[word])


def print_top(counts, n):
    """
    (Exercise)
    Given counts dict and int N, print the N most common words
    in decreasing order of count
    the 1639
    and 866
    to 725
    ...
    """
    items = counts.items()
    # Could print the items in raw form, just to see what we have
    # print(items)
    pass
    # Your code - my solution is 3 lines long, but it's dense!
    # Sort the items with a lambda so the most common words are first.
    # Then print just the first N word,count pairs with a slice
    items = sorted(items, key=lambda pair: pair[1], reverse=True)  # 1. Sort largest count first
    for word, count in items[:n]:                                  # 2. Slice to grab first N
        print(word, count)


def main():
    # (provided)
    # Command line forms
    # 1. filename
    # 2. -top N filename   # prints N most common words
    args = sys.argv[1:]

    if len(args) == 1:
        # filename
        counts = read_counts(args[0])
        print_counts(counts)

    if len(args) == 3 and args[0] == '-top':
        # -top N filename
        n = int(args[1])
        counts = read_counts(args[2])
        print_top(counts, n)

if __name__ == '__main__':
    main()