Today: TK GUI drawing, lambda/def, map-lambda, custom sorting with lambda, wordcount sorting

TK GUI Drawing

Lambda - Power Feature

Lambda is powerful feature, letting you express a lot of computation in very little space. As a result, it's weird looking at first, but when it clicks, you should feel like a Power Hacker when you wield it.

Lambda - Code as a Parameter

Countless times, you have called a function and passed in some data for it to use. The function name is the verb, and the parameters are extra nouns to guide the computation:

# e.g. "range" is the verb, up to 10
range(10)

# e.g. "draw_line" is the verb, with these int coords
canvas.draw_line(0, 0, 100, 50)

With lambda, we open up a new category, passing in code as the parameter for the function to use, e.g. with map():

map(lambda s: s.upper() + '!', ['pass', 'code']) ->
 ['PASS!', 'CODE!']

Map/Lambda vs. Boilerplate (optional)

Suppose I ask you to compute a new list, doubling each number

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

Now I want one where each number is times -1

result = []
for num in nums:
    result.append(num * -1)
return result

Now I want one where each number is plus 100

result = []
for num in nums:
    result.append(num + 100)
return result

Foreach Pattern

lambda To The Rescue

The above three are now 1-liners:

>>> list(map(lambda num: num * 2, nums))
[2, 4, 6, 8]
>>> list(map(lambda num: num * -1, nums))
[-1, -2, -3, -4]
>>> list(map(lambda num: num + 100, nums))
[101, 102, 103, 104]

Lambda Question: param is what?

map/lambda Reminder

Lambda-2 Examples

> lambda-2 examples

More filled-out uses of lambda, more realistic. Some of these use a list of numbers, some with list of (x, y) tuples. We can have a lot of these problems - the solutions are always 1 or 2 lines of code. We'll demo 1 or 2, have the students solve 1.

xy_sum()

Given a list of len-2 (x, y) tuples. Return a list of the sums of each tuple. Shows that the result-list does not need to hold the same type as the input list. Solve with a map/lambda.

[(4, 2), (1, 2) (2, 3)]  ->  [6, 3, 5]

This is a list of points. Q: What type is the param to the lambda? A: one point

Solution

def xy_sum(points):
    return map(lambda pt: pt[0] + pt[1], points)

xs()

Given a list of len-2 (x, y) tuples. Return a list of just the x value of each tuple. Solve with a map/lambda.

Solution

def xs(points):
    return map(lambda pt: pt[0], points)

min_x()

Given a non-empty list of len-2 (x, y) tuples. What is the leftmost x among the tuples? Return the smallest x value among all the tuples, e.g. [(4, 2), (1, 2) (2, 3)] returns the value 1. Solve with a map/lambda and the builtin min(). Recall: min([4, 1, 2]) returns 1

[(4, 2), (1, 2), (2, 3)]  -> 1

Solution

def min_x(points):
    return min(map(lambda pt: pt[0], points))
    # Use map/lambda to form a list of
    # just the x coords. Feed that into min()

shift(nums, delta)

shift(): Given a list of numbers and an int delta. Return a new list where each number has been changed by delta.

[2, 3, 2, 5], delta=1 -> [3, 4, 3, 6]

Solution

def shift(nums, delta):
    return map(lambda n: n + delta, nums)
    # Compute (n + delta) for each num.
    # Observe: the lambda code can refer to vars
    # like "delta" here

shift_left(nums)

Given a non-empty list of numbers. Compute the min value of the numbers. Return a new list of numbers, subtracting the min from each. Solve with 2 lines of code. Suggestion: use the builtin function min().

[2, 3, 2, 5] -> [0, 1, 0, 3]

Solution

def shift_left(nums):
    least = min(nums)
    return map(lambda n: n - least, nums)
    # Note: resist using "min" as a var name,
    # since it is the name of a builtin fn.

Custom Sort - Power Feature

Python Custom Sort - Food Examples

>>> foods = [('radish', 2, 8), ('donut', 10, 1), ('apple', 7, 9), ('broccoli', 6, 10)]
>>> 
>>> # By default, sorts food tuples by [0]
>>> sorted(foods)
[('apple', 7, 9), ('broccoli', 6, 10), ('donut', 10, 1), ('radish', 2, 8)]
>>> 

Python Custom Sort - Lambda

[('radish', 2, 8), ('donut', 10, 1), ('apple', 7, 9), ('broccoli', 6, 10)]

#  Project out these values for sort-compare

[2, 10, 7, 6]
alt: project out len-4 list of tasty values from len-4 list of food tuples

Sort By Tasty - Lambda

lambda food: food[1]

Q: What is the parameter to the lambda?

A: One elem from the list (similar to map() function)

Food Sort Examples

>>> foods = [('radish', 2, 8), ('donut', 10, 1), ('apple', 7, 9), ('broccoli', 6, 10)]
>>> # sort by tasty - project out the tasty int - radish first, donut last
>>> sorted(foods, key=lambda food: food[1])
[('radish', 2, 8), ('broccoli', 6, 10), ('apple', 7, 9), ('donut', 10, 1)]
>>> 
>>> sorted(foods, key=lambda food: food[1], reverse=True)  # by tasty, reverse=True
[('donut', 10, 1), ('apple', 7, 9), ('broccoli', 6, 10), ('radish', 2, 8)]
>>> 
>>> sorted(foods, key=lambda food: food[2], reverse=True)  # by healthy
[('broccoli', 6, 10), ('apple', 7, 9), ('radish', 2, 8), ('donut', 10, 1)]
>>> 
>>> sorted(foods, key=lambda food: food[1] * food[2], reverse=True) # by tasty*healthy
[('apple', 7, 9), ('broccoli', 6, 10), ('radish', 2, 8), ('donut', 10, 1)]
>>>

Sorted vs. Min Max

>>> foods = [('radish', 2, 8), ('donut', 10, 1), ('apple', 7, 9), ('broccoli', 6, 10)]
>>> max(foods)     # uses [0] by default - tragic!
('radish', 2, 8)
>>> 
>>> sorted(foods, key=lambda food: food[1])
[('radish', 2, 8), ('broccoli', 6, 10), ('apple', 7, 9), ('donut', 10, 1)]
>>> 
>>> max(foods, key=lambda food: food[1])  # most tasty
('donut', 10, 1)
>>> min(foods, key=lambda food: food[1])  # least tasty
('radish', 2, 8)

Key performance point: computing one max/min element is much faster than sorting all n elements.

Python Custom Sort String Examples

>>> strs = ['coffee', 'Donut', 'Zebra', 'apple', 'Banana']
>>> sorted(strs)
['Banana', 'Donut', 'Zebra', 'apple', 'coffee']
>>> strs = ['coffee', 'Donut', 'Zebra', 'apple', 'Banana']
>>> 
>>> sorted(strs, key=lambda s: s.lower())    # not case sensitive
['apple', 'Banana', 'coffee', 'Donut', 'Zebra']
>>> 
>>> sorted(strs, key=lambda s: s[len(s)-1])  # by last char
['Zebra', 'Banana', 'coffee', 'apple', 'Donut']
>>> 

Put It All Together - WordCount + Sorted

Look at wordcount project, apply custom sorting to the output stage.

Sorted vs. Dict Count Items

>>> items = [('z', 1), ('a', 3), ('e', 11), ('b', 3), ('c', 2)]
>>> items = [('z', 1), ('a', 3), ('e', 11), ('b', 3), ('c', 2)]
>>> 
>>> sorted(items)
[('a', 3), ('b', 3), ('c', 2), ('e', 11), ('z', 1)]
>>> 
>>> sorted(items, key=lambda pair: pair[1])   # sort by count
[('z', 1), ('c', 2), ('a', 3), ('b', 3), ('e', 11)]
>>> 
>>> sorted(items, key=lambda pair: pair[1], reverse=True)
[('e', 11), ('a', 3), ('b', 3), ('c', 2), ('z', 1)]
>>> 
>>> max(pairs, key=lambda pair: pair[1])      # largest count
('e', 11)

Wordcount - Lambda - You Try It

Here is the WordCount project we had before. This time look at the print_counts() and print_top() functions - you write code to make print_top() work.

> wordcount.zip

print_counts() - Alphabetic Output

Here is the output of the regular print_counts() function, which prints out in alphabetic order. Output looks like:

$ python3 wordcount.py poem.txt 
are 2
blue 2
red 2
roses 1
violets 1
$

print_counts() Solution

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])
    # Alternately use .items() to access all the key/value data
    # for key, value in sorted(counts.items()):
    #    print(key, value)

print_top()

The print_top(counts, n) function - print the n most common words in decreasing order by count.

$ python3 wordcount-solution.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

print_top() Solution

def print_top(counts, n):
    """
    Given counts dict and int N, print the N most common words
    in decreasing order of count
    the 1045
    a 672
    ...
    """
    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)