Today: lambda warmup, modules 1.0, wordcount module, HW7 preview, bluescreen art contest
Alonzo Church did crucial research in 1930 on the meaning of symbolically encoding a computation, with what he called the Lambda Calculus. What's funny is - computers did not exist yet! Later as computers were developed, they used his "lambda" term for a function, as we do today.
We'll do this one in the interpreter
>>> strs = ['bbb', 'cc', 'dd', 'aaa', 'z'] >>> >>> sorted(strs) ['aaa', 'bbb', 'cc', 'dd', 'z'] # sort by alphabetic
Suppose have a list of strings. How to sort these into increasing order by length? What 1-liner / lambda will pull out the string with the largest length?
We've solved these with a key=lambda - takes in one element from list, returns sort-by value, in this case the length.
>>> strs ['bbb', 'cc', 'dd', 'aaa', 'z'] >>> sorted(strs, key=lambda s: len(s)) ['z', 'cc', 'dd', 'bbb', 'aaa'] >>> >>>
Look at this
['z', 'cc', 'dd', 'bbb', 'aaa']
It's like there are 3 "key=" groups, each holding all the strings with that length.
(len 1 strs) (len 2 strs) (len 3 strs)
Most sorting algorithms are "stable" - when two elements are equal for sorting, they maintain their original ordering from the original list. Notice how 'bbb' comes before 'aaa' above. Or in terms of the groups above, elements keep their original ordering within a group.
Here is an obscure corner case, but you can see it in the demos, so I should explain it. even if reverse=True mode is on, the equal elements still keep their original ordering vs. each other. What's going on here: we are reversing the key= groups with respect to each other (len 1, len 2, len 3) vs. (len 3, len 2, len 1), but within a group, the elements keep their stable order.
>>> strs ['bbb', 'cc', 'dd', 'aaa', 'z'] >>> sorted(strs, key=lambda s: len(s), reverse=True) ['bbb', 'aaa', 'cc', 'dd', 'z']
Could write a def - always an option. Lambda is best if the code is very short. With a def we get: multiple lines, if-statements, tests, etc.
>>> def by_len(s): # by_len(s) - returns len(s) .. return len(s) >>> >>> sorted(strs, key=by_len) # sort with by_len ['z', 'cc', 'dd', 'bbb', 'aaa'] >>>
A sort of cute/trick solution: what is "len"? It's a function that takes in 1 string and returns an int. We don't need a lambda - just use len directly!
>>> sorted(strs, key=len) ['z', 'cc', 'dd', 'bbb', 'aaa']
>>> import math >>> math.sqrt(2) # call sqrt() fn 1.4142135623730951 >>> math.sqrt>>> >>> math.log(10) 2.302585092994046 >>> math.pi # constants in module too 3.141592653589793
Quit and restart the interpreter without the import, see common error:
>>> # quit and restart interpreter >>> math.sqrt(2) # OOPS forgot the import Traceback (most recent call last): NameError: name 'math' is not defined >>> >>> import math >>> math.sqrt(2) # now it works 1.4142135623730951
>>> import math
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>>
>>> help(math.sqrt)
Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.
>>>
>>> help(math.cos)
Help on built-in function cos in module math:
cos(x, /)
Return the cosine of x (measured in radians).
>>> # Run interpreter in wordcount directory
>>> import wordcount
>>>
>>> wordcount.read_counts('test1.txt')
{'a': 2, 'b': 2}
>>> dir(wordcount)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'clean', 'main', 'print_counts', 'print_top', 'read_counts', 'sys']
>>>
>>> help(wordcount.read_counts)
Help on function read_counts in module wordcount:
read_counts(filename)
Given filename, reads its text, splits it into words.
Returns a "counts" dict where each word
...
You have written many foo.py files with defs in the. Now we see, another program can import foo, and then call foo.bar() in your module to access your functions (in the same directory). It helps that your functions have well defined input/output, so they can be used and re-mixed by other programs.
Typical last 2 lines of .py file:
if __name__ == '__main__':
main()
Experiment: Put these lines at end of wordcount.py. Then try running wordcount from command line, and loading it in interpreter.
if __name__ == '__main__':
print("I feel like running main()")
main()
else:
print("Not running main()")
Design idea: doing the ordinary thing should be easy, not require thought. Doing something hard should be possible, but may require work.
This __name__ business seems a weak point in Python's design. It is not great that every vanilla python program has to carry around these 2 obscure looking lines. There should be a less obscure way of getting the default behavior that 99% of python programs want.