diff --git a/Examples/Session01/schedule.txt b/Examples/Session01/schedule.txt deleted file mode 100644 index 2325408..0000000 --- a/Examples/Session01/schedule.txt +++ /dev/null @@ -1,26 +0,0 @@ -week 2: Brendan Fogarty -week 2: Bruce Bauman -week 2: Michelle Yu -week 3: Eric Rosko -week 3: Michael Waddle -week 3: Robert Stevens Alford -week 4: Andrey Gusev -week 4: Cheryl Ohashi -week 4: Maxwell MacCamy -week 5: Michael Cimino -week 5: Pei Lin -week 5: Tiffany Ku -week 6: Gabriel Meringolo -week 6: Joseph Cardenas -week 6: Marc Teale -week 7: Eric Starr Vegors -week 7: Ian Cote -week 7: Masako Tebbetts -week 8: Kathleen Devlin (Moved to week 9) -week 8: Robert Ryan Leslie -week 8: Ryan Morin -week 9: Erica Winberry -week 9: Robert Jenkins -week 9: Kathleen Devlin -week 10: Austin Scara -week 10: Marty Pitts diff --git a/Examples/Session01/students.txt b/Examples/Session01/students.txt deleted file mode 100644 index 2f992df..0000000 --- a/Examples/Session01/students.txt +++ /dev/null @@ -1,26 +0,0 @@ -name: languages -Alford, Robert Stevens: javascript php -Bauman, Bruce: chemstation macro fortran, java -Cardenas, Joseph: python C html CSS lisp javascript -Cimino, Michael: C C++ Java SQL -Cote, Ian: bash ruby perl python -Devlin, Kathleen: 4D -Fogarty, Brendan: SQL -Gusev, Andrey: perl java bash -Jenkins, Robert: assm pascal -Ku, Tiffany: python SQL -Leslie, Robert Ryan: python -Lin, Pei: SQL java R -MacCamy, Maxwell: C C++ C# assm java -Meringolo, Gabriel: python -Morin, Ryan: python sql -Ohashi, Cheryl: -Pitts, Marty: python, similink and matlab -Rosko, Eric: C C++ -Scara, Austin: VBA SQL -Teale, Marc: perl bash -Tebbetts, Masako: SQL -Vegors, Eric Starr: bash perl -Waddle, Michael: -Winberry, Erica: python -Yu, Michelle: ruby objectiveC diff --git a/Examples/Session05/cigar_party.py b/Examples/Session05/cigar_party.py new file mode 100644 index 0000000..e6863f4 --- /dev/null +++ b/Examples/Session05/cigar_party.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +def cigar_party(cigars, is_weekend): + pass diff --git a/Examples/Session05/codingbat.py b/Examples/Session05/codingbat.py index 3971c4e..795157d 100644 --- a/Examples/Session05/codingbat.py +++ b/Examples/Session05/codingbat.py @@ -10,4 +10,17 @@ def sleep_in(weekday, vacation): - return not (weekday and vacation) + if vacation is True: + return True + elif weekday is False: + return True + else: + return False + + +def sumdouble(a, b): + if a == b: + return (a + b) * 2 + else: + return(a + b) + diff --git a/Examples/Session05/test_cigar_party.py b/Examples/Session05/test_cigar_party.py new file mode 100644 index 0000000..260d5f4 --- /dev/null +++ b/Examples/Session05/test_cigar_party.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +# you can change this import to test different versions +from cigar_party import cigar_party +# from cigar_party import cigar_party2 as cigar_party +# from cigar_party import cigar_party3 as cigar_party + + +def test_1(): + assert cigar_party(30, False) is False + + +def test_2(): + assert cigar_party(50, False) is True + + +def test_3(): + assert cigar_party(70, True) is True + + +def test_4(): + assert cigar_party(30, True) is False + + +def test_5(): + assert cigar_party(50, True) is True + + +def test_6(): + assert cigar_party(60, False) is True + + +def test_7(): + assert cigar_party(61, False) is False + + +def test_8(): + assert cigar_party(40, False) is True + + +def test_9(): + assert cigar_party(39, False) is False + + +def test_10(): + assert cigar_party(40, True) is True + + +def test_11(): + assert cigar_party(39, True) is False diff --git a/Examples/Session05/test_codingbat.py b/Examples/Session05/test_codingbat.py index 6681bdc..4df4cf8 100755 --- a/Examples/Session05/test_codingbat.py +++ b/Examples/Session05/test_codingbat.py @@ -7,19 +7,32 @@ """ from codingbat import sleep_in +from codingbat import sumdouble def test_false_false(): - assert sleep_in(False, False) + assert sleep_in(False, False) is True def test_true_false(): - assert not (sleep_in(True, False)) + assert not (sleep_in(True, False)) is True def test_false_true(): - assert sleep_in(False, True) + assert sleep_in(False, True) is True def test_true_true(): - assert sleep_in(True, True) + assert sleep_in(True, True) is True + + +def test_sumdouble1(): + assert sumdouble(1, 2) == 3 + + +def test_sumdouble2(): + assert sumdouble(3, 2) == 5 + + +def test_sumdouble3(): + assert sumdouble(2, 2) == 8 diff --git a/Examples/Session06/test_trapz.py b/Examples/Session06/test_trapz.py new file mode 100644 index 0000000..22acf19 --- /dev/null +++ b/Examples/Session06/test_trapz.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 + +""" +test code for the trapezoidal rule exercise +""" +import pytest + +from trapz import trapz, frange, quadratic, curry_quadratic + +# need a function for testing approximate equality +import math +try: + from math import isclose +except ImportError: # only there in py3.5 + + def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): + """ + Determine whether two floating point numbers are close in value. + + rel_tol + maximum difference for being considered "close", relative to the + magnitude of the input values + abs_tol + maximum difference for being considered "close", regardless of the + magnitude of the input values + + Return True if a is close in value to b, and False otherwise. + + For the values to be considered close, the difference between them + must be smaller than at least one of the tolerances. + + -inf, inf and NaN behave similarly to the IEEE 754 Standard. That + is, NaN is not close to anything, even itself. inf and -inf are + only close to themselves. + """ + + if rel_tol < 0.0 or abs_tol < 0.0: + raise ValueError('error tolerances must be non-negative') + + if a == b: # short-circuit exact equality + return True + if math.isinf(a) or math.isinf(b): + # This includes the case of two infinities of opposite sign, or + # one infinity and one finite number. Two infinities of opposite sign + # would otherwise have an infinite relative tolerance. + return False + diff = abs(b - a) + return (((diff <= abs(rel_tol * b)) and + (diff <= abs(rel_tol * a))) or + (diff <= abs_tol)) + + +def test_is_close(): + ''' just to make sure ''' + assert isclose(4.5, 4.5) + assert isclose(4.5, 4.499999999999999999) + + assert not isclose(4.5, 4.6) + # of course, not comprehesive! + + +# you need to compute a bunch of evenly spaced numbers from a to b +# kind of like range() but for floating point numbers +# I did it as a separate function so I could test it +def test_frange(): + ''' + tests the floating point range function + ''' + r = frange(10, 20, 100) + assert len(r) == 101 + assert r[0] == 10 + assert r[-1] == 20 + assert r[1] == 10.1 + assert r[-2] == 19.9 + + +def test_simple_line(): + ''' a simple horizontal line at y = 5''' + def line(x): + return 5 + + assert trapz(line, 0, 10) == 50 + + +def test_sloping_line(): + ''' a simple linear function ''' + def line(x): + return 2 + 3*x + + # I got 159.99999999999 rather than 160 + # hence the need for isclose() + assert isclose(trapz(line, 2, 10), 160) + m, B = 3, 2 + a, b = 0, 5 + assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a)) + + a, b = 5, 10 + assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a)) + + a, b = -10, 5 + assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a)) + + +def test_sine(): + # a sine curve from zero to pi -- should be 2 + # with a hundred points, only correct to about 4 figures + assert isclose(trapz(math.sin, 0, math.pi), 2.0, rel_tol=1e-04) + + +def test_sine2(): + # a sine curve from zero to 2pi -- should be 0.0 + # need to set an absolute tolerance when comparing to zero + assert isclose(trapz(math.sin, 0, 2*math.pi), 0.0, abs_tol=1e-8) + + +# test the quadratic function itself +# this is pytest's way to test a bunch of input and output values +# it creates a separate test for each case. +@pytest.mark.parametrize(("x", "y"), [(0, 1), + (1, 3), + (2, 7), + (-2, 3) + ]) +def test_quadratic_1(x, y): + """ + one set of coefficients + """ + assert quadratic(x, A=1, B=1, C=1) == y + + +# this is a nifty trick to write multiple tests at once: +# this will generate a test for each tuple passed in: +# each tuple is an x, and the expected y result +# don't worry about that weird "@" just yet -- we'll get to that! +# (but it's called a "decorator" if you're curious) +@pytest.mark.parametrize(("x", "y"), [(0, 2), + (1, 3), + (2, 0), + (-2, -12) + ]) +def test_quadratic_2(x, y): + """ + different coefficients + """ + assert quadratic(x, A=-2, B=3, C=2) == y + + +def quad_solution(a, b, A, B, C): + """ + Analytical solution to the area under a quadratic + used for testing + """ + return A/3*(b**3 - a**3) + B/2*(b**2 - a**2) + C*(b - a) + + +def test_quadratic_trapz_1(): + """ + simplest case -- horizontal line + """ + A, B, C = 0, 0, 5 + a, b = 0, 10 + assert trapz(quadratic, a, b, A=A, B=B, C=C) == quad_solution(a, b, A, B, C) + + +def test_quadratic_trapz_2(): + """ + one case: A=-1/3, B=0, C=4 + """ + A, B, C = -1/3, 0, 4 + a, b = -2, 2 + assert isclose(trapz(quadratic, a, b, A=A, B=B, C=C), + quad_solution(a, b, A, B, C), + rel_tol=1e-3) # not a great tolerance -- maybe should try more samples! + + +def test_quadratic_trapz_args_kwargs(): + """ + Testing if you can pass a combination of positional and keyword arguments + one case: A=2, B=-4, C=3 + """ + A, B, C = 2, -4, 3 + a, b = -2, 2 + assert isclose(trapz(quadratic, a, b, A, B, C=C), + quad_solution(a, b, A, B, C), + rel_tol=1e-3) # not a great tolerance -- maybe should try more samples! + + +def test_curry_quadratic(): + # tests if the quadratic currying function + + # create a specific quadratic function: + quad234 = curry_quadratic(2, 3, 4) + # quad234 is now a function that can take one argument, x + # and will evaluate quadratic for those particular values of A,B,C + + # try it for a few values + for x in range(5): + assert quad234(x) == quadratic(x, 2, 3, 4) + + +def test_curry_quadratic_trapz(): + # tests if the quadratic currying function + + # create a specific quadratic function: + quad234 = curry_quadratic(-2, 2, 3) + # quad234 is now a function that can take one argument, x + # and will evaluate quadratic for those particular values of A,B,C + + # try it with the trapz function + assert trapz(quad234, -5, 5) == trapz(quadratic, -5, 5, -2, 2, 3) + + +# testing the functools.partial version: +from trapz import quad_partial_123 +def test_partial(): + a = 4 + b = 10 + # quad_partial_123 is the quadratic function with A,B,C = 1,2,3 + assert trapz(quad_partial_123, a, b) == trapz(quadratic, a, b, 1, 2, 3) + + +# testing trapz with another function with multiple parameters. +def sine_freq_amp(t, amp, freq): + "the sine function with a frequency and amplitude specified" + return amp * math.sin(freq * t) + + +def solution_freq_amp(a, b, amp, freq): + " the solution to the definite integral of the general sin function" + return amp / freq * (math.cos(freq * a) - math.cos(freq * b)) + + +def test_sine_freq_amp(): + a = 0 + b = 5 + omega = 0.5 + amp = 10 + assert isclose(trapz(sine_freq_amp, a, b, amp=amp, freq=omega), + solution_freq_amp(a, b, amp, omega), + rel_tol=1e-04) diff --git a/Examples/Session06/closure.py b/Examples/Session09/closure.py similarity index 100% rename from Examples/Session06/closure.py rename to Examples/Session09/closure.py diff --git a/Examples/students.txt b/Examples/students.txt new file mode 100644 index 0000000..4498763 --- /dev/null +++ b/Examples/students.txt @@ -0,0 +1,25 @@ +Bindhu, Krishna: English, C, C++, Verilog +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembly +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: Python, JAVA, VBA, SQL, English, Chinese +Riehle, Rick: English, Python, Clojure, C, C++, SQL, Fortran, Pascal, Perl, R, Octave, Bash, Basic, Assembly \ No newline at end of file diff --git a/README.rst b/README.rst index 4ee4e0e..622628a 100644 --- a/README.rst +++ b/README.rst @@ -11,4 +11,4 @@ See the Syllabus for more detail. Class lecture materials are available in a rendered version from: -http://uwpce-pythoncert.github.io/IntroPython2016a \ No newline at end of file +http://uwpce-pythoncert.github.io/IntroPython2016a diff --git a/notebooks/ClassMethods.ipynb b/notebooks/ClassMethods.ipynb new file mode 100644 index 0000000..e44a01c --- /dev/null +++ b/notebooks/ClassMethods.ipynb @@ -0,0 +1,269 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Classy(object):\n", + " x = 2\n", + " \n", + " @classmethod\n", + " def class_method(cls, y):\n", + " print(\"In class_method: \", cls)\n", + " return y ** cls.x\n", + " \n", + " def bound_method(self):\n", + " print(\"In bound_method\")\n", + " \n", + " def unbound_method():\n", + " print(\"In unbound_method\")" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Classy.class_method" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "In class_method: \n" + ] + }, + { + "data": { + "text/plain": [ + "16" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Classy.class_method(4)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class SubClassy(Classy):\n", + " x = 3" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "In class_method: \n" + ] + }, + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Classy.class_method(2)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Classy.bound_method" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_classy = Classy()" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_classy.bound_method" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Classy.unbound_method" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "unbound_method() takes 0 positional arguments but 1 was given", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_classy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0munbound_method\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: unbound_method() takes 0 positional arguments but 1 was given" + ] + } + ], + "source": [ + "my_classy.unbound_method()" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "In unbound_method\n" + ] + } + ], + "source": [ + "Classy.unbound_method()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/ClassVsInstanceAttributes.ipynb b/notebooks/ClassVsInstanceAttributes.ipynb new file mode 100644 index 0000000..71b5ca8 --- /dev/null +++ b/notebooks/ClassVsInstanceAttributes.ipynb @@ -0,0 +1,600 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyClass(object):\n", + " my_class_attribute1 = \"This is a class attribute\"\n", + " my_class_attribute2 = \"All instances of the class will have this\"\n", + "\n", + " def __init__(self, a, b):\n", + " \"\"\"\n", + " Define instance attributes here\n", + " These will be unique to each instance of the class\n", + " \"\"\"\n", + " self.content = []\n", + " self.x = a\n", + " self.y = b" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### I think of classes as templates or blueprints for instances of the class. It is an imperfect metaphor, yet useful. Remember that just about everything in Python is an object and dir() provides an easy way to inspect things. What do we get out of the gate once the class is defined? Note that we have not yet created an instance from it." + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'my_class_attribute1',\n", + " 'my_class_attribute2']" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(MyClass)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Now let's create an instance of the class." + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_instance = MyClass(3,4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What do we get once we have created an instance of the class? How does it differ from the class itself?" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'content',\n", + " 'my_class_attribute1',\n", + " 'my_class_attribute2',\n", + " 'x',\n", + " 'y']" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(my_instance)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's take a closer look..." + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "mappingproxy({'__init__': , 'my_class_attribute2': 'All instances of the class will have this', '__weakref__': , '__doc__': None, 'my_class_attribute1': 'This is a class attribute', '__dict__': , '__module__': '__main__'})" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "MyClass.__dict__" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'content': [], 'x': 3, 'y': 4}" + ] + }, + "execution_count": 54, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.__dict__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Ah! So the class attributes appear in the class's dictionary (namespace) whereas the instance attributes appear in the instance's dictionary (namespace). What sorts of behaviors might we expect from this?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's work with instance attributes" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_instance.content = ['a', 'b', 'c']" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b', 'c']" + ] + }, + "execution_count": 56, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.content" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's create a second instance" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_second_instance = MyClass(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_second_instance.content = [6, 7, 8]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Since self.content is an instance attribute, each instance gets its own" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b', 'c']" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.content" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[6, 7, 8]" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_second_instance.content" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Since my_class_attribute1 and my_class_attribute2 are class attributes, the instances share" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a class attribute'" + ] + }, + "execution_count": 61, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.my_class_attribute1" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a class attribute'" + ] + }, + "execution_count": 62, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_second_instance.my_class_attribute1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What happens when I change a class attribute?" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_instance.my_class_attribute1 = \"New value for my_class_attribute1\"" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'New value for my_class_attribute1'" + ] + }, + "execution_count": 64, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.my_class_attribute1" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a class attribute'" + ] + }, + "execution_count": 65, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_second_instance.my_class_attribute1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What??? Interersting, eh? I thouht we *modified* the *class attribute*, yet it was unchanged for my_second_instance. What's going on? Let's take a look at those dicts (namespaces) again...." + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "mappingproxy({'__init__': , 'my_class_attribute2': 'All instances of the class will have this', '__weakref__': , '__doc__': None, 'my_class_attribute1': 'This is a class attribute', '__dict__': , '__module__': '__main__'})" + ] + }, + "execution_count": 66, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "MyClass.__dict__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Huh. Scanning back to where we looked at this earlier it looks pretty much the same... perhaps exactly the same? How about the instance's dict/namespace?" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'content': ['a', 'b', 'c'],\n", + " 'my_class_attribute1': 'New value for my_class_attribute1',\n", + " 'x': 3,\n", + " 'y': 4}" + ] + }, + "execution_count": 67, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.__dict__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Woah! There it is... we now have an *instance* attribute called *my_class_attribute1*! We did not *modify* a class attribute, as we thought we had several steps above, rather, we created a new attribute on our instance with the same name as the class attribute, effectively overriding the class attribute. Gotcha! How do we get access to the original class attribute?" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a class attribute'" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "MyClass.my_class_attribute1" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "### Hmm.. okay, but I'd like to access the original class attribute via the instance." + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a class attribute'" + ] + }, + "execution_count": 69, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_instance.__class__.my_class_attribute1" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Exceptions_Lab.ipynb b/notebooks/Exceptions_Lab.ipynb new file mode 100644 index 0000000..7b528c5 --- /dev/null +++ b/notebooks/Exceptions_Lab.ipynb @@ -0,0 +1,184 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Focus on input()" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on method raw_input in module ipykernel.kernelbase:\n", + "\n", + "raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance\n", + " Forward raw_input to frontends\n", + " \n", + " Raises\n", + " ------\n", + " StdinNotImplentedError if active frontend doesn't support stdin.\n", + "\n" + ] + } + ], + "source": [ + "help(input)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Two Exceptions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- EOFError: Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data. \n", + "- KeyboardInterrupt: Raised when the user hits the interrupt key (normally Control-C or Delete). " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Logic" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Create a wrapper function, perhaps safe_input() that returns None rather rather than raising these exceptions, when the user enters ^C for Keyboard Interrupt, or ^D (^Z on Windows) for End Of File." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def a function asking for user input(see help(input()) for required args):\n", + " try:\n", + " getting a response from the user\n", + " return that response\n", + " except for EOFError, KeyboardInterrupt:\n", + " when this happens, return none instead of the error" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### One possible implimentation\n" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def safe_input(message):\n", + " try:\n", + " user_input = input(message)\n", + " return user_input\n", + " except (KeyboardInterrupt, EOFError):\n", + " return None" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Yoyo! asdf\n" + ] + } + ], + "source": [ + "response = safe_input(\"Yoyo! \")" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'asdf'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "response" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### As a demo this works better in straight ipython rather than in the notebook, because you can better see what happens when you hit ^c or ^d." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/HTML_Rendering.ipynb b/notebooks/HTML_Rendering.ipynb new file mode 100644 index 0000000..536404e --- /dev/null +++ b/notebooks/HTML_Rendering.ipynb @@ -0,0 +1,990 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Overview of Basic HTML syntax" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# let the renderer know this is html\n", + "\n", + "\n", + "# document starts here\n", + "\n", + "\n", + " # tags label different sections with the format\n", + " # \n", + " # stuff in here\n", + " # \n", + " \n", + " \n", + " PythonClass = Revision 1087:\n", + " \n", + " \n", + " # h1, h2, h3 = heading types\n", + "

PythonClass - Class 6 example

\n", + " \n", + " # p = paragraph and defining attributes\n", + "

\n", + " Here is a paragraph of text -- there could be more of them, \n", + " but this is enough to show that we can do some text\n", + "

\n", + " \n", + " # hr = horizontal rule\n", + "
\n", + " \n", + " # ul = unordered list\n", + "
    \n", + " # li = list item, will show as bullets\n", + "
  • \n", + " The first item in a list\n", + "
  • \n", + "
  • \n", + " This is the second item\n", + "
  • \n", + "
  • \n", + " And this is a \n", + " # anchor tag for html link\n", + " link\n", + " to google\n", + "
  • \n", + "
\n", + " \n", + "\n", + "# ^ closing all the things" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Assignment" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Goal: Create a set of classes that will make this syntax a lot prettier to read" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## HTML Rendering Script" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "https://github.com/UWPCE-PythonCert/IntroPython2016a/blob/master/Examples/Session07/html_render/run_html_render.py/n", + "\n", + "- Broken down into steps\n", + "- Uncomment each step as you work through \n", + "- Encourages using test-driven development" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Review of OOP Basics" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### What is a class? \n", + " - Logical grouping of data and functions\n", + " - Instruction manual for constructing objects, not the actual creation\n", + " \n", + " The following example is from: \n", + " https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Customer(object):\n", + " \"\"\"A customer of ABC Bank with a checking account. Customers have the\n", + " following properties:\n", + "\n", + " Attributes:\n", + " name: A string representing the customer's name.\n", + " balance: A float tracking the current balance of the customer's account.\n", + " \"\"\"\n", + "\n", + " def __init__(self, name, balance=0.0):\n", + " \"\"\"Return a Customer object whose name is *name* and starting\n", + " balance is *balance*.\"\"\"\n", + " self.name = name\n", + " self.balance = balance\n", + "\n", + " def withdraw(self, amount):\n", + " \"\"\"Return the balance remaining after withdrawing *amount*\n", + " dollars.\"\"\"\n", + " if amount > self.balance:\n", + " raise RuntimeError('Amount greater than available balance.')\n", + " self.balance -= amount\n", + " return self.balance\n", + "\n", + " def deposit(self, amount):\n", + " \"\"\"Return the balance remaining after depositing *amount*\n", + " dollars.\"\"\"\n", + " self.balance += amount\n", + " return self.balance" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### How does this work? " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "#We create a customer object: \n", + "steve = Customer(\"Steve Jobs\", 1000.00)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "<__main__.Customer at 0x7f9dc06ba940>" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# steve is an instance of the Customer class\n", + "steve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What does self do? \n", + "\n", + "def withdraw(self, amount)\n", + "\n", + "Self is a placeholder for whatever customer you create. So when you create Steve and call the withdraw function: \n", + "\n", + " jeff.withdraw(100,000.00) \n", + "\n", + "This is shortand for Customer.withdraw(jeff, 100,000.00)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What is \\__init__ ? " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We use it to initialize objects (ready to use!), as in \n", + "\n", + " self.name = name\n", + "\n", + "Self is the instance and is equivalent to:\n", + " \n", + " steve.name = 'Steve Jobs'\n", + " \n", + "And self.balance = balance would be equivalent to:\n", + "\n", + " steve.balance = 100,000.00" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What is a Method? \n", + "\n", + "A function defined in a class" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What are Attributes? \n", + "\n", + "#### Class attributes\n", + "- Set at the class level\n", + "- Hold for all instances of a class\n", + "\n", + "Example:\n", + "\n", + " class Car(object):\n", + "\n", + " wheels = 4\n", + "\n", + " def __init__(self, make, model):\n", + " self.make = make\n", + " self.model = model\n", + "\n", + "A car will always have four wheels. \n", + "\n", + "### Instances\n", + "A class is the blueprint, but the instance is a specific copy that contains all the content created from this blueprint. \n", + "\n", + "For example, a human class where Billy Bob is an instance of human class. \n", + "\n", + "#### Instance Attributes\n", + "Declared inside an instance. " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Step 1\n", + "\n", + "#### Create an element class for rendering an html element" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# class for rendering html elements\n", + "class Element: \n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "type" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(Element)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Create class attributes for tag and indentation\n", + "\n", + "- Tag name = 'html'\n", + "- Indentation = spaces to indent for pretty printing" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# class for rendering html elements\n", + "class Element: \n", + " \n", + " # define class attributes \n", + " tag = 'html'\n", + " indent = ' '" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Add initializer signature\n", + "\n", + "- Element(content=None)\n", + "- Content is expected to be a string\n", + "- Need way to store content that can be updated (list)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def __init__(self, content=None):\n", + " # store content\n", + " content = []\n", + " # check for content\n", + " if content is not None:\n", + " self.content.append(content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Add append method\n", + "\n", + "- Can add strings to content" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + " def append(self, content):\n", + " self.content.append(content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Add render method\n", + "\n", + "- render(file_out, ind = \"\")\n", + "- renders starting from html tag and any strings in content container\n", + "- calls write()\n", + "- file_out = file writer object\n", + "- ind = string with indentation level from zero to lots of spaces, dependng on tree depth\n", + " - amt of indentation level set by class attribute indent" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# we're given this\n", + "def render(self, file_out, ind=\"\"):\n", + " \n", + " # takes a file-like object\n", + " \n", + " # calls write() method, writing html for a tag\n", + " \n", + " \n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def render(self, file_out, ind=\"\"):\n", + " # calling write method on a file object\n", + " file_out.write()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def render(self, file_out, ind=\"\"):\n", + " file_out.write()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### How do we render what's in between the tags? " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " Some content. Some more content.\n", + "<\\html>" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def render(self, file_out, ind=\"\"):\n", + " #start rendering at first html tag\n", + " start_tag = \"<{}>\".format(self.tag)\n", + " # add that start tag to your output\n", + " file_out.write(start_tag)\n", + " \n", + " # render in-between tag stuff here\n", + " \n", + " # stop at the closing html tag\n", + " end_tag = \"\".format(self.tag)\n", + " # add that tag to the end of file object\n", + " file_out.write(end_tag)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Do the stuff (rendering)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def render(self, file_out, ind=\"\"):\n", + " #start rendering at first html tag\n", + " start_tag = \"<{}>\".format(self.tag)\n", + " # add that start tag to your output\n", + " file_out.write(start_tag)\n", + " \n", + " # grab things out of content\n", + " for stuff in self.content:\n", + " try:\n", + " # render it\n", + " stuff.render(file_out)\n", + " except AttributeError:\n", + " file_out.write(str(stuff))\n", + " # stop at the closing html tag\n", + " end_tag = \"\".format(self.tag)\n", + " # add that tag to the end of file object\n", + " file_out.write(end_tag)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Code for Part 1" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# class for rendering html elements\n", + "class Element: \n", + " \n", + " # define class attributes \n", + " tag = 'html'\n", + " indent = ' '\n", + " \n", + " def __init__(self, content=None):\n", + " # store content\n", + " self.content = []\n", + " # check for content\n", + " if content is not None:\n", + " self.content.append(content)\n", + " \n", + " def append(self, content):\n", + " self.content.append(content)\n", + " \n", + " def render(self, file_out, ind=\"\"):\n", + " #start rendering at first html tag\n", + " start_tag = \"<{}>\".format(self.tag)\n", + " # add that start tag to your output\n", + " file_out.write(start_tag)\n", + " \n", + " # grab things out of content\n", + " for stuff in self.content:\n", + " try:\n", + " # render it\n", + " stuff.render(file_out)\n", + " except AttributeError:\n", + " file_out.write(str(stuff))\n", + " # stop at the closing html tag\n", + " end_tag = \"\".format(self.tag)\n", + " # add that tag to the end of file object\n", + " file_out.write(end_tag)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's try it out" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Download [sample_html.html](https://raw.githubusercontent.com/UWPCE-PythonCert/IntroPython2016a/master/Examples/Session07/html_render/sample_html.html)\n", + "- Download [run_html_render.py](https://raw.githubusercontent.com/UWPCE-PythonCert/IntroPython2016a/master/Examples/Session07/html_render/run_html_render.py)\n", + "- Save your script as html_render.py\n", + "- From your directory: \n", + " \n", + " python3 ./run_html_render.py\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " (py3env) summer@LinuxBox:~/python100_examples/Session7$ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some textAnd here is another piece of text -- you should be able to add any number" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Part 2: Create Subclasses\n", + "\n", + "#### Goal\n", + "Render more than just the content between the html tags" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Subclasses\n", + "\n", + "Taken from this [tutorial](http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/): \n", + "\n", + "Let's create a class called Pets: " + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Pet():\n", + "\n", + " def __init__(self, name, species):\n", + " self.name = name\n", + " self.species = species\n", + "\n", + " def getName(self):\n", + " return self.name\n", + "\n", + " def getSpecies(self):\n", + " return self.species\n", + "\n", + " def __str__(self):\n", + " return \"%s is a %s\" % (self.name, self.species)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Even though all pets share common, basic attributes, we can all agree that cats and dogs are different. It makes sense to keep them both under pets, to retain their common attributes, but we can create subclasses to further distinguish them. " + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Dog(Pet):\n", + "\n", + " def __init__(self, name, chases_cats):\n", + " Pet.__init__(self, name, \"Dog\")\n", + " self.chases_cats = chases_cats\n", + "\n", + " def chasesCats(self):\n", + " return self.chases_cats" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Cat(Pet):\n", + "\n", + " def __init__(self, name, hates_dogs):\n", + " Pet.__init__(self, name, \"Cat\")\n", + " self.hates_dogs = hates_dogs\n", + "\n", + " def hatesDogs(self):\n", + " return self.hates_dogs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Inheritance\n", + "\n", + "A subclass inherits all the attributes, methods, etc of the parent class. You can change alter these attributes to change the behavior, and you can add new ones. \n", + "\n", + "isinstance() is a function that can be used to see if an instance is from a certain type of class. " + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "mister_pet = Pet(\"Mister\", \"Dog\")\n", + "mister_dog = Dog(\"Mister\", True)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Mister is a Dog\n" + ] + } + ], + "source": [ + "print (mister_pet)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Mister is a Dog\n" + ] + } + ], + "source": [ + "print (mister_dog)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(mister_pet, Pet)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(mister_pet, Dog)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(mister_dog, Pet)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(mister_dog, Dog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create html, body and p subclasses" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Body(Element):\n", + " tag = 'body'\n", + "\n", + "class P(Element):\n", + " tag = 'p'\n", + " \n", + "class html(Element):\n", + " tag = 'html'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Update render method to work for these other elements" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Element(object):\n", + "\n", + " tag = 'html' # shouldn't really be usable without properly subclassing\n", + " indent = ' '\n", + "\n", + " def __init__(self, content=None, **attributes):\n", + "\n", + " self.content = []\n", + " # adding attributes dictionary\n", + " self.attributes = attributes\n", + "\n", + " if content is not None:\n", + " self.content.append(content)\n", + "\n", + " def append(self, content):\n", + " self.content.append(content)\n", + "\n", + " # added render tag method to deal with any type of tag at indentation level\n", + " def render_tag(self, current_ind):\n", + " # tag and then content for each class\n", + " attrs = \"\".join([' {}=\"{}\"'.format(key, val) for key, val in self.attributes.items()])\n", + " # indetation + tag + content\n", + " tag_str = \"{}<{}{}>\".format(current_ind, self.tag, attrs)\n", + " return tag_str\n", + "\n", + " def render(self, file_out, current_ind=\"\"):\n", + " # render method now calls the render tag method instead of just a string\n", + " file_out.write(self.render_tag(current_ind))\n", + " file_out.write('\\n')\n", + " for con in self.content:\n", + " try:\n", + " file_out.write(current_ind + self.indent + con+\"\\n\")\n", + " except TypeError:\n", + " con.render(file_out, current_ind+self.indent)\n", + " # write out closing tag\n", + " file_out.write(\"{}\\n\".format(current_ind, self.tag))\n", + " \n", + "class Body(Element):\n", + " tag = 'body'\n", + "\n", + "class P(Element):\n", + " tag = 'p'\n", + " \n", + "class Html(Element):\n", + " tag = 'html'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's try out Step 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Download [test_html_output2.html](https://github.com/UWPCE-PythonCert/IntroPython2016a/blob/master/Examples/Session07/html_render/test_html_output2.html)\n", + "- Comment out Part 1 of run_html_render.py\n", + "- Uncomment Part 2 of run_html_render.py" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "summer@LinuxBox:~/python100_examples/Session7$ python3 ./run_html_render.py \n", + " \n", + " \n", + "

\n", + " Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text\n", + "

\n", + "

\n", + " And here is another piece of text -- you should be able to add any number\n", + "

\n", + " \n", + " " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/HTML_Rendering_Part_Deux.ipynb b/notebooks/HTML_Rendering_Part_Deux.ipynb new file mode 100644 index 0000000..5845fa2 --- /dev/null +++ b/notebooks/HTML_Rendering_Part_Deux.ipynb @@ -0,0 +1,555 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Recap Step 2\n", + "\n", + "- We can render a basic web page\n", + "- We can handle html, body and p tags\n", + "- Everything is indented nicely" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Element(object):\n", + "\n", + " tag = 'html' # shouldn't really be usable without properly subclassing\n", + " indent = ' '\n", + "\n", + " def __init__(self, content=None, **attributes):\n", + "\n", + " self.content = []\n", + " # adding attributes dictionary\n", + " self.attributes = attributes\n", + "\n", + " if content is not None:\n", + " self.content.append(content)\n", + "\n", + " def append(self, content):\n", + " self.content.append(content)\n", + "\n", + " # added render tag method to deal with any type of tag at indentation level\n", + " def render_tag(self, current_ind):\n", + " # tag and then content for each class\n", + " attrs = \"\".join([' {}=\"{}\"'.format(key, val) for key, val in self.attributes.items()])\n", + " # indetation + tag + content\n", + " tag_str = \"{}<{}{}>\".format(current_ind, self.tag, attrs)\n", + " return tag_str\n", + "\n", + " def render(self, file_out, current_ind=\"\"):\n", + " # render method now calls the render tag method instead of just a string\n", + " file_out.write(self.render_tag(current_ind))\n", + " file_out.write('\\n')\n", + " for con in self.content:\n", + " try:\n", + " file_out.write(current_ind + self.indent + con+\"\\n\")\n", + " except TypeError:\n", + " con.render(file_out, current_ind+self.indent)\n", + " # write out closing tag\n", + " file_out.write(\"{}\\n\".format(current_ind, self.tag))\n", + " \n", + "class Body(Element):\n", + " tag = 'body'\n", + "\n", + "class P(Element):\n", + " tag = 'p'\n", + " \n", + "class Html(Element):\n", + " tag = 'html'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Create a subclass for a head tag\n", + "- Create a OneLineTag subclass of Element\n", + " - Override the render method to render everything on one line\n", + "- Create a Title subclass of OneLineTag\n", + "\n", + "#### Goal\n", + "- Render an html doc with a head, title, body and p elements" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a subclass for a head tag" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Head(Element):\n", + " tag = 'head'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a OneLineTag subclass of element\n", + "\n", + "- override render method to render everything between a tag on one line" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Overriding \n", + "\n", + "- Changing the implementation of a method provided by a parent class. \n", + "- Copy another class, avoiding duplication, but customize and enhance to fit your needs\n", + "- Define in the child class a method with the same name as the method in the parent class\n", + "- Good practice: call the original implementation of a method whenever possible (super())\n", + "\n", + "Great tutorial [here](http://lgiordani.com/blog/2014/05/19/method-overriding-in-python/#.VtO-ER9ytBQ)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Parent(object):\n", + " def __init__(self):\n", + " self.value = 5\n", + "\n", + " def get_value(self):\n", + " return self.value\n", + "\n", + "class Child(Parent):\n", + " def get_value(self):\n", + " return self.value + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c = Child()\n", + "\n", + "c.get_value()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Here's our original render method" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def render(self, file_out, current_ind=\"\"):\n", + " # render method now calls the render tag method instead of just a string\n", + " file_out.write(self.render_tag(current_ind))\n", + " file_out.write('\\n')\n", + " for con in self.content:\n", + " try:\n", + " file_out.write(current_ind + self.indent + con+\"\\n\")\n", + " except TypeError:\n", + " con.render(file_out, current_ind+self.indent)\n", + " # write out closing tag\n", + " file_out.write(\"{}\\n\".format(current_ind, self.tag))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Render everything on one line" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class OneLineTag(Element):\n", + " def render(self, file_out, current_ind=''):\n", + " # remove the new line \n", + " file_out.write(self, render_tag(current_ind))\n", + " for con in self.content:\n", + " # skip the indentation\n", + " file_out.write(con)\n", + " file_out.write(\"\\n\".format(self.tag))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Put it all together for Step 3" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Element(object):\n", + "\n", + " tag = 'html' # shouldn't really be usable without properly subclassing\n", + " indent = ' '\n", + "\n", + " def __init__(self, content=None, **attributes):\n", + "\n", + " self.content = []\n", + " # adding attributes dictionary\n", + " self.attributes = attributes\n", + "\n", + " if content is not None:\n", + " self.content.append(content)\n", + "\n", + " def append(self, content):\n", + " self.content.append(content)\n", + "\n", + " # added render tag method to deal with any type of tag at indentation level\n", + " def render_tag(self, current_ind):\n", + " # tag and then content for each class\n", + " attrs = \"\".join([' {}=\"{}\"'.format(key, val) for key, val in self.attributes.items()])\n", + " # indetation + tag + content\n", + " tag_str = \"{}<{}{}>\".format(current_ind, self.tag, attrs)\n", + " return tag_str\n", + "\n", + " def render(self, file_out, current_ind=\"\"):\n", + " # render method now calls the render tag method instead of just a string\n", + " file_out.write(self.render_tag(current_ind))\n", + " file_out.write('\\n')\n", + " for con in self.content:\n", + " try:\n", + " file_out.write(current_ind + self.indent + con+\"\\n\")\n", + " except TypeError:\n", + " con.render(file_out, current_ind+self.indent)\n", + " # write out closing tag\n", + " file_out.write(\"{}\\n\".format(current_ind, self.tag))\n", + " \n", + "class Body(Element):\n", + " tag = 'body'\n", + "\n", + "class P(Element):\n", + " tag = 'p'\n", + " \n", + "class Html(Element):\n", + " tag = 'html'\n", + " \n", + "class Head(Element):\n", + " tag = 'head'\n", + " \n", + "class OneLineTag(Element):\n", + " def render(self, file_out, current_ind=''):\n", + " # remove the new line \n", + " file_out.write(self, render_tag(current_ind))\n", + " for con in self.content:\n", + " # skip the indentation\n", + " file_out.write(con)\n", + " file_out.write(\"\\n\".format(self.tag))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 4\n", + "\n", + "- Extend Element class to accept attributes as keywords (**kwargs)\n", + "- Update render method to work with attributes\n", + "\n", + "#### Goal\n", + "Render tags with attributes" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + " def __init__(self, content=None, **attributes):\n", + "\n", + " self.content = []\n", + " # adding attributes dictionary\n", + " self.attributes = attributes\n", + "\n", + " if content is not None:\n", + " self.content.append(content)\n", + " \n", + "# added render tag method to deal with any type of tag at indentation level\n", + " def render_tag(self, current_ind):\n", + " # tag and then content for each class\n", + " attrs = \"\".join([' {}=\"{}\"'.format(key, val) for key, val in self.attributes.items()])\n", + " # indetation + tag + content\n", + " tag_str = \"{}<{}{}>\".format(current_ind, self.tag, attrs)\n", + " return tag_str" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 5\n", + "\n", + "- Create a SelfClosingTag subclass to render things like horizontal rule and line breaks\n", + " - < hr /> \n", + " - < br />\n", + "- Override render method to render just one tag and attributes (if any)\n", + "- Create subclasses of SelfClosingTag for < hr /> and < br /> " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class SelfClosingTag(Element):\n", + " def render(self, file_out, current_ind=''):\n", + " # calling render tag, but not adding the regular closing\n", + " file_out.write(self.render_tag(current_ind)[:-1])\n", + " # adding the self-closing tag instead\n", + " file_out.write(\" />\\n\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Hr(SelfClosingTag):\n", + " tag = 'hr'\n", + "\n", + "class Br(SelfClosingTag):\n", + " tag = 'br'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 6\n", + "\n", + "- Create an A class for anchor (link) element \n", + "- A(self, link, content)\n", + " - link = link\n", + " - content is the text that contains the link, such as \"Click here!\"\n", + "- Override the \\__init__ from Element" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class A(Element):\n", + " # define our tag\n", + " tag = 'a'\n", + "\n", + " # override init method using constructor given in hw\n", + " def __init__(self, link, content=None, **attributes):\n", + " Element.__init__(self, content, **attributes)\n", + " # pulling out the link from the attributes dictionary\n", + " self.attributes[\"href\"] = link" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 7\n", + "- Create ul class for unordered lists, as a subclass of Element\n", + "- Create a li class for ordered lists, subclass of Element\n", + "- Create a Header class that takes an int argumentfor header level < h1 > < h2 > etc\n", + " - Called like H(2, \"Text of header\") for an < h2 > header\n", + " - Subclass OneLineTag\n", + " - Overriding the \\__init__\n", + " - Then calling superclass \\__init" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Ul(Element):\n", + " tag = 'ul'\n", + " \n", + "class Li(Element):\n", + " tag = 'li'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class H(OneLineTag):\n", + " def __init__(self, level, content=None, **attributes):\n", + " OneLineTag.__init__(self, content, **attributes)\n", + " self.tag = \"h{:d}\".format(level)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 8" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Update HTML Element to render < !DOCTYPE html > tags\n", + " - Subclass Element and override render()\n", + " - Call Element render from new render\n", + "- Create subclass of SelfClosingTag for < meta charset=\"UTF 8\" /> \n", + " - Like the Hr subclass\n", + " - Add Meta Element to beginning of head element to encode your document" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Html(Element):\n", + " tag = 'html'\n", + "\n", + " def render(self, file_out, current_ind=\"\"):\n", + " file_out.write(\"\\n\")\n", + " Element.render(self, file_out, current_ind=current_ind)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### charset\n", + "\n", + "To display a page properly, the browser must know the character set used on the page. This is specified in the meta tag. \n", + "\n", + "< meta charset=\"UTF-8\" >" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Meta(SelfClosingTag):\n", + " tag = \"meta\"\n", + "\n", + " def __init__(self, content=None, **attributes):\n", + " # give it a default value for charset\n", + " if \"charset\" not in attributes:\n", + " attributes['charset'] = \"UTF-8\"\n", + " SelfClosingTag.__init__(self, content, **attributes)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/HowToGetInitToUseYourSetter.ipynb b/notebooks/HowToGetInitToUseYourSetter.ipynb new file mode 100644 index 0000000..463f62d --- /dev/null +++ b/notebooks/HowToGetInitToUseYourSetter.ipynb @@ -0,0 +1,161 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### In the following code we want to trigger the exception if we are not passed Bob Jones" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Person:\n", + " def __init__(self, name=None):\n", + " self._name=name # Note that we're calling the _attribute, not the @property\n", + "\n", + " @property\n", + " def name(self):\n", + " return self._name\n", + "\n", + " @name.setter\n", + " def name(self,value):\n", + " if not (value in ('Bob Jones')):\n", + " raise Exception (\"Invalid Bob\")\n", + " self._name = value" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "bob = Person(\"Bob Smith\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Bob Smith'" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "bob.name" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Uh oh... Bob Smith is an invalid Bob... what went wrong? Let's try again...." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Person:\n", + " def __init__(self, name=None):\n", + " self.name = name # Note that I'm calling the @property, not the _attribute.\n", + "\n", + " @property\n", + " def name(self):\n", + " return self._name\n", + "\n", + " @name.setter\n", + " def name(self,value):\n", + " if not (value in ('Bob Jones')):\n", + " raise Exception (\"Invalid Bob\")\n", + " self._name = value" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "Exception", + "evalue": "Invalid Bob", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mbob\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mPerson\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Bob Smith\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36m__init__\u001b[0;34m(self, name)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mclass\u001b[0m \u001b[0mPerson\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m__init__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m@\u001b[0m\u001b[0mproperty\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m\u001b[0m in \u001b[0;36mname\u001b[0;34m(self, value)\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mvalue\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m'Bob Jones'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\"Invalid Bob\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_name\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mException\u001b[0m: Invalid Bob" + ] + } + ], + "source": [ + "bob = Person(\"Bob Smith\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "### See the difference? Look at the declaration of name vs \\_name in the \\_\\_init\\_\\_" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Lambda_Lab.ipynb b/notebooks/Lambda_Lab.ipynb new file mode 100644 index 0000000..3d71703 --- /dev/null +++ b/notebooks/Lambda_Lab.ipynb @@ -0,0 +1,256 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is lambda? \n", + "\n", + "- A shortcut for building one-off functions\n", + "- Define functions in-line" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Traditional function\n", + "\n", + "import math\n", + "def square_root(x):\n", + " return math.sqrt(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# using lambda\n", + "\n", + "square_rt = lambda x: math.sqrt(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5.0" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square_root(25)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5.0" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square_rt(25)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## When should you use lambda? " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Functions that should only be used once\n", + "- Code that only performs one, well-defined task\n", + "- Passing a function to other functions\n", + "- Cleaner code, avoid duplication" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# traditional function\n", + "def square(x):\n", + " return x**2\n", + "square(5)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# lambda\n", + "square = lambda x: x**2\n", + "square(5)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[25]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# list comprehension\n", + "a = [5]\n", + "[x**2 for x in a]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Lambda Lab" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# write a function\n", + "def function_builder():\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# return a list of n functions\n", + "\n", + "def function_builder(n):\n", + " func_list = []\n", + " for i in range(n):\n", + " func_list.append(insert lambda function here)\n", + " return (func_list)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# fill in lambda function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# update function to use list comprehension" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/OfficeHours_2016-02-21.ipynb b/notebooks/OfficeHours_2016-02-21.ipynb new file mode 100644 index 0000000..07d3251 --- /dev/null +++ b/notebooks/OfficeHours_2016-02-21.ipynb @@ -0,0 +1,438 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyClass(object):\n", + " my_class_attribute1 = \"This is a class attribute\"\n", + " my_class_attribute2 = \"All instances of the class will have this\"\n", + "\n", + " def __init__(self, a, b):\n", + " \"\"\"\n", + " Define instance attributes here\n", + " These will be unique to each instance of the class\n", + " \"\"\"\n", + " self.content = []\n", + " self.x = a\n", + " self.y = b\n", + " \n", + " def assign_content(self, my_list):\n", + " self.content = my_list\n", + " \n", + " def show_me_my_content(self):\n", + " print(self.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### I think of classes as templates or blueprints for instances of the class. It is an imperfect metaphor, yet perhaps useful. Remember that just about everything in Python is an object and dir() provides an easy way to inspect things. What do we get out of the gate once the class is defined? Note that we have not yet created an instance from it." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'assign_content',\n", + " 'my_class_attribute1',\n", + " 'my_class_attribute2',\n", + " 'show_me_my_content']" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(MyClass)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Now let's create an instance of the class." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_instance = MyClass(3,4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What do we get once we have created an instance of the calss?" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'assign_content',\n", + " 'content',\n", + " 'my_class_attribute1',\n", + " 'my_class_attribute2',\n", + " 'show_me_my_content',\n", + " 'x',\n", + " 'y']" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(my_instance)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a_list = ['a', 'b', 'c']" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_instance.assign_content(a_list)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'b', 'c']\n" + ] + } + ], + "source": [ + "my_instance.show_me_my_content()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b_list = [6, 7, 8]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_instance.assign_content(b_list)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[6, 7, 8]\n" + ] + } + ], + "source": [ + "my_instance.show_me_my_content()" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_second_instance = MyClass(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_second_instance.assign_content(a_list)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Since .content is an instance attribute, each instance gets its own" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'b', 'c']\n" + ] + } + ], + "source": [ + "my_second_instance.show_me_my_content()" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[6, 7, 8]\n" + ] + } + ], + "source": [ + "my_instance.show_me_my_content()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Need a little help? Try help()" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function append:\n", + "\n", + "append(...) method of builtins.list instance\n", + " L.append(object) -> None -- append object to end\n", + "\n" + ] + } + ], + "source": [ + "help(a_list.append)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Fun with strings" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "string1 = \"string_one\"" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "string2 = \"string_two\"" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "string3 = string1 + string2" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'string_onestring_two'" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "string3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Session05.ipynb b/notebooks/Session05.ipynb new file mode 100644 index 0000000..afa2bad --- /dev/null +++ b/notebooks/Session05.ipynb @@ -0,0 +1,1202 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Strings\n", + "=======" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "stringa = \"this is a string\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'this is a string'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "stringa" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(stringa)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(str(33.55))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "csv = \"123, 654, 26\"" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['123', '654', '26']" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "csv.split(', ')" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "csv.split?" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "pipe_separated_values = '|'.join(csv.split(', '))" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'123|654|26'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pipe_separated_values" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Raw strings\n", + "-----------" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "new_line = '\\n'" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "There is going to be a space below this line\n", + "\n", + "and a line here at the bottom\n" + ] + } + ], + "source": [ + "print('There is going to be a space below this line' + new_line + new_line + 'and a line here at the bottom')" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "raw_string = r'one\\two'" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'one\\\\two'" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "raw_string" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "regular_string = 'one\\two'" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'one\\two'" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "regular_string" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "one\two\n" + ] + } + ], + "source": [ + "print(regular_string)" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "one\\two\n" + ] + } + ], + "source": [ + "print(raw_string)" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "EOL while scanning string literal (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m this_is_bad = r\"\\\"\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m EOL while scanning string literal\n" + ] + } + ], + "source": [ + "this_is_bad = r\"\\\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "... so ya gotta ask yourself... how raw is raw?" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "this_is_less_bad = r\"\\\\\"" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\\\\\n" + ] + } + ], + "source": [ + "print(this_is_less_bad)" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "121\n", + "111\n", + "100\n", + "97\n" + ] + } + ], + "source": [ + "for i in 'yoda':\n", + " print(ord(i))" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "yoda" + ] + } + ], + "source": [ + "for i in(\n", + " 121,\n", + " 111,\n", + " 100,\n", + " 97,\n", + " ):\n", + " print(chr(i), end='', )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "string formatting\n", + "-----------------" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note use of stringa from way up top toward the beginning of the notebook." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "stringb = \"And here's another\"" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Hello this is a string! And here's another\"" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {first_string}! {second_string}'.format(second_string=stringb, first_string=stringa, )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lab: string formatting\n", + "-----------------------" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "http://uwpce-pythoncert.github.io/IntroPython2016a/exercises/string_formatting.html" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Files & Streams\n", + "===============" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Session05.ipynb students.txt\r\n" + ] + } + ], + "source": [ + "!ls" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "with open('students.txt', 'r') as f:\n", + " read_data = f.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "f.closed" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Bindhu, Krishna\\nBounds, Brennen\\nGregor, Michael\\nHolmer, Deana\\nKumar, Pradeep\\nRees, Susan\\nRudolph, John\\nSolomon, Tsega\\nWarren, Benjamin\\nAleson, Brandon\\nChang, Jaemin\\nChinn, Kyle\\nDerdouri, Abderrazak\\nFannin, Calvin\\nGaffney, Thomas\\nGlogowski, Bryan\\nHo, Chi Kin\\nMcKeag, Gregory\\nMyerscough, Damian\\nNewton, Michael\\nSarpangala, Kishan\\nSchincariol, Mike\\nZhao, Yuanrui\\n'" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_data" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Bindhu, Krishna\n", + "Bounds, Brennen\n", + "Gregor, Michael\n", + "Holmer, Deana\n", + "Kumar, Pradeep\n", + "Rees, Susan\n", + "Rudolph, John\n", + "Solomon, Tsega\n", + "Warren, Benjamin\n", + "Aleson, Brandon\n", + "Chang, Jaemin\n", + "Chinn, Kyle\n", + "Derdouri, Abderrazak\n", + "Fannin, Calvin\n", + "Gaffney, Thomas\n", + "Glogowski, Bryan\n", + "Ho, Chi Kin\n", + "McKeag, Gregory\n", + "Myerscough, Damian\n", + "Newton, Michael\n", + "Sarpangala, Kishan\n", + "Schincariol, Mike\n", + "Zhao, Yuanrui\n", + "\n" + ] + } + ], + "source": [ + "print(read_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import io" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['BlockingIOError',\n", + " 'BufferedIOBase',\n", + " 'BufferedRWPair',\n", + " 'BufferedRandom',\n", + " 'BufferedReader',\n", + " 'BufferedWriter',\n", + " 'BytesIO',\n", + " 'DEFAULT_BUFFER_SIZE',\n", + " 'FileIO',\n", + " 'IOBase',\n", + " 'IncrementalNewlineDecoder',\n", + " 'OpenWrapper',\n", + " 'RawIOBase',\n", + " 'SEEK_CUR',\n", + " 'SEEK_END',\n", + " 'SEEK_SET',\n", + " 'StringIO',\n", + " 'TextIOBase',\n", + " 'TextIOWrapper',\n", + " 'UnsupportedOperation',\n", + " '__all__',\n", + " '__author__',\n", + " '__builtins__',\n", + " '__cached__',\n", + " '__doc__',\n", + " '__file__',\n", + " '__loader__',\n", + " '__name__',\n", + " '__package__',\n", + " '__spec__',\n", + " '_io',\n", + " 'abc',\n", + " 'open']" + ] + }, + "execution_count": 55, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(io)" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import os" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['CLD_CONTINUED',\n", + " 'CLD_DUMPED',\n", + " 'CLD_EXITED',\n", + " 'CLD_TRAPPED',\n", + " 'EX_CANTCREAT',\n", + " 'EX_CONFIG',\n", + " 'EX_DATAERR',\n", + " 'EX_IOERR',\n", + " 'EX_NOHOST',\n", + " 'EX_NOINPUT',\n", + " 'EX_NOPERM',\n", + " 'EX_NOUSER',\n", + " 'EX_OK',\n", + " 'EX_OSERR',\n", + " 'EX_OSFILE',\n", + " 'EX_PROTOCOL',\n", + " 'EX_SOFTWARE',\n", + " 'EX_TEMPFAIL',\n", + " 'EX_UNAVAILABLE',\n", + " 'EX_USAGE',\n", + " 'F_LOCK',\n", + " 'F_OK',\n", + " 'F_TEST',\n", + " 'F_TLOCK',\n", + " 'F_ULOCK',\n", + " 'MutableMapping',\n", + " 'NGROUPS_MAX',\n", + " 'O_ACCMODE',\n", + " 'O_APPEND',\n", + " 'O_ASYNC',\n", + " 'O_CLOEXEC',\n", + " 'O_CREAT',\n", + " 'O_DIRECTORY',\n", + " 'O_DSYNC',\n", + " 'O_EXCL',\n", + " 'O_EXLOCK',\n", + " 'O_NDELAY',\n", + " 'O_NOCTTY',\n", + " 'O_NOFOLLOW',\n", + " 'O_NONBLOCK',\n", + " 'O_RDONLY',\n", + " 'O_RDWR',\n", + " 'O_SHLOCK',\n", + " 'O_SYNC',\n", + " 'O_TRUNC',\n", + " 'O_WRONLY',\n", + " 'PRIO_PGRP',\n", + " 'PRIO_PROCESS',\n", + " 'PRIO_USER',\n", + " 'P_ALL',\n", + " 'P_NOWAIT',\n", + " 'P_NOWAITO',\n", + " 'P_PGID',\n", + " 'P_PID',\n", + " 'P_WAIT',\n", + " 'RTLD_GLOBAL',\n", + " 'RTLD_LAZY',\n", + " 'RTLD_LOCAL',\n", + " 'RTLD_NODELETE',\n", + " 'RTLD_NOLOAD',\n", + " 'RTLD_NOW',\n", + " 'R_OK',\n", + " 'SCHED_FIFO',\n", + " 'SCHED_OTHER',\n", + " 'SCHED_RR',\n", + " 'SEEK_CUR',\n", + " 'SEEK_END',\n", + " 'SEEK_SET',\n", + " 'ST_NOSUID',\n", + " 'ST_RDONLY',\n", + " 'TMP_MAX',\n", + " 'WCONTINUED',\n", + " 'WCOREDUMP',\n", + " 'WEXITED',\n", + " 'WEXITSTATUS',\n", + " 'WIFCONTINUED',\n", + " 'WIFEXITED',\n", + " 'WIFSIGNALED',\n", + " 'WIFSTOPPED',\n", + " 'WNOHANG',\n", + " 'WNOWAIT',\n", + " 'WSTOPPED',\n", + " 'WSTOPSIG',\n", + " 'WTERMSIG',\n", + " 'WUNTRACED',\n", + " 'W_OK',\n", + " 'X_OK',\n", + " '_Environ',\n", + " '__all__',\n", + " '__builtins__',\n", + " '__cached__',\n", + " '__doc__',\n", + " '__file__',\n", + " '__loader__',\n", + " '__name__',\n", + " '__package__',\n", + " '__spec__',\n", + " '_execvpe',\n", + " '_exists',\n", + " '_exit',\n", + " '_fwalk',\n", + " '_get_exports_list',\n", + " '_putenv',\n", + " '_spawnvef',\n", + " '_unsetenv',\n", + " '_wrap_close',\n", + " 'abort',\n", + " 'access',\n", + " 'altsep',\n", + " 'chdir',\n", + " 'chflags',\n", + " 'chmod',\n", + " 'chown',\n", + " 'chroot',\n", + " 'close',\n", + " 'closerange',\n", + " 'confstr',\n", + " 'confstr_names',\n", + " 'cpu_count',\n", + " 'ctermid',\n", + " 'curdir',\n", + " 'defpath',\n", + " 'device_encoding',\n", + " 'devnull',\n", + " 'dup',\n", + " 'dup2',\n", + " 'environ',\n", + " 'environb',\n", + " 'errno',\n", + " 'error',\n", + " 'execl',\n", + " 'execle',\n", + " 'execlp',\n", + " 'execlpe',\n", + " 'execv',\n", + " 'execve',\n", + " 'execvp',\n", + " 'execvpe',\n", + " 'extsep',\n", + " 'fchdir',\n", + " 'fchmod',\n", + " 'fchown',\n", + " 'fdopen',\n", + " 'fork',\n", + " 'forkpty',\n", + " 'fpathconf',\n", + " 'fsdecode',\n", + " 'fsencode',\n", + " 'fstat',\n", + " 'fstatvfs',\n", + " 'fsync',\n", + " 'ftruncate',\n", + " 'fwalk',\n", + " 'get_blocking',\n", + " 'get_exec_path',\n", + " 'get_inheritable',\n", + " 'get_terminal_size',\n", + " 'getcwd',\n", + " 'getcwdb',\n", + " 'getegid',\n", + " 'getenv',\n", + " 'getenvb',\n", + " 'geteuid',\n", + " 'getgid',\n", + " 'getgrouplist',\n", + " 'getgroups',\n", + " 'getloadavg',\n", + " 'getlogin',\n", + " 'getpgid',\n", + " 'getpgrp',\n", + " 'getpid',\n", + " 'getppid',\n", + " 'getpriority',\n", + " 'getsid',\n", + " 'getuid',\n", + " 'initgroups',\n", + " 'isatty',\n", + " 'kill',\n", + " 'killpg',\n", + " 'lchflags',\n", + " 'lchmod',\n", + " 'lchown',\n", + " 'linesep',\n", + " 'link',\n", + " 'listdir',\n", + " 'lockf',\n", + " 'lseek',\n", + " 'lstat',\n", + " 'major',\n", + " 'makedev',\n", + " 'makedirs',\n", + " 'minor',\n", + " 'mkdir',\n", + " 'mkfifo',\n", + " 'mknod',\n", + " 'name',\n", + " 'nice',\n", + " 'open',\n", + " 'openpty',\n", + " 'pardir',\n", + " 'path',\n", + " 'pathconf',\n", + " 'pathconf_names',\n", + " 'pathsep',\n", + " 'pipe',\n", + " 'popen',\n", + " 'pread',\n", + " 'putenv',\n", + " 'pwrite',\n", + " 'read',\n", + " 'readlink',\n", + " 'readv',\n", + " 'remove',\n", + " 'removedirs',\n", + " 'rename',\n", + " 'renames',\n", + " 'replace',\n", + " 'rmdir',\n", + " 'scandir',\n", + " 'sched_get_priority_max',\n", + " 'sched_get_priority_min',\n", + " 'sched_yield',\n", + " 'sendfile',\n", + " 'sep',\n", + " 'set_blocking',\n", + " 'set_inheritable',\n", + " 'setegid',\n", + " 'seteuid',\n", + " 'setgid',\n", + " 'setgroups',\n", + " 'setpgid',\n", + " 'setpgrp',\n", + " 'setpriority',\n", + " 'setregid',\n", + " 'setreuid',\n", + " 'setsid',\n", + " 'setuid',\n", + " 'spawnl',\n", + " 'spawnle',\n", + " 'spawnlp',\n", + " 'spawnlpe',\n", + " 'spawnv',\n", + " 'spawnve',\n", + " 'spawnvp',\n", + " 'spawnvpe',\n", + " 'st',\n", + " 'stat',\n", + " 'stat_float_times',\n", + " 'stat_result',\n", + " 'statvfs',\n", + " 'statvfs_result',\n", + " 'strerror',\n", + " 'supports_bytes_environ',\n", + " 'supports_dir_fd',\n", + " 'supports_effective_ids',\n", + " 'supports_fd',\n", + " 'supports_follow_symlinks',\n", + " 'symlink',\n", + " 'sync',\n", + " 'sys',\n", + " 'sysconf',\n", + " 'sysconf_names',\n", + " 'system',\n", + " 'tcgetpgrp',\n", + " 'tcsetpgrp',\n", + " 'terminal_size',\n", + " 'times',\n", + " 'times_result',\n", + " 'truncate',\n", + " 'ttyname',\n", + " 'umask',\n", + " 'uname',\n", + " 'uname_result',\n", + " 'unlink',\n", + " 'unsetenv',\n", + " 'urandom',\n", + " 'utime',\n", + " 'wait',\n", + " 'wait3',\n", + " 'wait4',\n", + " 'waitpid',\n", + " 'walk',\n", + " 'write',\n", + " 'writev']" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(os)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lab: files\n", + "---------" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "http://uwpce-pythoncert.github.io/IntroPython2016a/session05.html#lab-files" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Session05.ipynb students.txt\r\n" + ] + } + ], + "source": [ + "!ls" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Bindhu, Krishna: \r\n", + "Bounds, Brennen: English\r\n", + "Gregor, Michael: English\r\n", + "Holmer, Deana: SQL, English\r\n", + "Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl\r\n", + "Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL\r\n", + "Rudolph, John: English, Python, Sass, R, Basic\r\n", + "Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman\r\n", + "Warren, Benjamin: English\r\n", + "Aleson, Brandon: English\r\n", + "Chang, Jaemin: English\r\n", + "Chinn, Kyle: English\r\n", + "Derdouri, Abderrazak: English\r\n", + "Fannin, Calvin: C#, SQL, R\r\n", + "Gaffney, Thomas: SQL, Python, R, VBA, English\r\n", + "Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby\r\n", + "Ganzalez, Luis: Basic, C++, Python, English, Spanish\r\n", + "Ho, Chi Kin: English\r\n", + "McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley\r\n", + "Myerscough, Damian: \r\n", + "Newton, Michael: Python, Perl, Matlab\r\n", + "Sarpangala, Kishan: \r\n", + "Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab\r\n", + "Zhao, Yuanrui: " + ] + } + ], + "source": [ + "!cat students.txt" + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " \n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " SQL, English\n", + "\n", + " English, Hindi, Python, shell, d2k, SQL, Perl\n", + "\n", + " English, Latin, HTML, CSS, Javascript, Ruby, SQL\n", + "\n", + " English, Python, Sass, R, Basic\n", + "\n", + " C, C++, Perl, VHDL, Verilog, Specman\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " C#, SQL, R\n", + "\n", + " SQL, Python, R, VBA, English\n", + "\n", + " Basic, Pascal, C, Perl, Ruby\n", + "\n", + " Basic, C++, Python, English, Spanish\n", + "\n", + " English\n", + "\n", + " C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley\n", + "\n", + " \n", + "\n", + " Python, Perl, Matlab\n", + "\n", + " \n", + "\n", + " Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab\n", + "\n", + " \n" + ] + } + ], + "source": [ + "with open('students.txt', 'r') as f:\n", + " for line in f:\n", + " student_languages = line.rsplit(':')[1]\n", + " print(student_languages)" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{' C', ' \\n', ' English', ' HTML', ' Javascript', ' Verilog', ' Bash', ' VHDL', ' Python', ' English\\n', ' Matlab\\n', ' Perl\\n', ' Spanish\\n', ' ', ' Ruby', ' Sass', ' Pascal', ' d2k', ' C++', ' Prolog', ' C#', ' Specman\\n', ' SQL\\n', ' Tcl', ' Assembley\\n', ' Basic', ' R\\n', ' Perl', ' Ada', ' Scheme', ' Latin', ' Hindi', ' Basic\\n', ' R', ' Lisp', ' shell', ' VBA', ' CSS', ' SQL', ' Ruby\\n', ' Objective-C'}\n" + ] + } + ], + "source": [ + "language_set = set()\n", + "with open('students.txt', 'r') as f:\n", + " for line in f:\n", + " student_languages = line.rsplit(':')[1]\n", + " language_list = student_languages.split(',')\n", + " for language in language_list:\n", + " language_set.add(language)\n", + "print(language_set)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Check out Mike's work on this lab\n", + "---------------------------------" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "https://github.com/UWPCE-PythonCert/IntroPython2016a/tree/master/students/MikeSchincariol" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Session06.ipynb b/notebooks/Session06.ipynb new file mode 100644 index 0000000..94e4a4b --- /dev/null +++ b/notebooks/Session06.ipynb @@ -0,0 +1,654 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Exceptions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Set up and catch an IO Error" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " f = open('missing.txt')\n", + " process(f) # never called if file missing\n", + "except:\n", + " print(\"couldn't open missing.txt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Cleaner to move the processing elsewhere so that you better know the error you're trapping." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " f = open('missing.txt')\n", + "except:\n", + " print(\"couldn't open missing.txt\")\n", + "else:\n", + " process(f)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### We covered context managers last week" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " with open('missing.txt') as f:\n", + " process(f)\n", + "except:\n", + " print(\"couldn't open missing.txt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Advanced Argument Passing" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Be careful to actually call() a method() when() you() intend() to()." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "donor_name = 'Exit'" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "bye\n" + ] + } + ], + "source": [ + "if donor_name.lower() == 'exit':\n", + " print(\"bye\")" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "builtin_function_or_method" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(donor_name.lower)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(donor_name.lower())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### kwargs (key word arguments)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def myfunc(a=0, b=1, c=2):\n", + " print(a, b, c)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0 1 2\n" + ] + } + ], + "source": [ + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 1 22\n" + ] + } + ], + "source": [ + "myfunc(5, c=22)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0 3232 456\n" + ] + } + ], + "source": [ + "myfunc(c=456, b=3232)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Positional and keyword args mixed, note that the positionals come first, which makes perfect sense and leads to some handy properties" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def my_positional_and_kwargs_func(x, y, z=\"Hi I'm z\", a=\"Hi I'm a\"):\n", + " print(a, x, y, z, end=\" \")" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_positional_and_kwargs_func" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Python can be helpful and explicit when you don't call a funciton correctly" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "my_positional_and_kwargs_func() missing 2 required positional arguments: 'x' and 'y'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_positional_and_kwargs_func\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: my_positional_and_kwargs_func() missing 2 required positional arguments: 'x' and 'y'" + ] + } + ], + "source": [ + "my_positional_and_kwargs_func()" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hi I'm a Hi I'm x Hi I'm y No, I'm asdfasdf " + ] + } + ], + "source": [ + "my_positional_and_kwargs_func(\"Hi I'm x\", \"Hi I'm y\", z=\"No, I'm asdfasdf\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Now that you know that kwargs are represented by dictionaries, what else can you do?" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "mydict = {\"last_name\": 'Grimes', \"first_name\": 'Rick'}" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'my name is Rick Grimes'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"my name is {first_name} {last_name}\".format(**mydict)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Dict as switch" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "switch_dict = {\n", + " 0: 'zero',\n", + " 1: 'one',\n", + " 2: 'two',\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Note that the values in the dictionary are strings." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'zero'" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_dict.get(0)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'two'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_dict.get(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Supplying a default" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'or nothing'" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_dict.get(234234, \"or nothing\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What would this be like if you used functions instead? Think of the possibilities." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def my_zero_func():\n", + " return \"I'm zero\"" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def my_one_func():\n", + " return \"I'm one\"" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "switch_func_dict = {\n", + " 0: my_zero_func,\n", + " 1: my_one_func,\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"I'm zero\"" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_func_dict.get(0)()" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"I'm one\"" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_func_dict.get(1)()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### If you try something like this, don't forget to make the call()! Otherwise...." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_func_dict.get(1) # Missing the final ()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Session07.ipynb b/notebooks/Session07.ipynb new file mode 100644 index 0000000..5db9c2f --- /dev/null +++ b/notebooks/Session07.ipynb @@ -0,0 +1,300 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 111, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Point(object):\n", + " \"\"\" All instances of a class get the same class attributes. \"\"\"\n", + " size = 4\n", + " color = 'red'\n", + " \n", + " def __init__(self, x, y):\n", + " \"\"\" These are instance attributes, unique to each instance. \"\"\"\n", + " self.origin = 0\n", + " self.x = x\n", + " self.y = y\n", + " self.z = x * y -2\n", + " \n", + " def get_color(self):\n", + " \"\"\" Compare to print_color() \"\"\"\n", + " return self.color\n", + " \n", + " def print_color():\n", + " \"\"\" Compare to get_color() \"\"\"\n", + " return self.color\n", + " \n", + " def gimme_two_values(bob, a, b):\n", + " \"\"\"\n", + " Is 'self' a keyword? No, but it's a strong convention.\n", + " Most programmers would say using 'bob' in this context simply looks wrong.\n", + " \"\"\"\n", + " bob.x = a\n", + " bob.y = b" + ] + }, + { + "cell_type": "code", + "execution_count": 102, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_point = Point(2, 3)" + ] + }, + { + "cell_type": "code", + "execution_count": 103, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_other_point = Point(4, 5)" + ] + }, + { + "cell_type": "code", + "execution_count": 104, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_point.gimme_two_values(54, 765)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "The interpreter is doing something close to this:\n", + "\n", + " Point.gimme_two_values(my_point, 54, 765)\n", + "\n", + "...and the first argument is silently or implicitly passed in, and by convention is referred to as self." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "### Both my_point and my_other_point have access to the class attributes:" + ] + }, + { + "cell_type": "code", + "execution_count": 105, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 105, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.get_color()" + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 106, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_other_point.get_color()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Both have their own instance attributes:" + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "54" + ] + }, + "execution_count": 107, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.x" + ] + }, + { + "cell_type": "code", + "execution_count": 108, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 108, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_other_point.x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Note that get_color() works:" + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 109, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.get_color()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "### Whereas my_point.print_color() is broken:" + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "print_color() takes 0 positional arguments but 1 was given", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_point\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mprint_color\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: print_color() takes 0 positional arguments but 1 was given" + ] + } + ], + "source": [ + "my_point.print_color()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "#### ...and this is should help explian how the first argument to a method (self) works." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Session08.ipynb b/notebooks/Session08.ipynb new file mode 100644 index 0000000..f1f05ad --- /dev/null +++ b/notebooks/Session08.ipynb @@ -0,0 +1,732 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Basic, single inheritance" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class A:\n", + " def hello(self):\n", + " print(\"Hi\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class B(A):\n", + " def hello(self):\n", + " # super().hello()\n", + " print(\"there\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b = B()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "there\n" + ] + } + ], + "source": [ + "b.hello()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### What's my MRO?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Good insights to be got for calling help() on a class or instance:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on class B in module __main__:\n", + "\n", + "class B(A)\n", + " | Method resolution order:\n", + " | B\n", + " | A\n", + " | builtins.object\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | hello(self)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors inherited from A:\n", + " | \n", + " | __dict__\n", + " | dictionary for instance variables (if defined)\n", + " | \n", + " | __weakref__\n", + " | list of weak references to the object (if defined)\n", + "\n" + ] + } + ], + "source": [ + "help(B)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Animal Kingdom" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Animal(object):\n", + "\n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Mammal(Animal):\n", + " gestation_in_a_womb = True\n", + " warm_blood = True\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Reptile(Animal):\n", + " gestation_in_a_womb = False\n", + " warm_blood = False\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_mammal = Mammal()" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_mammal.gestation_in_a_womb" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_reptile = Reptile()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_reptile.gestation_in_a_womb" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Bird(Reptile):\n", + " warm_blood = True\n", + "\n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Snake(Reptile):\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Dog(Mammal):\n", + "\n", + " def __init__(self, chases_cats=True):\n", + " self.chases_cats = chases_cats\n", + " pass\n", + " \n", + " def make_me_cold_blooded(self):\n", + " self.warm_blood = False" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Cat(Mammal):\n", + " \n", + " def __init__(self, hates_dogs=True):\n", + " self.hates_dogs = hates_dogs\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_dog = Dog(chases_cats=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dog.chases_cats" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_dog.make_me_cold_blooded()" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dog.warm_blood" + ] + }, + { + "cell_type": "code", + "execution_count": 104, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_cat = Cat()" + ] + }, + { + "cell_type": "code", + "execution_count": 105, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 105, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_cat.hates_dogs" + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_dog.warm_blood = False" + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 107, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dog.warm_blood" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def main():\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "if __name__ == '__main__':\n", + " main()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# We got to about this point in class. I'm going to play around a little more in this space with in the hope of providing a few more insights." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's start at the top of the heirarchy. What else can we say about animals in general, or perhaps about any specific animal in particular?" + ] + }, + { + "cell_type": "code", + "execution_count": 113, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Animal(object):\n", + "\n", + " def __init__(self, age=0, location=0, weight=0):\n", + " self.age = age\n", + " self.location = location\n", + " self.weight = weight\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Or perhaps better if we start to handle arguments more gracefully..." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Animal(object):\n", + "\n", + " def __init__(self, **kwargs):\n", + " \n", + " if 'age' in kwargs:\n", + " self.age = kwargs['age']\n", + " else:\n", + " self.age = 0\n", + " \n", + " if 'location' in kwargs:\n", + " self.location = kwargs['location']\n", + " else:\n", + " self.location = 0\n", + "\n", + " if 'weight' in kwargs:\n", + " self.weight = kwargs['weight']\n", + " else:\n", + " self.weight = 0\n", + " \n", + " super().__init__()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##### Let's clean up Mammal while we're at it..." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Mammal(Animal):\n", + " gestation_in_a_womb = True\n", + " warm_blood = True\n", + " \n", + " def __init__(self, **kwargs):\n", + " super().__init__(**kwargs)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### How can we make Dog() more interesting? Let's check inputs against a collection of known breeds..." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Dog(Mammal):\n", + " breeds = ('Chow', 'Lab', 'Poodle', 'Samiod')\n", + " \n", + " def __init__(self, **kwargs):\n", + "\n", + " if 'breed' in kwargs and kwargs['breed'] in self.breeds:\n", + " self.breed = kwargs['breed']\n", + " else: self.breed = 'unknown'\n", + "\n", + " if 'chases_cats' in kwargs:\n", + " self.chases_cats = kwargs['chases_cats']\n", + " else:\n", + " self.chases_cats = True\n", + " \n", + " super().__init__(**kwargs)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_dog = Dog(age=14, breed='Chow')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Note that we didn't handle .age until all the way back up in the parent Animal() class, passing it up through Mammal(), yet our dog still has a .age" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "14" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dog.age" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'age': 14, 'breed': 'Chow', 'chases_cats': True, 'location': 0, 'weight': 0}" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dog.__dict__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### We started talking about multiple inheritance. Let's touch on that..." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Reptile(Animal):\n", + " gestation_in_a_womb = False\n", + " warm_blood = False\n", + "\n", + " def __init__(self, **kwargs):\n", + " super().__init__(**kwargs)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Platypus(Mammal, Reptile):\n", + " gestation_in_a_womb = False\n", + " warm_blood = True\n", + " \n", + " def __init__(self, **kwargs):\n", + " super().__init__(**kwargs)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_platypus = Platypus(weight=30)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##### All for now. Take over for me. :)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Session09.ipynb b/notebooks/Session09.ipynb new file mode 100644 index 0000000..23660ac --- /dev/null +++ b/notebooks/Session09.ipynb @@ -0,0 +1,839 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Composition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Lifted mostly from Learn Python the Hard Way" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "http://learnpythonthehardway.org/book/ex44.html" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Other(object):\n", + " \n", + " def __init__(self):\n", + " print(\"Other __init__\")\n", + " \n", + " def override(self):\n", + " print(\"Other override()\")\n", + " \n", + " def implicit(self):\n", + " print(\"Other implicit()\")\n", + " \n", + " def altered(self):\n", + " print(\"Other altered()\")" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyComposedClass(object):\n", + " \"\"\" I use Other, but I do not inherit from it \"\"\"\n", + " \n", + " def __init__(self):\n", + " self.other = Other()\n", + " \n", + " def implicit(self):\n", + " '''\n", + " I do nothing myself, I delegate\n", + " '''\n", + " self.other.implicit()\n", + " \n", + " def override(self):\n", + " \"\"\"\n", + " I simply choose to ignore self.other.override()\n", + " and instead do the work myself\n", + " \"\"\"\n", + " print(\"MyComposedClass override()\")\n", + " \n", + " def altered(self):\n", + " \"\"\"\n", + " I do some work myself, yet also delegate\n", + " \"\"\"\n", + " print(\"MyComposedClass, BEFORE OTHER altered()\")\n", + " self.other.altered()\n", + " print(\"MyComposedClass, AFTER OTHER altered()\")" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Other __init__\n" + ] + } + ], + "source": [ + "my_composed_class = MyComposedClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Other implicit()\n" + ] + } + ], + "source": [ + "my_composed_class.implicit()" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "MyComposedClass override()\n" + ] + } + ], + "source": [ + "my_composed_class.override()" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "MyComposedClass, BEFORE OTHER altered()\n", + "Other altered()\n", + "MyComposedClass, AFTER OTHER altered()\n" + ] + } + ], + "source": [ + "my_composed_class.altered()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Properties" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyClass(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5\n", + " \n", + " def get_x(self):\n", + " return self._x\n", + " \n", + " def set_x(self, x):\n", + " if 2 < x < 9:\n", + " self._x = x\n", + " else:\n", + " raise ValueError(\"Whoa, what are you thinking?\")" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_class = MyClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class.get_x()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_class.set_x(4)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "ValueError", + "evalue": "Whoa, what are you thinking?", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_x\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m11\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mset_x\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_x\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 13\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Whoa, what are you thinking?\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mValueError\u001b[0m: Whoa, what are you thinking?" + ] + } + ], + "source": [ + "my_class.set_x(11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Okay, basic stuff here... what's the big deal? What if you have a few instances of MyClass floating around and you want to do some work with their attributes...." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_other_class = MyClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "ValueError", + "evalue": "Whoa, what are you thinking?", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_x\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmy_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_x\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mmy_other_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_x\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mset_x\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_x\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 13\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Whoa, what are you thinking?\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mValueError\u001b[0m: Whoa, what are you thinking?" + ] + } + ], + "source": [ + "my_class.set_x(my_class.get_x() + my_other_class.get_x())" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class.get_x()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### That worked, but it sure was ugly. Note that the throwing of the exception was deliberate and planned! I set x to a value outside its perscribed range. The uglyness is in having to access an attribute via a method call. I'd rather do something like this..." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_class._x = my_class._x + my_other_class._x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### That was easy, the syntax clear, but I now have a value for x in my_class that is out of range: x should never be equal to or greater than 9! Oh no! The internal consistancy of my object has been violated! Mayhem ensues...." + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 64, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class._x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Enter properties!" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on class property in module builtins:\n", + "\n", + "class property(object)\n", + " | property(fget=None, fset=None, fdel=None, doc=None) -> property attribute\n", + " | \n", + " | fget is a function to be used for getting an attribute value, and likewise\n", + " | fset is a function for setting, and fdel a function for del'ing, an\n", + " | attribute. Typical use is to define a managed attribute x:\n", + " | \n", + " | class C(object):\n", + " | def getx(self): return self._x\n", + " | def setx(self, value): self._x = value\n", + " | def delx(self): del self._x\n", + " | x = property(getx, setx, delx, \"I'm the 'x' property.\")\n", + " | \n", + " | Decorators make defining new properties or modifying existing ones easy:\n", + " | \n", + " | class C(object):\n", + " | @property\n", + " | def x(self):\n", + " | \"I am the 'x' property.\"\n", + " | return self._x\n", + " | @x.setter\n", + " | def x(self, value):\n", + " | self._x = value\n", + " | @x.deleter\n", + " | def x(self):\n", + " | del self._x\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | __delete__(self, instance, /)\n", + " | Delete an attribute of instance.\n", + " | \n", + " | __get__(self, instance, owner, /)\n", + " | Return an attribute of instance, which is of type owner.\n", + " | \n", + " | __getattribute__(self, name, /)\n", + " | Return getattr(self, name).\n", + " | \n", + " | __init__(self, /, *args, **kwargs)\n", + " | Initialize self. See help(type(self)) for accurate signature.\n", + " | \n", + " | __new__(*args, **kwargs) from builtins.type\n", + " | Create and return a new object. See help(type) for accurate signature.\n", + " | \n", + " | __set__(self, instance, value, /)\n", + " | Set an attribute of instance to value.\n", + " | \n", + " | deleter(...)\n", + " | Descriptor to change the deleter on a property.\n", + " | \n", + " | getter(...)\n", + " | Descriptor to change the getter on a property.\n", + " | \n", + " | setter(...)\n", + " | Descriptor to change the setter on a property.\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors defined here:\n", + " | \n", + " | __isabstractmethod__\n", + " | \n", + " | fdel\n", + " | \n", + " | fget\n", + " | \n", + " | fset\n", + "\n" + ] + } + ], + "source": [ + "help(property)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyNewClass(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5\n", + " self._y = 33\n", + " \n", + " def get_x(self):\n", + " return self._x\n", + " \n", + " def set_x(self, x):\n", + " if 2 < x < 9:\n", + " self._x = x\n", + " else:\n", + " raise ValueError(\"Whoa, what are you thinking?\")\n", + " \n", + " x = property(get_x, set_x)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_new_class = MyNewClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_new_class.x" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_new_class.x = 4" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_new_class.x" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "ValueError", + "evalue": "Whoa, what are you thinking?", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_new_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m99\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mset_x\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_x\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 13\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Whoa, what are you thinking?\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 14\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mproperty\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mget_x\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mset_x\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mValueError\u001b[0m: Whoa, what are you thinking?" + ] + } + ], + "source": [ + "my_new_class.x = 99" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "'MyClass' object has no attribute 'x'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_new_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmy_new_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mmy_other_class\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m: 'MyClass' object has no attribute 'x'" + ] + } + ], + "source": [ + "my_new_class.x = my_new_class.x + my_other_class.x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Let's refactor the class to use decorators rather than a call to the property() built-in" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class MyDecoratedClass(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5\n", + " self._y = 33\n", + " \n", + "# def get_x(self):\n", + "# return self._x\n", + "\n", + " @property\n", + " def x(self):\n", + " return self._x\n", + " \n", + "# def set_x(self, x):\n", + "# if 2 < x < 9:\n", + "# self._x = x\n", + "# else:\n", + "# raise ValueError(\"Whoa, what are you thinking?\")\n", + "\n", + " @x.setter\n", + " def x(self, x):\n", + " if 2 < x < 9:\n", + " self._x = x\n", + " else:\n", + " raise ValueError(\"Whoa, what are you thinking?\")\n", + "\n", + " def make_me_a_sandwhich(self):\n", + " pass\n", + "\n", + " # x = property(get_x, set_x)" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_decorated_class = MyDecoratedClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_decorated_class.x = my_decorated_class.x + 1" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_decorated_class.x" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_decorated_class.x += 1" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_decorated_class.x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### To create a read-only attribute... don't define the setter" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyReadOnlyClass(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5\n", + " \n", + " @property\n", + " def x(self):\n", + " return self._x" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_read_only = MyReadOnlyClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 55, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_read_only.x" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "can't set attribute", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_read_only\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m6\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m: can't set attribute" + ] + } + ], + "source": [ + "my_read_only.x = 6" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/Session10.ipynb b/notebooks/Session10.ipynb new file mode 100644 index 0000000..25775f6 --- /dev/null +++ b/notebooks/Session10.ipynb @@ -0,0 +1,1536 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functional Programming" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## map()" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "l = [2, 5, 7, 12, 6, 4]" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def fun(x):\n", + " return x * 2 + 10" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "m = map(fun, l)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "m" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "map" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(m)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[14, 20, 24, 34, 22, 18]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(m)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Or, use a comprehension to accomplish the same thing in a single line!" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_new_list = [x * 2 + 10 for x in l]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[14, 20, 24, 34, 22, 18]" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_new_list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## filter()" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def fil(x):\n", + " return x%2 == 0" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "f = filter(fil, l)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 12, 6, 4]" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(f)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Or, use a comprehension to accomplish the same thing in a single line!" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 12, 6, 4]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x for x in l if x%2 == 0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### A comprehension implimenting both map and filter..." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[4, 14, 8, 6]" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[y+2 for y in l if y%2 == 0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comprehensions as looping constructs" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "4\n" + ] + } + ], + "source": [ + "for x in range(3):\n", + " print(x ** 2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### The simple for loop can above can be expressed as the comprehension below" + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4]" + ] + }, + "execution_count": 107, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x ** 2 for x in range(3)]" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "6\n", + "10\n" + ] + } + ], + "source": [ + "for x in range(6):\n", + " if x%2 !=0:\n", + " print(x*2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### The for loop with an 'if' above can be expressed as a comprehension with the filter clause below" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 6, 10]" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x*2 for x in range(6) if x%2 !=0]" + ] + }, + { + "cell_type": "code", + "execution_count": 115, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "0\n", + "1\n", + "2\n", + "0\n", + "1\n", + "2\n", + "0\n", + "1\n", + "2\n", + "0\n", + "1\n", + "2\n", + "0\n", + "1\n", + "2\n" + ] + } + ], + "source": [ + "for x in range(6): # six iterations...\n", + " for y in range(3): # of 0, 1, 2\n", + " print(y)" + ] + }, + { + "cell_type": "code", + "execution_count": 125, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]" + ] + }, + "execution_count": 125, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[[y for y in range(3)] for x in range(6)] # six lists of [0, 1, 2]" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]" + ] + }, + "execution_count": 123, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sum([[y for y in range(3)] for x in range(6)], []) # Flatten nested lists with sum(list,[])" + ] + }, + { + "cell_type": "code", + "execution_count": 134, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2]" + ] + }, + "execution_count": 134, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x for x in range(3) if x in [1, 2, 3]]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Getting creative" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['ArithmeticError',\n", + " 'AssertionError',\n", + " 'AttributeError',\n", + " 'BlockingIOError',\n", + " 'BrokenPipeError',\n", + " 'BufferError',\n", + " 'ChildProcessError',\n", + " 'ConnectionAbortedError',\n", + " 'ConnectionError',\n", + " 'ConnectionRefusedError',\n", + " 'ConnectionResetError',\n", + " 'EOFError',\n", + " 'EnvironmentError',\n", + " 'FileExistsError',\n", + " 'FileNotFoundError',\n", + " 'FloatingPointError',\n", + " 'IOError',\n", + " 'ImportError',\n", + " 'IndentationError',\n", + " 'IndexError',\n", + " 'InterruptedError',\n", + " 'IsADirectoryError',\n", + " 'KeyError',\n", + " 'LookupError',\n", + " 'MemoryError',\n", + " 'NameError',\n", + " 'NotADirectoryError',\n", + " 'NotImplementedError',\n", + " 'OSError',\n", + " 'OverflowError',\n", + " 'PermissionError',\n", + " 'ProcessLookupError',\n", + " 'RecursionError',\n", + " 'ReferenceError',\n", + " 'RuntimeError',\n", + " 'SyntaxError',\n", + " 'SystemError',\n", + " 'TabError',\n", + " 'TimeoutError',\n", + " 'TypeError',\n", + " 'UnboundLocalError',\n", + " 'UnicodeDecodeError',\n", + " 'UnicodeEncodeError',\n", + " 'UnicodeError',\n", + " 'UnicodeTranslateError',\n", + " 'ValueError',\n", + " 'ZeroDivisionError']" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[name for name in dir(__builtin__) if \"Error\" in name]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Pradeep's variation...." + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['ArithmeticError',\n", + " 'AssertionError',\n", + " 'AttributeError',\n", + " 'BaseException',\n", + " 'BlockingIOError',\n", + " 'BrokenPipeError',\n", + " 'BufferError',\n", + " 'BytesWarning',\n", + " 'ChildProcessError',\n", + " 'ConnectionAbortedError',\n", + " 'ConnectionError',\n", + " 'ConnectionRefusedError',\n", + " 'ConnectionResetError',\n", + " 'DeprecationWarning',\n", + " 'EOFError',\n", + " 'Ellipsis',\n", + " 'EnvironmentError',\n", + " 'Exception',\n", + " 'False',\n", + " 'FileExistsError',\n", + " 'FileNotFoundError',\n", + " 'FloatingPointError',\n", + " 'FutureWarning',\n", + " 'GeneratorExit',\n", + " 'IOError',\n", + " 'ImportError',\n", + " 'ImportWarning',\n", + " 'IndentationError',\n", + " 'IndexError',\n", + " 'InterruptedError',\n", + " 'IsADirectoryError',\n", + " 'KeyError',\n", + " 'KeyboardInterrupt',\n", + " 'LookupError',\n", + " 'MemoryError',\n", + " 'NameError',\n", + " 'None',\n", + " 'NotADirectoryError',\n", + " 'NotImplemented',\n", + " 'NotImplementedError',\n", + " 'OSError',\n", + " 'OverflowError',\n", + " 'PendingDeprecationWarning',\n", + " 'PermissionError',\n", + " 'ProcessLookupError',\n", + " 'RecursionError',\n", + " 'ReferenceError',\n", + " 'ResourceWarning',\n", + " 'RuntimeError',\n", + " 'RuntimeWarning',\n", + " 'StopAsyncIteration',\n", + " 'StopIteration',\n", + " 'SyntaxError',\n", + " 'SyntaxWarning',\n", + " 'SystemError',\n", + " 'SystemExit',\n", + " 'TabError',\n", + " 'TimeoutError',\n", + " 'True',\n", + " 'TypeError',\n", + " 'UnboundLocalError',\n", + " 'UnicodeDecodeError',\n", + " 'UnicodeEncodeError',\n", + " 'UnicodeError',\n", + " 'UnicodeTranslateError',\n", + " 'UnicodeWarning',\n", + " 'UserWarning',\n", + " 'ValueError',\n", + " 'Warning',\n", + " 'ZeroDivisionError',\n", + " '__IPYTHON__',\n", + " '__IPYTHON__active',\n", + " '__build_class__',\n", + " '__debug__',\n", + " '__doc__',\n", + " '__import__',\n", + " '__loader__',\n", + " '__name__',\n", + " '__package__',\n", + " '__spec__',\n", + " 'abs',\n", + " 'all',\n", + " 'any',\n", + " 'ascii',\n", + " 'bin',\n", + " 'bool',\n", + " 'bytearray',\n", + " 'bytes',\n", + " 'callable',\n", + " 'chr',\n", + " 'classmethod',\n", + " 'compile',\n", + " 'complex',\n", + " 'copyright',\n", + " 'credits',\n", + " 'delattr',\n", + " 'dict',\n", + " 'dir',\n", + " 'divmod',\n", + " 'dreload',\n", + " 'enumerate',\n", + " 'eval',\n", + " 'exec',\n", + " 'filter',\n", + " 'float',\n", + " 'format',\n", + " 'frozenset',\n", + " 'get_ipython',\n", + " 'getattr',\n", + " 'globals',\n", + " 'hasattr',\n", + " 'hash',\n", + " 'help',\n", + " 'hex',\n", + " 'id',\n", + " 'input',\n", + " 'int',\n", + " 'isinstance',\n", + " 'issubclass',\n", + " 'iter',\n", + " 'len',\n", + " 'license',\n", + " 'list',\n", + " 'locals',\n", + " 'map',\n", + " 'max',\n", + " 'memoryview',\n", + " 'min',\n", + " 'next',\n", + " 'object',\n", + " 'oct',\n", + " 'open',\n", + " 'ord',\n", + " 'pow',\n", + " 'print',\n", + " 'property',\n", + " 'range',\n", + " 'repr',\n", + " 'reversed',\n", + " 'round',\n", + " 'set',\n", + " 'setattr',\n", + " 'slice',\n", + " 'sorted',\n", + " 'staticmethod',\n", + " 'str',\n", + " 'sum',\n", + " 'super',\n", + " 'tuple',\n", + " 'type',\n", + " 'vars',\n", + " 'zip']" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[name if x is not None else '' for name in dir(__builtin__)]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Nested loops" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5\n", + "6\n", + "6\n", + "7\n", + "7\n", + "8\n" + ] + } + ], + "source": [ + "for x in range(3):\n", + " for y in range(5, 7):\n", + " print(x+y)" + ] + }, + { + "cell_type": "code", + "execution_count": 139, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 6, 7, 6, 7, 8]" + ] + }, + "execution_count": 139, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x+y for y in range(5, 7) for x in range(3)] # almost, but not quite" + ] + }, + { + "cell_type": "code", + "execution_count": 140, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 6, 6, 7, 7, 8]" + ] + }, + "execution_count": 140, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x+y for x in range(3) for y in range(5, 7)] # Got it!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# reduce()" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from functools import reduce" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def my_sum(x, y):\n", + " return x+y" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "r = reduce(my_sum, l)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "36" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lambda" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### A standard function..." + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def f(x, y):\n", + " return x+y" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "f(3,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "function" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(f)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Same thing as a lambda" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "l = lambda x, y: x+y" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "function" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(l)" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l(3,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_func_list = [lambda x, y: x+y, lambda x, y: x*y] # a list of functions" + ] + }, + { + "cell_type": "code", + "execution_count": 142, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 142, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_func_list[0](3,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 143, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "12" + ] + }, + "execution_count": 143, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_func_list[1](3,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 144, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_func_dict = {'add': lambda x, y, z: x+y+z, 'mult':lambda x, y: x*y} # a dict of functions" + ] + }, + { + "cell_type": "code", + "execution_count": 145, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "12" + ] + }, + "execution_count": 145, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_func_dict['add'](3,4,5) # Now I can call these by something meaningful" + ] + }, + { + "cell_type": "code", + "execution_count": 146, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "12" + ] + }, + "execution_count": 146, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_func_dict['mult'](3,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_list = [1, 2, 3, 4, 5]" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_lambda = lambda my_list: print(my_list)" + ] + }, + { + "cell_type": "code", + "execution_count": 149, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], + "source": [ + "my_lambda(my_list)" + ] + }, + { + "cell_type": "code", + "execution_count": 150, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "12" + ] + }, + "execution_count": 150, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_func_dict['add'](z=5,y=4,x=3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Closures" + ] + }, + { + "cell_type": "code", + "execution_count": 151, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def make_multiplier_of(n):\n", + " def multiplier(x):\n", + " return x * n\n", + " return multiplier" + ] + }, + { + "cell_type": "code", + "execution_count": 152, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "times3 = make_multiplier_of(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 153, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "times5 = make_multiplier_of(5)" + ] + }, + { + "cell_type": "code", + "execution_count": 154, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "24" + ] + }, + "execution_count": 154, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "times3(8)" + ] + }, + { + "cell_type": "code", + "execution_count": 155, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "50" + ] + }, + "execution_count": 155, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "times5(10)" + ] + }, + { + "cell_type": "code", + "execution_count": 156, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{}" + ] + }, + "execution_count": 156, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "times3.__dict__" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Circle" + ] + }, + { + "cell_type": "code", + "execution_count": 157, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from math import pi\n", + "\n", + "class Circle(object):\n", + " pi = 3.1415\n", + " \n", + " def __init__(self, **kwargs):\n", + " \n", + " if 'radius' not in kwargs and 'diameter' not in kwargs:\n", + " raise AttributeError (\"Please supply either radius or diameter\")\n", + " \n", + " if 'radius' in kwargs:\n", + " self.radius = kwargs['radius']\n", + " \n", + " if 'diameter' in kwargs:\n", + " self.radius = kwargs['diameter'] / 2\n", + " \n", + " @property\n", + " def radius(self):\n", + " return self._radius\n", + " \n", + " @radius.setter\n", + " def radius(self, radius):\n", + " self._radius = radius\n", + " \n", + " @property\n", + " def diameter(self):\n", + " return self._radius * 2\n", + " \n", + " @diameter.setter\n", + " def diameter(self, diameter):\n", + " self._radius = diameter / 2\n", + " \n", + " @property\n", + " def area(self):\n", + " return pi * self._radius**2" + ] + }, + { + "cell_type": "code", + "execution_count": 158, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "c = Circle(radius=3)" + ] + }, + { + "cell_type": "code", + "execution_count": 159, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 159, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.diameter" + ] + }, + { + "cell_type": "code", + "execution_count": 160, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "28.274333882308138" + ] + }, + "execution_count": 160, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.area" + ] + }, + { + "cell_type": "code", + "execution_count": 161, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Circle2(object):\n", + " \n", + " def __init__(self, radius):\n", + " print(\"In Circle.__init__()\")\n", + " self.radius = radius\n", + " \n", + " @classmethod\n", + " def from_diameter(cls, diameter):\n", + " return cls(diameter / 2.0)" + ] + }, + { + "cell_type": "code", + "execution_count": 162, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "In Circle.__init__()\n" + ] + } + ], + "source": [ + "c2 = Circle2.from_diameter(9)" + ] + }, + { + "cell_type": "code", + "execution_count": 163, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4.5" + ] + }, + "execution_count": 163, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c2.radius" + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'from_diameter']" + ] + }, + "execution_count": 164, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(Circle2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/SuperConsideredSuper/README.md b/notebooks/SuperConsideredSuper/README.md new file mode 100644 index 0000000..93a8d6d --- /dev/null +++ b/notebooks/SuperConsideredSuper/README.md @@ -0,0 +1,9 @@ +# Super() Considered Super! + +Raymond Hettinger's talk: + +https://youtu.be/EiOglTERPEo + +Sample/demo code within this directory. + +Enjoy. diff --git a/notebooks/SuperConsideredSuper/organic_pizza.py b/notebooks/SuperConsideredSuper/organic_pizza.py new file mode 100644 index 0000000..bd05f9d --- /dev/null +++ b/notebooks/SuperConsideredSuper/organic_pizza.py @@ -0,0 +1,17 @@ +# organic_pizza.py + +from pizza import DoughFactory, Pizza + + +class OrganicDoughFactory(DoughFactory): + def get_dough(self): + return "pure untreated wheat dough" + + +class OrganicPizza(Pizza, OrganicDoughFactory): + pass + + +if __name__ == '__main__': + my_pie = OrganicPizza() + my_pie.order_pizza('pepperoni', 'shrooms') diff --git a/notebooks/SuperConsideredSuper/pizza.py b/notebooks/SuperConsideredSuper/pizza.py new file mode 100644 index 0000000..46561ac --- /dev/null +++ b/notebooks/SuperConsideredSuper/pizza.py @@ -0,0 +1,28 @@ +# pizza.py + + +class DoughFactory(object): + + def get_dough(self): + return "insecticide treated wheat dough" + + +class Pizza(DoughFactory): + + def order_pizza(self, *toppings): + print("Getting dough") + + # Uh oh, this is hard coded! What happens if we change the parent class? + # dough = DoughFactory.get_dough(self) + # dough = self.get_dough() + dough = super().get_dough() + + print("Making pie with {}".format(dough)) + + for topping in toppings: + print("Adding {}".format(topping)) + + +if __name__ == '__main__': + my_pie = Pizza() + my_pie.order_pizza('pepperoni', 'shrooms') diff --git a/notebooks/SuperConsideredSuper/robot.py b/notebooks/SuperConsideredSuper/robot.py new file mode 100644 index 0000000..b12a539 --- /dev/null +++ b/notebooks/SuperConsideredSuper/robot.py @@ -0,0 +1,30 @@ +# robot.py + +class Robot(object): + + def fetch(self, tool): + print("Physical Movement: Fetching") + + def move_forward(self, tool): + print("Physical Movement: Moving forward") + + def move_backward(self, tool): + print("Physical Movement: Moving backward") + + def replace(self, tool): + print("Physical Movement: Replacing") + + +class CleaningRobot(Robot): + + def clean(self, tool, times=3): + super().fetch(tool) + for _ in range(times): + super().move_forward(tool) + super().move_backward(tool) + super().replace(tool) + + +if __name__ == '__main__': + t = CleaningRobot() + t.clean('broom') diff --git a/notebooks/SuperConsideredSuper/test_robot.py b/notebooks/SuperConsideredSuper/test_robot.py new file mode 100644 index 0000000..d45b8e3 --- /dev/null +++ b/notebooks/SuperConsideredSuper/test_robot.py @@ -0,0 +1,41 @@ +# test_robot.py + +from robot import Robot, CleaningRobot + + +class MockBot(Robot): + + def __init__(self): + self.tasks = [] + + def fetch(self, tool): + self.tasks.append("fetching {}".format(tool)) + + def move_forward(self, tool): + self.tasks.append("forward {}".format(tool)) + + def move_backward(self, tool): + self.tasks.append("backward {}".format(tool)) + + def replace(self, tool): + self.tasks.append("replace {}".format(tool)) + + +class MockedCleaningRobot(CleaningRobot, MockBot): + pass + + +def test_clean(): + t = MockedCleaningRobot() + t.clean('mop') + expected = ( + ['fetching mop'] + + ['forward mop', 'backward mop'] * 3 + + ['replace mop'] + ) + assert t.tasks == expected + + +if __name__ == '__main__': + t = MockedCleaningRobot() + t.clean('broom') diff --git a/notebooks/Trap_Rule.ipynb b/notebooks/Trap_Rule.ipynb new file mode 100644 index 0000000..1d7412c --- /dev/null +++ b/notebooks/Trap_Rule.ipynb @@ -0,0 +1,587 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Background" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You have a function f(x) and want to calculate the area under the curve of f(x) from a to b. \n", + "\n", + "\n", + "\n", + "- Intervals of equal length \n", + "- h = (b - a) / n \n", + " - where b = end point \n", + " - a = start point \n", + " - n = number of intervals " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The goal " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Create a function that can integrate any function you pass to it: \n", + "\n", + "- Pass a function to this trapz function \n", + "- Pass a start point \n", + "- Pass an end point\n", + "- Return the area under the curve" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def line(x):\n", + " '''a very simple straight horizontal line at y = 5'''\n", + " return 5\n", + "\n", + "area = trapz(line, 0, 10)\n", + "\n", + "print (area)\n", + "\n", + "50" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def trapz(fun, a, b):\n", + " \"\"\"\n", + " Compute the area under the curve defined by\n", + " y = fun(x), for x between a and b\n", + " \n", + " :param fun: the function to evaluate\n", + " :type fun: a function that takes a single parameter\n", + "\n", + " :param a: the start point for the integration\n", + " :type a: a numeric value\n", + "\n", + " :param b: the end point for the integration\n", + " :type b: a numeric value\n", + " \"\"\" \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You will need to: \n", + " - create list of x values from a to b \n", + " - compute whatever the function is for each of those values \n", + " - add the results up \n", + " - multiply by half the difference between a and b divided by the number of steps " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a function to test\n", + "\n", + "Let's use the straight line function from the example. \n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# create a straight line\n", + "def line(x):\n", + " '''a very simple straight horizontal line at y = 5'''\n", + " return 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Create a list of x values from a to b" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def create_range(a,b,n):\n", + " '''\n", + " a = start point\n", + " b = end point\n", + " n = number of intervals to create\n", + " '''\n", + " # create list of x values from a to b \n", + " delta = float(b - a)/n\n", + " return [a + i * delta for i in range(n + 1)]\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1.0, 5.5, 10.0]\n" + ] + } + ], + "source": [ + "stuff = create_range(1,10,2)\n", + "print (stuff)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Compute the function for each of those values and sum" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def trapz(fun, a, b, n):\n", + " # create a range from a to b\n", + " my_vals = create_range(a,b,n)\n", + " # compute the function for each of those values and double\n", + " s = [fun(x) for x in my_vals[1:-1]] * 2\n", + " print (s)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[5, 5]\n" + ] + } + ], + "source": [ + "test_calc_fun = trapz(line, 1,10,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def trapz(fun, a, b, n):\n", + " # create a range from a to b\n", + " my_vals = create_range(a,b,n)\n", + " # compute the function for each of those values\n", + " s = sum([fun(x) for x in my_vals[1:-1]] * 2)\n", + " print (s)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n" + ] + } + ], + "source": [ + "test_sum = trapz(line, 1,10,2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Multiply by half the difference between a and b divided by the number of steps" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def trapz(fun, a, b, n):\n", + " # create a range from a to b\n", + " my_vals = create_range(a,b,n)\n", + " # compute the function for each of those values and double, then sum\n", + " s = sum([fun(x) for x in my_vals[1:-1]] * 2)\n", + " # calculate half the diff between a and b divided by n\n", + " diff = ((b - a) * .5)/n\n", + " print (diff)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2.25\n" + ] + } + ], + "source": [ + "test_diff = trapz(line, 1,10,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def trapz(fun, a, b, n):\n", + " # create a range from a to b\n", + " my_vals = create_range(a,b,n)\n", + " # compute the function for each of those values\n", + " s = sum([fun(x) for x in my_vals[1:-1]])\n", + " # calculate diff between f(a) and f(b) divided by n\n", + " diff = ((b - a) * .5)/n\n", + " # multiply s by diff\n", + " area = s * diff\n", + " return area" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "11.25\n" + ] + } + ], + "source": [ + "test_trapz = trapz(line, 1,10,2)\n", + "print (test_trapz)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Test with a simple function" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def add_one(x):\n", + " one_more = x + 1\n", + " return one_more" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n" + ] + } + ], + "source": [ + "print (add_one(2))" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "14.625\n" + ] + } + ], + "source": [ + "test2 = trapz(add_one, 1,10,2)\n", + "print (test2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Stage 2: Passing functions with more than one argument" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "So far, the functions we pass to trapz can only take on argument. Let's update it so that we can pass through a function with any number of arguments. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Goal = pass a variable number or arguments to a function\n", + "\n", + "- trapz(quadratic, 2, 20, A=1, B=3, C=2) \n", + "- trapz(quadratic, 2, 20, 1, 3, C=2) \n", + "- coef = {'A':1, 'B':3, 'C': 2} \n", + "- trapz(quadratic, 2, 20, **coef) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Quick review of *args and **kwargs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Example from http://markmiyMashita.com/blog/python-args-and-kwargs/Mm" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def func_with_two(one, two):\n", + " \"\"\"\n", + " Takes in two arguments because we explicitly\n", + " defined two formal parameters. \n", + " Any more or any less will cause anerror.\n", + " \"\"\"\n", + " \n", + "def func_with_start_args(*args):\n", + " \"\"\"\n", + " This function can take in any number of arguments, including zero!\n", + " \"\"\"\n", + " \n", + "def func_with_both(one, two, *args):\n", + " \"\"\"\n", + " This function requires at least two arguments. The *args at the end\n", + " says that it can take just two arguments or any number of arguments as long\n", + " as there are at least two.\n", + " \"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "#keyword argument = you name the variable as you pass it\n", + "def print_table(**kwargs):\n", + " for key, value in kwargs.items():\n", + " print(key, value)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "b 6\n", + "c 7\n", + "a 5\n" + ] + } + ], + "source": [ + "print_table(a = 5, b = 6, c = 7)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "How can you use *args and **kwargs to update the trapezoid function? " + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# student example\n", + "\n", + "def trapz(fun, a, b, num_steps, **kwargs):\n", + " \"\"\"\n", + " Compute the area under the curve defined by\n", + " y = fun(x), for x between a and b\n", + " :param fun: the function to evaluate\n", + " :type fun: a function that takes a single parameter\n", + " :param a: the start point for the integration\n", + " :type a: a numeric value\n", + " :param b: the end point for the integration\n", + " :type b: a numeric value\n", + " \"\"\"\n", + " STEP_SIZE = (b-a)/num_steps\n", + "\n", + " sum = 0\n", + " for i in range(0, num_steps):\n", + " left = a + (i * STEP_SIZE)\n", + " right = a + ((i+1) * STEP_SIZE)\n", + " sum += fun(left, **kwargs) + fun(right, **kwargs)\n", + "\n", + " sum = sum * STEP_SIZE / 2\n", + " return sum" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "58.5" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "trapz(add_one, 1,10,2)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/notebooks/students.txt b/notebooks/students.txt new file mode 120000 index 0000000..dfbe477 --- /dev/null +++ b/notebooks/students.txt @@ -0,0 +1 @@ +../Examples/students.txt \ No newline at end of file diff --git a/slides_sources/source/exercises/exceptions_lab.rst b/slides_sources/source/exercises/exceptions_lab.rst index 5ff5b16..a25a58c 100644 --- a/slides_sources/source/exercises/exceptions_lab.rst +++ b/slides_sources/source/exercises/exceptions_lab.rst @@ -14,12 +14,8 @@ Exceptions Lab Improving ``input`` -* The ``input()`` function can generate two exceptions: ``EOFError`` - or ``KeyboardInterrupt`` on end-of-file(EOF) or canceled input. +* The ``input()`` function can generate two exceptions: ``EOFError`` or ``KeyboardInterrupt`` on end-of-file(EOF) or canceled input. -* Create a wrapper function, perhaps ``safe_input()`` that returns ``None`` - rather rather than raising these exceptions, when the user enters ``^C`` for Keyboard Interrupt, or ``^D`` (``^Z`` on Windows) for End Of File. - -* Update your mailroom program to use exceptions (and IBAFP) to handle - malformed numeric input +* Create a wrapper function, perhaps ``safe_input()`` that returns ``None`` rather rather than raising these exceptions, when the user enters ``^C`` for Keyboard Interrupt, or ``^D`` (``^Z`` on Windows) for End Of File. +* Update your mailroom program to use exceptions to handle malformed numeric input. diff --git a/slides_sources/source/exercises/fib_and_lucas.rst b/slides_sources/source/exercises/fib_and_lucas.rst index 0181536..f47c1ce 100644 --- a/slides_sources/source/exercises/fib_and_lucas.rst +++ b/slides_sources/source/exercises/fib_and_lucas.rst @@ -22,6 +22,7 @@ We will write a function that computes this series -- then generalize it. .. _Fibonacci Series: http://en.wikipedia.org/wiki/Fibbonaci_Series + Step 1 ------ @@ -57,6 +58,7 @@ In your ``series.py`` module, add a new function ``lucas`` that returns the Ensure that your function has a well-formed ``docstring`` + Generalizing ------------ @@ -75,8 +77,35 @@ parameters will produce other series. Ensure that your function has a well-formed ``docstring`` -Tests... --------- + +assert +------ + +Writing ``tests`` that demonstrate that your program works is an important part of learning to program. + +The python ``assert`` statement is useful in writing simple tests +for your code. + +.. code-block:: ipython + + In [1]: def add(n1, n2): + ...: return n1 + n2 + ...: + + In [2]: assert add(3, 4) == 7 + + In [3]: assert add(3, 4) == 10 + + --------------------------------------------------------------------- + AssertionError Traceback (most recent call last) + in () + ----> 1 assert add(3, 4) == 10 + + AssertionError: + + +Tests +----- Add a block of code to the end of your ``series.py`` module. Use the block to write a series of ``assert`` statements that @@ -91,3 +120,5 @@ your implementation. Include good commit messages that explain concisely both When you are finished, push your changes to your fork of the class repository in GitHub and make a pull request. + + diff --git a/slides_sources/source/exercises/functions_as_args.rst b/slides_sources/source/exercises/functions_as_args.rst new file mode 100644 index 0000000..44bcbf8 --- /dev/null +++ b/slides_sources/source/exercises/functions_as_args.rst @@ -0,0 +1,52 @@ +.. _exercise_slicing: + + +Passing functions to functions +****************************** + +Goal +---- + +Practice passing functions as arguments to other functions + + +Scenario +-------- + +You are a game designer working on a scoring system. You have several different categories of weapons: hand weapons, guns, and flower power weapons. In each of these categories of weapon there is a small, a medium and a large weapon. Your task is to write a scoring function that takes two arguments and returns an integer which represets the score value of the specified size of the specified weapon. + +The first argument to the scoring function is itself a function that represents the cagetory of weapon, be it a hand weapon, a gun or a weapon of the dreaded flower power variety. + +The second argument to the scoring function is one of three strings: small, medium or large. + +The score for weapons across the various categories follow the fibonacci scale such that acceptance tests for the scoring function follow the following pattern. Keep in mind that you need not do any math to get the tests to pass. + +.. code-block:: python + + def test_scoring(): + assert score(hand_weapon, 'small') == 1 + assert score(hand_weapon, 'medium') == 2 + assert score(hand_weapon, 'large') == 3 + assert score(gun, 'small') == 5 + assert score(gun, 'medium') == 8 + assert score(gun, 'large') == 13 + assert score(flower_power, 'small') == 21 + assert score(flower_power, 'medium') == 34 + assert score(flower_power, 'large') == 55 + + +Your task is to fill out the following functions. + +.. code-block:: python + + def hand_weapon(): + pass + + def gun(): + pass + + def flower_power(): + pass + + def score(weapon_type, weapon_size): + pass diff --git a/slides_sources/source/exercises/index.rst b/slides_sources/source/exercises/index.rst index 51cc103..473bc9e 100644 --- a/slides_sources/source/exercises/index.rst +++ b/slides_sources/source/exercises/index.rst @@ -49,7 +49,7 @@ Session 6: .. toctree:: :maxdepth: 1 - lambda_magic + functions_as_args trapezoid Session 7: @@ -65,5 +65,12 @@ Session 8: :maxdepth: 1 circle_class - sparse_array + + +Session 9: +---------- +.. toctree:: + :maxdepth: 1 + + lambda_magic diff --git a/slides_sources/source/exercises/list_lab.rst b/slides_sources/source/exercises/list_lab.rst index cb5aaae..99767d5 100644 --- a/slides_sources/source/exercises/list_lab.rst +++ b/slides_sources/source/exercises/list_lab.rst @@ -31,7 +31,7 @@ to query the user for info at the command line, you use: Procedure --------- -In your student dir in the IntroPython2015 repo, create a ``session02`` dir and put in a new ``list_lab.py`` file. +In your student dir in the repo, create a directory for today's session and put in a new ``list_lab.py`` file. The file should be an executable python script. That is to say that one should be able to run the script directly like so: diff --git a/slides_sources/source/exercises/mailroom.rst b/slides_sources/source/exercises/mailroom.rst index 077349b..c9f9ac1 100644 --- a/slides_sources/source/exercises/mailroom.rst +++ b/slides_sources/source/exercises/mailroom.rst @@ -84,8 +84,4 @@ about so far. There is no need to go any farther than that for this assignment. Submission ---------- -As always, put the new file in your student directory in a ``session03`` -directory, and add it to your clone early. Make frequent commits with -good, clear messages about what you are doing and why. - -When you are done, push your changes and make a pull request. +As always, put the new file in your student directory and git add it to your repo early. Make frequent commits with good, clear messages about what you are doing and why. When you are done, push your changes and make a pull request. diff --git a/slides_sources/source/include.rst b/slides_sources/source/include.rst index 0238567..fd6ea04 100644 --- a/slides_sources/source/include.rst +++ b/slides_sources/source/include.rst @@ -1,16 +1,124 @@ +.. include.rst +.. +.. Include this file at the top of project source files to effect substitutions in the source. +.. Note that preformatted/code blocks ignore .rst style substitutions. + +.. |course-name-short| replace:: Python300 +.. |course-name-long| replace:: Systems Programming with Python +.. |course-term| replace:: Summer 2016 +.. |course-meeting-time| replace:: tbd +.. |course-meeting-location| replace:: tbd .. |instructor_1_name| replace:: Rick Riehle .. |instructor_1_email| replace:: rriehle (at) uw (dot) edu -.. |instructor_2_name| replace:: Kai Yang -.. |instructor_2_email| replace:: hky2 (at) uw (dot) edu +.. |instructor_2_name| replace:: Summer Rae +.. |instructor_2_email| replace:: summe (at) uw (dot) edu .. |repo-url| replace:: https://github.com/UWPCE-PythonCert/IntroPython2016a - .. |gh-pages-url| replace:: http://uwpce-pythoncert.github.io/IntroPython2016a/ .. |cms| replace:: https://canvas.uw.edu/courses/1026775 - .. |discussion-forum| replace:: https://canvas.uw.edu/courses/1026775/discussion_topics -.. |office-hours-time| replace:: 10 a.m. to noon on Sundays \ No newline at end of file +.. |office-hours-time| replace:: 10 a.m. to noon on Sundays +.. |office-hours-location| replace:: tbd + +.. |lightning-session02a| replace:: tbd +.. |lightning-session02b| replace:: tbd +.. |lightning-session02c| replace:: tbd +.. |lightning-session02d| replace:: tbd +.. |lightning-session02e| replace:: tbd +.. |lightning-session02f| replace:: tbd +.. |lightning-session02g| replace:: tbd +.. |lightning-session02h| replace:: tbd +.. |lightning-session02i| replace:: tbd +.. |lightning-session02j| replace:: tbd + +.. |lightning-session03a| replace:: John Rudolph +.. |lightning-session03b| replace:: Mike Schincariol +.. |lightning-session03c| replace:: tbd +.. |lightning-session03d| replace:: tbd +.. |lightning-session03e| replace:: tbd +.. |lightning-session03f| replace:: tbd +.. |lightning-session03g| replace:: tbd +.. |lightning-session03h| replace:: tbd +.. |lightning-session03i| replace:: tbd +.. |lightning-session03j| replace:: tbd + +.. |lightning-session04a| replace:: Chi Ho +.. |lightning-session04b| replace:: Tom Gaffney +.. |lightning-session04c| replace:: tbd +.. |lightning-session04d| replace:: tbd +.. |lightning-session04e| replace:: tbd +.. |lightning-session04f| replace:: tbd +.. |lightning-session04g| replace:: tbd +.. |lightning-session04h| replace:: tbd +.. |lightning-session04i| replace:: tbd +.. |lightning-session04j| replace:: tbd + +.. |lightning-session05a| replace:: tbd +.. |lightning-session05b| replace:: tbd +.. |lightning-session05c| replace:: tbd +.. |lightning-session05d| replace:: tbd +.. |lightning-session05e| replace:: tbd +.. |lightning-session05f| replace:: tbd +.. |lightning-session05g| replace:: tbd +.. |lightning-session05h| replace:: tbd +.. |lightning-session05i| replace:: tbd +.. |lightning-session05j| replace:: tbd + +.. |lightning-session06a| replace:: Gregory McKeag +.. |lightning-session06b| replace:: Bryan Glogowski +.. |lightning-session06c| replace:: (anyone?) +.. |lightning-session06d| replace:: (anyone?) +.. |lightning-session06e| replace:: (anyone?) +.. |lightning-session06f| replace:: tbd +.. |lightning-session06g| replace:: tbd +.. |lightning-session06h| replace:: tbd +.. |lightning-session06i| replace:: tbd +.. |lightning-session06j| replace:: tbd + +.. |lightning-session07a| replace:: (anyone?) +.. |lightning-session07b| replace:: Michael Gregor +.. |lightning-session07c| replace:: Tsega Solomon +.. |lightning-session07d| replace:: Yuanrui (Robert) Zhao +.. |lightning-session07e| replace:: tbd +.. |lightning-session07f| replace:: tbd +.. |lightning-session07g| replace:: tbd +.. |lightning-session07h| replace:: tbd +.. |lightning-session07i| replace:: tbd +.. |lightning-session07j| replace:: tbd + +.. |lightning-session08a| replace:: Deana Holmer +.. |lightning-session08b| replace:: Brennen Bounds +.. |lightning-session08c| replace:: tbd +.. |lightning-session08d| replace:: tbd +.. |lightning-session08e| replace:: tbd +.. |lightning-session08f| replace:: tbd +.. |lightning-session08g| replace:: tbd +.. |lightning-session08h| replace:: tbd +.. |lightning-session08i| replace:: tbd +.. |lightning-session08j| replace:: tbd + +.. |lightning-session09a| replace:: Krishna Bindhu +.. |lightning-session09b| replace:: Calvin Fannin +.. |lightning-session09c| replace:: tbd +.. |lightning-session09d| replace:: tbd +.. |lightning-session09e| replace:: Pradeep Kumar +.. |lightning-session09f| replace:: tbd +.. |lightning-session09g| replace:: tbd +.. |lightning-session09h| replace:: tbd +.. |lightning-session09i| replace:: tbd +.. |lightning-session09j| replace:: tbd + +.. |lightning-session10a| replace:: Benjamin Warren +.. |lightning-session10b| replace:: Brandon Aleson +.. |lightning-session10c| replace:: Susan Rees +.. |lightning-session10d| replace:: Luis Ganzalez +.. |lightning-session10e| replace:: Damian Myerscough +.. |lightning-session10f| replace:: Kyle Chinn +.. |lightning-session10g| replace:: Michael Newton +.. |lightning-session10h| replace:: Kishan Sarpangala +.. |lightning-session10i| replace:: Jaemin Chang +.. |lightning-session10j| replace:: tbd diff --git a/slides_sources/source/session02.rst b/slides_sources/source/session02.rst index c43aabb..977122f 100644 --- a/slides_sources/source/session02.rst +++ b/slides_sources/source/session02.rst @@ -273,13 +273,13 @@ When you add a *remote* (existing git repository), it creates a directory with t .. code-block:: bash - $ git remote add upstream https://github.com/UWPCE-PythonCert/IntroPython2015.git + $ git remote add upstream https://github.com/UWPCE-PythonCert/IntroPython2016a.git $ git remote -v - origin https://github.com/PythonCHB/IntroPython2015.git (fetch) - origin https://github.com/PythonCHB/IntroPython2015.git (push) - upstream https://github.com/UWPCE-PythonCert/IntroPython2015.git (fetch) - upstream https://github.com/UWPCE-PythonCert/IntroPython2015.git (push) + origin https://github.com/UWPCE-PythonCert/IntroPython2016a.git (fetch) + origin https://github.com/UWPCE-PythonCert/IntroPython2016a.git (push) + upstream https://github.com/UWPCE-PythonCert/IntroPython2016a.git (fetch) + upstream https://github.com/UWPCE-PythonCert/IntroPython2016a.git (push) .. nextslide:: @@ -322,7 +322,7 @@ Start by making sure you are on your own master branch: $ git checkout master This is **really really** important. Take the time to ensure you are where you -think you are, iow, not on a remote. Use git status to find out where you are, if necesary. +think you are, in other words, not on a remote. Use git status to see where you are. .. nextslide:: Merging Upstream Changes @@ -387,12 +387,12 @@ You can incorporate this into your daily workflow: :: Because of the way we have set up the class, you will be able to see all work submitted to us from everyone in the class in the students directory on your machine. This is not a bad thing. -And the files tend to be small. +The files tend to be small. We encourage sharing of knowledge in this class. Helping your fellow students will also help you to better understand. Share -your code, and get use to giving/receiving feedback on how to -improve your code, if you are not already. +your code, and get used to giving and receiving feedback on how +to improve your code, if you are not already. LAB: Grid Printer @@ -455,7 +455,7 @@ Lightning Talk: .. rst-class:: center medium -Brendan Fogarty + Beyond Printing @@ -482,13 +482,13 @@ Making a Decision .. code-block:: python if a: - print 'a' + print('a') elif b: - print 'b' + print('b') elif c: - print 'c' + print('c') else: - print 'that was unexpected' + print('that was unexpected') .. nextslide:: if @@ -498,15 +498,15 @@ What's the difference between these two? .. code-block:: python if a: - print 'a' + print('a') elif b: - print 'b' + print('b') ## versus... if a: - print 'a' + print('a') if b: - print 'b' + print('b') @@ -606,7 +606,7 @@ Lightning Talk: .. rst-class:: center medium -Bruce Bauman + More on Functions @@ -963,7 +963,7 @@ Lightning Talk: .. rst-class:: center medium -Michelle Yu + Boolean Expressions @@ -1209,7 +1209,7 @@ LAB: Booleans Experiment with ``locals`` by adding this statement one of the functions you wrote today:: - print locals() + print(locals()) Code Structure, Modules, and Namespaces @@ -1245,7 +1245,7 @@ You can put a one-liner after the colon: .. code-block:: ipython In [167]: x = 12 - In [168]: if x > 4: print x + In [168]: if x > 4: print(x) 12 But this should only be done if it makes your code **more** readable. @@ -1516,11 +1516,13 @@ Next Class * Strings and String Formatting * Lightning talks by: - - Eric Rosko - - Michael Waddle - - Robert Stevens Alford + +| +| +| +| -Office hours: Sunday 10:00 -- 12:00 +Office hours: |office-hours-time| Homework diff --git a/slides_sources/source/session03.rst b/slides_sources/source/session03.rst index 0f13df2..b348f95 100644 --- a/slides_sources/source/session03.rst +++ b/slides_sources/source/session03.rst @@ -45,11 +45,11 @@ Lightning Talks Today: .. rst-class:: mlarge - Eric Rosko + John Rudolph - Michael Waddle + Mike Schincariol - Robert Alford + Chi Ho Sequences @@ -272,7 +272,6 @@ Indexing past the end of a sequence will raise an error, slicing will not: Out[132]: " -(demo) Membership ---------- @@ -455,12 +454,7 @@ Slicing LAB Lightning Talks ---------------- -| -| Eric Rosko -| -| -| Michael Waddle -| + Ready.... go! Lists, Tuples... @@ -931,6 +925,19 @@ This looks benign enough, but changing a list while you are iterating over it ca For example: +.. code-block:: ipython + + In [27]: l = list(range(10)) + In [28]: l + Out[28]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + In [29]: for item in l: + ....: l.remove(item) + ....: + +.. nextslide:: Was this what you expected? + +For example: + .. code-block:: ipython In [27]: l = list(range(10)) @@ -942,8 +949,6 @@ For example: In [30]: l Out[30]: [1, 3, 5, 7, 9] -Was that what you expected? - .. nextslide:: The Solution Iterate over a copy, and mutate the original: @@ -1115,9 +1120,7 @@ Let's play a bit with Python lists... Lightning Talk --------------- -| -| Robert Alford -| + Place holder... any more? Iteration @@ -1389,7 +1392,6 @@ You can also use ``str()`` In [256]: str(34) Out[256]: '34' -(demo) String Methods @@ -1712,12 +1714,8 @@ Next Week: **Lightning talks next week:** -Andrey Gusev - -Cheryl Ohashi - -Maxwell MacCamy + (Your name here) diff --git a/slides_sources/source/session04.rst b/slides_sources/source/session04.rst index 2170666..bbfaecf 100644 --- a/slides_sources/source/session04.rst +++ b/slides_sources/source/session04.rst @@ -1,203 +1,941 @@ .. include:: include.rst -******************************************* -Session Four: Dictionaries, Sets, and Files -******************************************* +*********************************************************** +Session Four: Lists, Iteration, Strings, Dictionaries, Sets +*********************************************************** + + +Announcements +============= -================ Review/Questions ================ -Review of Previous Classes + +Homework +-------- + +Let's take a look. + + +Topics for Today +================ + +.. rst-class:: build left + +* Lists +* Iteration +* Strings +* Dictionaries +* Sets + + Driving toward the mailroom. + + + +Lightning Talks +--------------------- + +.. rst-class:: medium + + Chi Ho + + Tom Gaffney + + Anybody else ready? I'll be asking for volunteers at the end of class. + + + +Lists +===== + +.. rst-class:: left + +In addition to all the methods supported by sequences we've already seen, mutable sequences such as Lists have a number of other methods. + +You can find all these in the Standard Library Documentation: + +https://docs.python.org/3/library/stdtypes.html#typesseq-mutable + + +Assignment +----------- + +You've already seen changing a single element of a list by assignment. + +Pretty much the same as "arrays" in most languages: + +.. code-block:: ipython + + In [100]: list = [1, 2, 3] + In [101]: list[2] = 10 + In [102]: list + Out[102]: [1, 2, 10] + + +Growing the List +---------------- + +``.append()``, ``.insert()``, ``.extend()`` + +.. code-block:: ipython + + In [74]: food = ['spam', 'eggs', 'ham'] + In [75]: food.append('sushi') + In [76]: food + Out[76]: ['spam', 'eggs', 'ham', 'sushi'] + In [77]: food.insert(0, 'beans') + In [78]: food + Out[78]: ['beans', 'spam', 'eggs', 'ham', 'sushi'] + In [79]: food.extend(['bread', 'water']) + In [80]: food + Out[80]: ['beans', 'spam', 'eggs', 'ham', 'sushi', 'bread', 'water'] + + +.. nextslide:: More on Extend + +You can pass any sequence to ``.extend()``: + +.. code-block:: ipython + + In [85]: food + Out[85]: ['beans', 'spam', 'eggs', 'ham', 'sushi', 'bread', 'water'] + In [86]: food.extend('spaghetti') + In [87]: food + Out[87]: + ['beans', 'spam', 'eggs', 'ham', 'sushi', 'bread', 'water', + 's', 'p', 'a', 'g', 'h', 'e', 't', 't', 'i'] + + +Shrinking a List +---------------- + +``.pop()``, ``.remove()`` + +.. code-block:: ipython + + In [203]: food = ['spam', 'eggs', 'ham', 'toast'] + In [204]: food.pop() + Out[204]: 'toast' + In [205]: food.pop(0) + Out[205]: 'spam' + In [206]: food + Out[206]: ['eggs', 'ham'] + In [207]: food.remove('ham') + In [208]: food + Out[208]: ['eggs'] + +.. nextslide:: Removing Chunks of a List + +You can also delete *slices* of a list with the ``del`` keyword: + +.. code-block:: ipython + + In [92]: nums = range(10) + In [93]: nums + Out[93]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + In [94]: del nums[1:6:2] + In [95]: nums + Out[95]: [0, 2, 4, 6, 7, 8, 9] + In [96]: del nums[-3:] + In [97]: nums + Out[97]: [0, 2, 4, 6] + + +Copying Lists +------------- + +You can make copies of part of a list using *slicing*: + +.. code-block:: ipython + + In [227]: food = ['spam', 'eggs', 'ham', 'sushi'] + In [228]: some_food = food[1:3] + In [229]: some_food[1] = 'bacon' + In [230]: food + Out[230]: ['spam', 'eggs', 'ham', 'sushi'] + In [231]: some_food + Out[231]: ['eggs', 'bacon'] + +If you provide *no* arguments to the slice, it makes a copy of the entire list: + +.. code-block:: ipython + + In [232]: food + Out[232]: ['spam', 'eggs', 'ham', 'sushi'] + In [233]: food2 = food[:] + In [234]: food is food2 + Out[234]: False + + +.. nextslide:: Shallow Copies + +The copy of a list made this way is a *shallow copy*. + +The list is itself a new object, but the objects it contains are not. + +*Mutable* objects in the list can be mutated in both copies: + +.. code-block:: ipython + + In [249]: food = ['spam', ['eggs', 'ham']] + In [251]: food_copy = food[:] + In [252]: food[1].pop() + Out[252]: 'ham' + In [253]: food + Out[253]: ['spam', ['eggs']] + In [256]: food.pop(0) + Out[256]: 'spam' + In [257]: food + Out[257]: [['eggs']] + In [258]: food_copy + Out[258]: ['spam', ['eggs']] + + +.. nextslide:: Copies Solve Problems + +Consider this common pattern: + +.. code-block:: python + + for x in somelist: + if should_be_removed(x): + somelist.remove(x) + +This looks benign enough, but changing a list while you are iterating over it can be the cause of some pernicious bugs. + +.. nextslide:: The Problem + +For example: + +.. code-block:: ipython + + In [27]: l = list(range(10)) + In [28]: l + Out[28]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + In [29]: for item in l: + ....: l.remove(item) + ....: + +.. nextslide:: Was this what you expected? + +For example: + +.. code-block:: ipython + + In [27]: l = list(range(10)) + In [28]: l + Out[28]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + In [29]: for item in l: + ....: l.remove(item) + ....: + In [30]: l + Out[30]: [1, 3, 5, 7, 9] + +.. nextslide:: The Solution + +Iterate over a copy, and mutate the original: + +.. code-block:: ipython + + In [33]: l = list(range(10)) + + In [34]: for item in l[:]: + ....: l.remove(item) + ....: + In [35]: l + Out[35]: [] + + +.. nextslide:: Just Say It, Already + +Okay, so we've done this a bunch already, but let's state it out loud. + +You can iterate over a sequence. + +.. code-block:: python + + for element in sequence: + do_something(element) + +which is what we mean when we say a sequence is an "iterable". + +Again, we'll touch more on this in a short while, but first a few more words about Lists and Tuples. + + +Miscellaneous List Methods -------------------------- - * Sequences +These methods change a list in place and are not available on immutable sequence types. - - Slicing - - Lists - - Tuples - - tuple vs lists - which to use? +``.reverse()`` - * interating +.. code-block:: ipython - - for - - while + In [129]: food = ['spam', 'eggs', 'ham'] + In [130]: food.reverse() + In [131]: food + Out[131]: ['ham', 'eggs', 'spam'] - - break and continue +``.sort()`` - - else with loops +.. code-block:: ipython -Any questions? + In [132]: food.sort() + In [133]: food + Out[133]: ['eggs', 'ham', 'spam'] -Lightning Talks Today: ----------------------- +Because these methods mutate the list in place, they have a return value of ``None`` -.. rst-class:: mlarge - Andrey Gusev +.. nextslide:: Custom Sorting - Cheryl Ohashi +``.sort()`` can take an optional ``key`` parameter. - Maxwell MacCamy +It should be a function that takes one parameter (list items one at a time) and returns something that can be used for sorting: +.. code-block:: ipython -============================== -Handy hints for/from Homework -============================== + In [137]: def third_letter(string): + .....: return string[2] + .....: + In [138]: food.sort(key=third_letter) + In [139]: food + Out[139]: ['spam', 'eggs', 'ham'] -.. rst-class:: mlarge - You almost never need to loop through the indexes of a sequence -nifty for loop tricks ---------------------- +List Performance +---------------- -**tuple unpacking:** +.. rst-class:: build -remember this? +* indexing is fast and constant time: O(1) +* ``x in l`` is proportional to n: O(n) +* visiting all is proportional to n: O(n) +* operating on the end of list is fast and constant time: O(1) + + * append(), pop() + +* operating on the front (or middle) of the list depends on n: O(n) + + * ``pop(0)``, ``insert(0, v)`` + * But, reversing is fast. ``Also, collections.deque`` + + http://wiki.python.org/moin/TimeComplexity + + +Choosing Lists or Tuples +------------------------ + +Here are a few guidelines on when to choose a list or a tuple: + +* If it needs to mutable: list + +* If it needs to be immutable: tuple + + * (safety when passing to a function) + +Otherwise ... taste and convention + + +Convention +----------- + + +Lists are Collections (homogeneous): +-- contain values of the same type +-- simplifies iterating, sorting, etc + +tuples are mixed types: +-- Group multiple values into one logical thing +-- Kind of like simple C structs. + + +Other Considerations +-------------------- + +.. rst-class:: build + +* Do the same operation to each element? + + * list + +* Small collection of values which make a single logical item? + + * tuple + +* To document that these values won't change? + + * tuple + +* Build it iteratively? + + * list + +* Transform, filter, etc? + + * list + + +More Documentation +------------------ + +For more information, read the list docs: + +https://docs.python.org/3.5/library/stdtypes.html#mutable-sequence-types + +(actually any mutable sequence....) + + +List Lab +--------- + +Let's play a bit with Python lists... + +:ref:`exercise_list_lab` + + + +Lightning Talk +============== + +.. rst-class:: center large + +Chi Ho + + + +Iteration +========= + +.. rst-class:: build + +Repetition, Repetition, Repetition, Repe... + + +For Loops +--------- + +We've seen simple iteration over a sequence with ``for ... in``: + +.. code-block:: ipython + + In [170]: for x in "a string": + .....: print(x) + .....: + a + s + t + r + i + n + g + + +.. nextslide:: No Indexing Required + +Contrast this with other languages, where you must build and use an ``index``: + +.. code-block:: javascript + + for(var i = 0; i < arr.length; i++) { + var value = arr[i]; + alert(i + value); + } + +If you *do* need an index, you can use ``enumerate``: + +.. code-block:: ipython + + In [140]: for idx, letter in enumerate('Python'): + .....: print(idx, letter, end=' ') + .....: + 0 P 1 y 2 t 3 h 4 o 5 n + + +``range`` and ``for`` Loops +--------------------------- + +The ``range`` builtin is useful for looping a known number of times: + +.. code-block:: ipython + + In [171]: for i in range(5): + .....: print(i) + .....: + 0 + 1 + 2 + 3 + 4 + +But you don't really need to do anything at all with ``i`` + +.. nextslide:: + +In fact, it's a common convension to make this clear with a "nothing" name: + +.. code-block:: ipython + + In [21]: for __ in range(5): + ....: print("*") + ....: + * + * + * + * + * + + +.. nextslide:: Loop Control + +Sometimes you want to interrupt or alter the flow of control through a loop. + +Loops can be controlled in two ways, with ``break`` and ``continue`` + + +.. nextslide:: Break + +The ``break`` keyword will cause a loop to immediately terminate: + +.. code-block:: ipython + + In [141]: for i in range(101): + .....: print(i) + .....: if i > 50: + .....: break + .....: + 0 1 2 3 4 5... 46 47 48 49 50 51 + +.. nextslide:: Continue + +The ``continue`` keyword will skip later statements in the loop block, but +allow iteration to continue: + +.. code-block:: ipython + + In [143]: for in in range(101): + .....: if i > 50: + .....: break + .....: if i < 25: + .....: continue + .....: print(i, end=' ') + .....: + 25 26 27 28 29 ... 41 42 43 44 45 46 47 48 49 50 + +.. nextslide:: else + +For loops can also take an optional ``else`` block. + +Executed only when the loop exits normally (not via break): + +.. code-block:: ipython + + In [147]: for x in range(10): + .....: if x == 11: + .....: break + .....: else: + .....: print('finished') + finished + In [148]: for x in range(10): + .....: if x == 5: + .....: print(x) + .....: break + .....: else: + .....: print('finished') + 5 + +This is a really nice unique Python feature! + + +While Loops +----------- + +The ``while`` keyword is for when you don't know how many loops you need. + +It continues to execute the body until condition is not ``True``:: + + while a_condition: + some_code + in_the_body + +.. nextslide:: ``while`` vs. ``for`` + +``while`` is more general than ``for`` + +-- you can always express ``for`` as ``while``, but not always vice-versa. + +``while`` is more error-prone -- requires some care to terminate + +loop body must make progress, so condition can become ``False`` + +potential error -- infinite loops: .. code-block:: python - x, y = 3, 4 + i = 0; + while i < 5: + print(i) -You can do that in a for loop, also: + +.. nextslide:: Terminating a while Loop + +Use ``break``: .. code-block:: ipython - In [4]: l = [(1, 2), (3, 4), (5, 6)] + In [150]: while True: + .....: i += 1 + .....: if i > 10: + .....: break + .....: print(i) + .....: + 1 2 3 4 5 6 7 8 9 10 - In [5]: for i, j in l: - print("i:%i, j:%i"%(i, j)) +.. nextslide:: Terminating a while Loop - i:1, j:2 - i:3, j:4 - i:5, j:6 +Set a flag: -(Mailroom example) +.. code-block:: ipython + + In [156]: import random + In [157]: keep_going = True + In [158]: while keep_going: + .....: num = random.choice(range(5)) + .....: print(num) + .....: if num == 3: + .....: keep_going = False + .....: + 3 + +.. nextslide:: Terminating a While Loop + +Use a condition: + +.. code-block:: ipython + + In [161]: while i < 10: + .....: i += random.choice(range(4)) + .....: print(i) + .....: + 0 0 2 3 4 6 8 8 8 9 12 + + +Similarities +------------ + +Both ``for`` and ``while`` loops can use ``break`` and ``continue`` for +internal flow control. + +Both ``for`` and ``while`` loops can have an optional ``else`` block +In both loops, the statements in the ``else`` block are only executed if the +loop terminates normally (no ``break``) + + +Lightning Talk +============== + +.. rst-class:: center large + +Tom Gaffney + + +Strings +======= + +.. rst-class:: left + +Quick review: a string literal creates a string type: + +.. code-block:: python + + "this is a string" + + 'So is this' + + "And maybe y'all need somthing like this!" + + """and this also""" + +.. rst-class:: left + +You can also use ``str()`` + +.. code-block:: ipython + + In [256]: str(34) + Out[256]: '34' + + + +String Methods +-------------- + +String objects have a lot of methods. + +Here are just a few: + +String Manipulations +--------------------- + +``split`` and ``join``: + +.. code-block:: ipython + + In [167]: csv = "comma, separated, values" + In [168]: csv.split(', ') + Out[168]: ['comma', 'separated', 'values'] + In [169]: psv = '|'.join(csv.split(', ')) + In [170]: psv + Out[170]: 'comma|separated|values' + + +Case Switching +-------------- + +.. code-block:: ipython + + In [171]: sample = 'A long string of words' + In [172]: sample.upper() + Out[172]: 'A LONG STRING OF WORDS' + In [173]: sample.lower() + Out[173]: 'a long string of words' + In [174]: sample.swapcase() + Out[174]: 'a LONG STRING OF WORDS' + In [175]: sample.title() + Out[175]: 'A Long String Of Words' + + +Testing +-------- + +.. code-block:: ipython + + In [181]: number = "12345" + In [182]: number.isnumeric() + Out[182]: True + In [183]: number.isalnum() + Out[183]: True + In [184]: number.isalpha() + Out[184]: False + In [185]: fancy = "Th!$ $tr!ng h@$ $ymb0l$" + In [186]: fancy.isalnum() + Out[186]: False + + +String Literals +----------------- + +Common Escape Sequences:: + + \\ Backslash (\) + \a ASCII Bell (BEL) + \b ASCII Backspace (BS) + \n ASCII Linefeed (LF) + \r ASCII Carriage Return (CR) + \t ASCII Horizontal Tab (TAB) + \ooo Character with octal value ooo + \xhh Character with hex value hh + +for example -- for tab-separted values: + +.. code-block:: ipython + + In [25]: s = "these\tare\tseparated\tby\ttabs" + + In [26]: print(s) + these are separated by tabs + +https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals +https://docs.python.org/3/library/stdtypes.html#string-methods + +Raw Strings +------------ + +Add an ``r`` in front of the string literal: + +Escape Sequences Ignored + +.. code-block:: ipython + + In [408]: print("this\nthat") + this + that + In [409]: print(r"this\nthat") + this\nthat + +**Gotcha** + +.. code-block:: ipython + + In [415]: r"\" + SyntaxError: EOL while scanning string literal + + +Ordinal values +-------------- + +Characters in strings are stored as numeric values: + +* "ASCII" values: 1-127 + +* Unicode values -- 1 - 1,114,111 (!!!) + +To get the value: + +.. code-block:: ipython + + In [109]: for i in 'Chris': + .....: print(ord(i), end=' ') + 67 104 114 105 115 + In [110]: for i in (67,104,114,105,115): + .....: print(chr(i), end='') + Chris + +(these days, stick with ASCII, or use full Unicode: more on that in a few weeks) + + +Old and New string formatting +----------------------------- + +back in early python days, there was the string formatting operator: ``%`` + +.. code-block:: python + + " a string: %s and a number: %i "%("text", 45) + +This is very similar to C-style string formatting (`sprintf`). + +It's still around, and handy --- but ... + +The "new" ``format()`` method is more powerful and flexible, so we'll focus on that in this class. + +.. nextslide:: String Formatting + +The string ``format()`` method: + +.. code-block:: ipython -Looping through two loops at once: ----------------------------------- + In [62]: "A decimal integer is: {:d}".format(34) + Out[62]: 'A decimal integer is: 34' -.. rst-class:: mlarge + In [63]: "a floating point is: {:f}".format(34.5) + Out[63]: 'a floating point is: 34.500000' - ``zip`` + In [64]: "a string is the default: {}".format("anything") + Out[64]: 'a string is the default: anything' -.. code-block:: ipython - In [10]: l1 = [1, 2, 3] +Multiple placeholders: +----------------------- - In [11]: l2 = [3, 4, 5] +.. code-block:: ipython - In [12]: for i, j in zip(l1, l2): - ....: print("i:%i, j:%i"%(i, j)) - ....: - i:1, j:3 - i:2, j:4 - i:3, j:5 + In [65]: "the number is {} is {}".format('five', 5) + Out[65]: 'the number is five is 5' -Can be more than two: + In [66]: "the first 3 numbers are {}, {}, {}".format(1,2,3) + Out[66]: 'the first 3 numbers are 1, 2, 3' -.. code-block:: python +The counts must agree: - for i, j, k, l in zip(l1, l2, l3, l4): +.. code-block:: ipython + In [67]: "string with {} formatting {}".format(1) + --------------------------------------------------------------------------- + IndexError Traceback (most recent call last) + in () + ----> 1 "string with {} formatting {}".format(1) -Need the index and the item? ----------------------------- + IndexError: tuple index out of range -.. rst-class:: mlarge - ``enumerate`` +Named placeholders: +------------------- .. code-block:: ipython - In [2]: l = ['this', 'that', 'the other'] - - In [3]: for i, item in enumerate(l): - ...: print("the %ith item is: %s"%(i, item)) - ...: - the 0th item is: this - the 1th item is: that - the 2th item is: the other + In [69]: "Hello, {name}, whaddaya know?".format(name="Joe") + Out[69]: 'Hello, Joe, whaddaya know?' +You can use values more than once, and skip values: -Homework Comments ------------------ +.. code-block:: ipython -Building up a long string. + In [73]: "Hi, {name}. Howzit, {name}?".format(name='Bob') + Out[73]: 'Hi, Bob. Howzit, Bob?' -The obvious thing to do is something like:: +.. nextslide:: - msg = "" - for piece in list_of_stuff: - msg += piece +The format operator works with string variables, too: -But: strings are immutable -- python needs to create a new string each time you add a piece -- not efficient:: +.. code-block:: ipython - msg = [] - for piece in list_of_stuff: - msg.append(piece) - " ".join(msg) + In [80]: s = "{:d} / {:d} = {:f}" -appending to lists is efficient -- and so is the join() method of strings. + In [81]: a, b = 12, 3 -.. nextslide:: + In [82]: s.format(a, b, a/b) + Out[82]: '12 / 3 = 4.000000' -.. rst-class:: center mlarge +So you can dynamically build a format string -You can put a mutable item in an immutable object! +Complex Formatting +------------------ -(demo) +There is a complete syntax for specifying all sorts of options. -.. nextslide:: A couple small things: +It's well worth your while to spend some time getting to know this +`formatting language`_. You can accomplish a great deal just with this. -| -| Use string formatting -| -| The ``sum()`` function -| -| Deleting from list (list_lab) -| +.. _formatting language: https://docs.python.org/3/library/string.html#format-specification-mini-language -.. nextslide:: -What is ``assert`` for? +One Last Trick +--------------- -Testing -- NOT for issues expected to happen operationally:: +.. rst-class:: left - assert m >= 0 +For some of the exercises, you'll need to interact with a user at the +command line. -in operational code should be:: +There's a nice built in function to do this - ``input``: - if m < 0: - raise ValueError +.. code-block:: ipython -I'll cover next week ... + In [85]: fred = input('type something-->') + type something-->I've typed something -(Asserts get ignored if optimization is turned on!) + In [86]: print(fred) + I've typed something +This will display a prompt to the user, allowing them to input text and +allowing you to bind that input to a symbol. -================= -A little warm up -================= Fun with strings ------------------- +---------------- * Rewrite: ``the first 3 numbers are: %i, %i, %i"%(1,2,3)`` - for an arbitrary number of numbers... -===================== -Dictionaries and Sets -===================== +String Formatting LAB +--------------------- + +Let's play with these a bit: + +:ref:`exercise_string_formatting` + + +Dictionaries +============ -Dictionary ----------- Python calls it a ``dict`` Other languages call it: @@ -545,7 +1283,8 @@ Use explicit copy method to get a copy Sets ------ +==== + ``set`` is an unordered collection of distinct values @@ -643,316 +1382,160 @@ immutable -- for use as a key in a dict LAB: Dictionaries and Sets lab -============================== +------------------------------ Have some fun with dictionaries and sets! :ref:`exercise_dict_lab` -Lightning Talk --------------- - -| -| Maxwell MacCamy -| - - -======================== -File Reading and Writing -======================== - -Files ------ - -Text Files - -.. code-block:: python - - f = open('secrets.txt') - secret_data = f.read() - f.close() - -``secret_data`` is a string - -NOTE: these days, you probably need to use Unicode for text -- we'll get to that next week - -.. nextslide:: - -Binary Files - -.. code-block:: python - - f = open('secrets.bin', 'rb') - secret_data = f.read() - f.close() - -``secret_data`` is a byte string - -(with arbitrary bytes in it -- well, not arbitrary -- whatever is in the file.) - -(See the ``struct`` module to unpack binary data ) - - -.. nextslide:: - - -File Opening Modes - -.. code-block:: python - - f = open('secrets.txt', [mode]) - 'r', 'w', 'a' - 'rb', 'wb', 'ab' - r+, w+, a+ - r+b, w+b, a+b - - -These follow the Unix conventions, and aren't all that well documented -in the Python docs. But these BSD docs make it pretty clear: - -http://www.manpagez.com/man/3/fopen/ - -**Gotcha** -- 'w' modes always clear the file - -.. nextslide:: Text File Notes - -Text is default - - * Newlines are translated: ``\r\n -> \n`` - * -- reading and writing! - * Use \*nix-style in your code: ``\n`` - - -Gotcha: - - * no difference between text and binary on \*nix - * breaks on Windows - - -File Reading ------------- - -Reading part of a file - -.. code-block:: python - - header_size = 4096 - f = open('secrets.txt') - secret_header = f.read(header_size) - secret_rest = f.read() - f.close() - -.. nextslide:: - - -Common Idioms - -.. code-block:: python - - for line in open('secrets.txt'): - print(line) - -(the file object is an iterator!) - -.. code-block:: python - - f = open('secrets.txt') - while True: - line = f.readline() - if not line: - break - do_something_with_line() - -.. nextslide:: - -We will learn more about the keyword with later, but for now, just understand -the syntax and the advantage over the try-finally block: - -.. code-block:: python - - with open('workfile', 'r') as f: - read_data = f.read() - f.closed - True - - -File Writing ------------- +Homework +======== -.. code-block:: python +Handy hints for/from Homework +----------------------------- - outfile = open('output.txt', 'w') - for i in range(10): - outfile.write("this is line: %i\n"%i) - outfile.close() +.. rst-class:: mlarge - with open('output.txt', 'w'): - for i in range(10): - f.write("this is line: %i\n"%i) + You almost never need to loop through the indexes of a sequence +nifty for loop tricks +--------------------- -File Methods ------------- +**tuple unpacking:** -Commonly Used Methods +remember this? .. code-block:: python - f.read() f.readline() f.readlines() - - f.write(str) f.writelines(seq) - - f.seek(offset) f.tell() # for binary files, mostly + x, y = 3, 4 - f.close() +You can do that in a for loop, also: -StringIO --------- +.. code-block:: ipython -.. code-block:: python + In [4]: l = [(1, 2), (3, 4), (5, 6)] - In [417]: import io - In [420]: f = io.StringIO() - In [421]: f.write("somestuff") - In [422]: f.seek(0) - In [423]: f.read() - Out[423]: 'somestuff' - Out[424]: stuff = f.getvalue() - Out[425]: f.close() + In [5]: for i, j in l: + print("i:%i, j:%i"%(i, j)) -(handy for testing file handling code...) + i:1, j:2 + i:3, j:4 + i:5, j:6 -There is also cStringIO -- a bit faster. +(Mailroom example) -.. code-block:: python - from cStringIO import StringIO +Looping through two loops at once: +---------------------------------- -===================== -Paths and Directories -===================== +.. rst-class:: mlarge -Paths ------ + ``zip`` -Paths are generally handled with simple strings (or Unicode strings) +.. code-block:: ipython -Relative paths: + In [10]: l1 = [1, 2, 3] -.. code-block:: python + In [11]: l2 = [3, 4, 5] - 'secret.txt' - './secret.txt' + In [12]: for i, j in zip(l1, l2): + ....: print("i:%i, j:%i"%(i, j)) + ....: + i:1, j:3 + i:2, j:4 + i:3, j:5 -Absolute paths: +Can be more than two: .. code-block:: python - '/home/chris/secret.txt' - - -Either work with ``open()`` , etc. - -(working directory only makes sense with command-line programs...) - -os module ----------- + for i, j, k, l in zip(l1, l2, l3, l4): -.. code-block:: python - os.getcwd() - os.chdir(path) - os.path.abspath() - os.path.relpath() +Need the index and the item? +---------------------------- +.. rst-class:: mlarge -.. nextslide:: os.path module + ``enumerate`` -.. code-block:: python +.. code-block:: ipython - os.path.split() - os.path.splitext() - os.path.basename() - os.path.dirname() - os.path.join() + In [2]: l = ['this', 'that', 'the other'] + In [3]: for i, item in enumerate(l): + ...: print("the %ith item is: %s"%(i, item)) + ...: + the 0th item is: this + the 1th item is: that + the 2th item is: the other -(all platform independent) -.. nextslide:: directories +Homework Comments +----------------- -.. code-block:: python +Building up a long string. - os.listdir() - os.mkdir() - os.walk() +The obvious thing to do is something like:: -(higher level stuff in ``shutil`` module) + msg = "" + for piece in list_of_stuff: + msg += piece -pathlib -------- +But: strings are immutable -- python needs to create a new string each time you add a piece -- not efficient:: -``pathlib`` is a package for handling paths in an OO way: + msg = [] + for piece in list_of_stuff: + msg.append(piece) + " ".join(msg) -http://pathlib.readthedocs.org/en/pep428/ +appending to lists is efficient -- and so is the join() method of strings. -All the stuff in os.path and more: +.. nextslide:: -.. code-block:: ipython +.. rst-class:: center mlarge - In [64]: import pathlib - In [65]: pth = pathlib.Path('./') - In [66]: pth.is_dir() - Out[66]: True - In [67]: pth.absolute() - Out[67]: PosixPath('/Users/Chris/PythonStuff/UWPCE/IntroPython2015') - In [68]: for f in pth.iterdir(): - print(f) - junk2.txt - junkfile.txt - ... +You can put a mutable item in an immutable object! -=== -LAB -=== -Files Lab: If there is time. +.. nextslide:: A couple small things: -Files Lab ---------- +| +| Use string formatting +| +| The ``sum()`` function +| +| Deleting from list (list_lab) +| -In the class repo, in: +.. nextslide:: -``Examples\students.txt`` +What is ``assert`` for? -You will find the list I generated of all the students in the class, and -what programming languages they have used in the past. +Testing -- NOT for issues expected to happen operationally:: -Write a little script that reads that file, and generates a list of all -the languages that have been used. + assert m >= 0 -Extra credit: keep track of how many students specified each language. +in operational code should be:: -If you've got git set up right, ``git pull upstream master`` should update -your repo. Otherwise, you can get it from gitHub: + if m < 0: + raise ValueError -``https://github.com/UWPCE-PythonCert/IntroPython2015/blob/master/Examples/students.txt`` +I'll cover next week ... +(Asserts get ignored if optimization is turned on!) -========= -Homework -========= Recommended Reading: --------------------- * Dive Into Python: Chapt. 13,14 + Assignments: ------------- - * Finish the dict/sets lab - * Finish the Exceptions lab + * Finish lab exercises * Coding kata: trigrams * Paths and files * Update mailroom with dicts and exceptions @@ -987,27 +1570,3 @@ Text and files and dicts, and... * Experiment with different lengths for the lookup key. (3 words, 4 words, 3 letters, etc) - -Paths and File Processing --------------------------- - -* write a program which prints the full path to all files in the current - directory, one per line - -* write a program which copies a file from a source, to a destination - (without using shutil, or the OS copy command) - - - advanced: make it work for any size file: i.e. don't read the entire - contents of the file into memory at once. - - - Note that if you want it to do any kind of file, you need to open the files in binary mode: - ``open(filename, 'rb')`` (or ``'wb'`` for writing.) - -* update mailroom from last week to: - - - Use dicts where appropriate - - Write a full set of letters to everyone to individual files on disk - - See if you can use a dict to switch between the users selections - - Try to use a dict and the .format() method to do the letter as one - big template -- rather than building up a big string in parts. - diff --git a/slides_sources/source/session05.rst b/slides_sources/source/session05.rst index 74287d5..14908df 100644 --- a/slides_sources/source/session05.rst +++ b/slides_sources/source/session05.rst @@ -1,845 +1,591 @@ -.. include:: include.rst - -************************************************* -Session Five: Exceptions, Testing, Comprehensions -************************************************* - -====================== -Lightning Talks Today: -====================== - -.. rst-class:: medium - - Michael Cimino - - Pei Lin - - Tiffany Ku - -================ -Review/Questions -================ - -Review of Previous Class ------------------------- - - * Dictionaries - * Sets - * File processing, etc. - -.. nextslide:: - -.. rst-class:: center large - How many of you finished ALL the homework? -.. nextslide:: - -.. rst-class:: center large - - Sorry about that! - -.. nextslide:: - -.. rst-class:: medium - - * That was a lot. +.. include:: include.rst -.. rst-class:: medium +**************************************** +Session Five: Files, Streams & String IO +**************************************** -.. rst-class:: build - * But it's all good stuff. +Announcements +============= - * I'll take time to go over it in class. +Review & Questions +================== +Homework +======== -Homework review ---------------- +Code review -- let's take a look. -Homework Questions? -My Solutions to all the exercises in the class repo in: +Lightening talks +================ -``Solutions/Session04`` +Today’s lightening talks will be from: -A few tidbits .... -Sorting stuff in dictionaries: -------------------------------- -dicts aren't sorted, so what if you want to do something in a sorted way? -The "standard" way: -.. code-block:: python +Strings +======= - for key in sorted(d.keys()): - ... +.. rst-class:: left -Other options: +Quick review: a string literal creates a string type: .. code-block:: python - collections.OrderedDict - -Also other nifty stuff in the ``collections`` module: + "this is a string" -https://docs.python.org/3.5/library/collections.html + 'So is this' + "And maybe y'all need something like this!" -PEP 8 reminder --------------- + """and this also""" -PEP 8 (Python Enhancement Proposal 8): https://www.python.org/dev/peps/pep-0008/ +.. rst-class:: left -Is the "official" style guide for Python code. +You can also use ``str()`` -Strictly speaking, you only need to follow it for code in the standard library. - -But style matters -- consistent style makes your code easier to read and understand. - -So **follow PEP 8** +.. code-block:: ipython -*Exception* -- if you have a company style guide follow that instead. + In [256]: str(34) + Out[256]: '34' -try the "pep8" module on your code:: +String Manipulation +------------------- - $ python3 -m pip install pep8 - $ pep8 my_python_file +``split`` and ``join``: -(demo) +.. code-block:: ipython -Naming things... ----------------- + In [167]: csv = "comma, separated, values" + In [168]: csv.split(', ') + Out[168]: ['comma', 'separated', 'values'] + In [169]: psv = '|'.join(csv.split(', ')) + In [170]: psv + Out[170]: 'comma|separated|values' -It matters what names you give your variables. +Case Switching +-------------- -Python has rules about what it *allows* +.. code-block:: ipython -PEP8 has rules for style: capitalization, and underscores and all that. + In [171]: sample = 'A long string of words' + In [172]: sample.upper() + Out[172]: 'A LONG STRING OF WORDS' + In [173]: sample.lower() + Out[173]: 'a long string of words' + In [174]: sample.swapcase() + Out[174]: 'a LONG STRING OF WORDS' + In [175]: sample.title() + Out[175]: 'A Long String Of Words' -But you still get to decide within those rules. +Testing +------- -So use names that make sense to the reader. +.. code-block:: ipython -Naming Guidelines + In [181]: number = "12345" + In [182]: number.isnumeric() + Out[182]: True + In [183]: number.isalnum() + Out[183]: True + In [184]: number.isalpha() + Out[184]: False + In [185]: fancy = "Th!$ $tr!ng h@$ $ymb0l$" + In [186]: fancy.isalnum() + Out[186]: False + +String Literals ----------------- -Only use single-letter names for things with limited scope: indexes and teh like: - -.. code-block:: python - - for i, item in enumerate(a_sequence): - do_something(i, item) - -**Don't** use a name like "item", when there is a meaning to what the item is: +Common Escape Sequences:: -.. code-block:: python - - for name in all_the_names: - do_something_with(name) - -Use plurals for collections of things: - -.. code-block:: python - - names = ['Fred', 'George', ...] - -.. nextslide:: - -**Do** re-use names when the use is essentially the same, and you don't need the old one: + \\ Backslash (\) + \a ASCII Bell (BEL) + \b ASCII Backspace (BS) + \n ASCII Linefeed (LF) + \r ASCII Carriage Return (CR) + \t ASCII Horizontal Tab (TAB) + \ooo Character with octal value ooo + \xhh Character with hex value hh -.. code-block:: python +for example -- for tab-separted values: - line = line.strip() - line = line.replace(",", " ") - .... +.. code-block:: ipython -Here's a nice talk about naming: + In [25]: s = "these\tare\tseparated\tby\ttabs" -http://pyvideo.org/video/3792/name-things-once-0 + In [26]: print(s) + these are separated by tabs +https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals +https://docs.python.org/3/library/stdtypes.html#string-methods -Code Review +Raw Strings ------------ -.. rst-class:: center medium +Add an ``r`` in front of the string literal: -Anyone stuck or confused that's willing to volunteer for a live code review? +Escape Sequences Ignored -My Solutions -------------- - -Anyone look at my solutions? +.. code-block:: ipython -(yeah, not much time for that...) + In [408]: print("this\nthat") + this + that + In [409]: print(r"this\nthat") + this\nthat -Anything in particular you'd like me to go over? +**Gotcha** -========== -Exceptions -========== +.. code-block:: ipython -A really nifty python feature -- really handy! + In [415]: r"\" + SyntaxError: EOL while scanning string literal -Exceptions ----------- +(handy for regex, windows paths...) -Another Branching structure: +Ordinal values +-------------- -.. code-block:: python +Characters in strings are stored as numeric values: - try: - do_something() - f = open('missing.txt') - process(f) # never called if file missing - except IOError: - print("couldn't open missing.txt") +* "ASCII" values: 1-127 -Exceptions ----------- -Never Do this: +* Unicode values -- 1 - 1,114,111 (!!!) -.. code-block:: python +To get the value: - try: - do_something() - f = open('missing.txt') - process(f) # never called if file missing - except: - print "couldn't open missing.txt" +.. code-block:: ipython + In [109]: for i in 'Chris': + .....: print(ord(i), end=' ') + 67 104 114 105 115 + In [110]: for i in (67,104,114,105,115): + .....: print(chr(i), end='') + Chris -Exceptions ----------- +(these days, stick with ASCII, or use full Unicode: more on that in a few weeks) -Use Exceptions, rather than your own tests: +Building Strings +---------------- -Don't do this: +You can, but please don't do this: .. code-block:: python - do_something() - if os.path.exists('missing.txt'): - f = open('missing.txt') - process(f) # never called if file missing + 'Hello ' + name + '!' -It will almost always work -- but the almost will drive you crazy +(I know -- we did that in the grid_printing excercise) -.. nextslide:: - -Example from homework +Do this instead: .. code-block:: python - if num_in.isdigit(): - num_in = int(num_in) + 'Hello {}!'.format(name) -but -- ``int(num_in)`` will only work if the string can be converted to an integer. +It's much faster and safer, and easier to modify as code gets complicated. -So you can do - -.. code-block:: python +https://docs.python.org/3/library/string.html#string-formatting - try: - num_in = int(num_in) - except ValueError: - print("Input must be an integer, try again.") +Old and New string formatting +----------------------------- -Or let the Exception be raised.... - - -.. nextslide:: EAFP +back in early python days, there was the string formatting operator: ``%`` +.. code-block:: python -"it's Easier to Ask Forgiveness than Permission" + " a string: %s and a number: %i "%("text", 45) - -- Grace Hopper +This is very similar to C-style string formatting (`sprintf`). +It's still around, and handy --- but ... -http://www.youtube.com/watch?v=AZDWveIdqjY +The "new" ``format()`` method is more powerful and flexible, so we'll focus on that in this class. -(PyCon talk by Alex Martelli) +.. nextslide:: String Formatting -.. nextslide:: Do you catch all Exceptions? +The string ``format()`` method: -For simple scripts, let exceptions happen. +.. code-block:: ipython -Only handle the exception if the code can and will do something about it. + In [62]: "A decimal integer is: {:d}".format(34) + Out[62]: 'A decimal integer is: 34' -(much better debugging info when an error does occur) + In [63]: "a floating point is: {:f}".format(34.5) + Out[63]: 'a floating point is: 34.500000' + In [64]: "a string is the default: {}".format("anything") + Out[64]: 'a string is the default: anything' -Exceptions -- finally +Multiple placeholders --------------------- -.. code-block:: python - - try: - do_something() - f = open('missing.txt') - process(f) # never called if file missing - except IOError: - print("couldn't open missing.txt") - finally: - do_some_clean-up - -The ``finally:`` clause will always run - - -Exceptions -- else -------------------- - -.. code-block:: python - - try: - do_something() - f = open('missing.txt') - except IOError: - print("couldn't open missing.txt") - else: - process(f) # only called if there was no exception - -Advantage: - -you know where the Exception came from - -Exceptions -- using them ------------------------- - -.. code-block:: python +.. code-block:: ipython - try: - do_something() - f = open('missing.txt') - except IOError as the_error: - print(the_error) - the_error.extra_info = "some more information" - raise + In [65]: "the number is {} is {}".format('five', 5) + Out[65]: 'the number is five is 5' + In [66]: "the first 3 numbers are {}, {}, {}".format(1,2,3) + Out[66]: 'the first 3 numbers are 1, 2, 3' -Particularly useful if you catch more than one exception: +The counts must agree: -.. code-block:: python +.. code-block:: ipython - except (IOError, BufferError, OSError) as the_error: - do_something_with (the_error) + In [67]: "string with {} formatting {}".format(1) + --------------------------------------------------------------------------- + IndexError Traceback (most recent call last) + in () + ----> 1 "string with {} formatting {}".format(1) + IndexError: tuple index out of range -Raising Exceptions -------------------- +Named placeholders +------------------ -.. code-block:: python +.. code-block:: ipython - def divide(a,b): - if b == 0: - raise ZeroDivisionError("b can not be zero") - else: - return a / b + In [69]: "Hello, {name}, whaddaya know?".format(name="Joe") + Out[69]: 'Hello, Joe, whaddaya know?' -when you call it: +You can use values more than once, and skip values: .. code-block:: ipython - In [515]: divide (12,0) - ZeroDivisionError: b can not be zero - - -Built in Exceptions -------------------- + In [73]: "Hi, {name}. Howzit, {name}?".format(name='Bob') + Out[73]: 'Hi, Bob. Howzit, Bob?' -You can create your own custom exceptions - -But... +.. nextslide:: -.. code-block:: python +The format operator works with string variables, too: - exp = \ - [name for name in dir(__builtin__) if "Error" in name] - len(exp) - 32 +.. code-block:: ipython + In [80]: s = "{:d} / {:d} = {:f}" -For the most part, you can/should use a built in one + In [81]: a, b = 12, 3 -.. nextslide:: + In [82]: s.format(a, b, a/b) + Out[82]: '12 / 3 = 4.000000' -Choose the best match you can for the built in Exception you raise. +So you can dynamically build a format string -Example (from last week's exercises):: +Complex Formatting +------------------ - if (not isinstance(m, int)) or (not isinstance(n, int)): - raise ValueError +There is a complete syntax for specifying all sorts of options. -Is it the *value* or the input the problem here? +It's well worth your while to spend some time getting to know this +`formatting language`_. You can accomplish a great deal just with this. -Nope: the *type* is the problem:: +.. _formatting language: https://docs.python.org/3/library/string.html#format-specification-mini-language - if (not isinstance(m, int)) or (not isinstance(n, int)): - raise TypeError +``input`` +--------- -but should you be checking type anyway? (EAFP) +.. rst-class:: left -=== -LAB -=== +For some of the exercises, you'll need to interact with a user at the +command line. -Exceptions Lab: +There's a nice built in function to do this - ``input``: -A number of you already did this -- so do it at home if you haven't +.. code-block:: ipython -:ref:`exercise_exceptions_lab` + In [85]: fred = input('type something-->') + type something-->I've typed something + In [86]: print(fred) + I've typed something -Lightning Talks ----------------- +This will display a prompt to the user, allowing them to input text and +allowing you to bind that input to a symbol. -.. rst-class:: medium +Lab: String Formatting +---------------------- -| -| Michael Cimino -| -| -| Pei Lin -| +Let's play with these a bit: +:ref:`exercise_string_formatting` -============================ -List and Dict Comprehensions -============================ -List comprehensions -------------------- -A bit of functional programming +Files +===== -consider this common ``for`` loop structure: +Text Files .. code-block:: python - new_list = [] - for variable in a_list: - new_list.append(expression) + f = open('secrets.txt') + secret_data = f.read() + f.close() -This can be expressed with a single line using a "list comprehension" - -.. code-block:: python - - new_list = [expression for variable in a_list] +``secret_data`` is a string +NOTE: these days, you probably need to use Unicode for text -- we'll get to that next week .. nextslide:: -What about nested for loops? +Binary Files .. code-block:: python - new_list = [] - for var in a_list: - for var2 in a_list2: - new_list.append(expression) + f = open('secrets.bin', 'rb') + secret_data = f.read() + f.close() -Can also be expressed in one line: +``secret_data`` is a byte string -.. code-block:: python +(with arbitrary bytes in it -- well, not arbitrary -- whatever is in the file.) - new_list = [exp for var in a_list for var2 in a_list2] +(See the ``struct`` module to unpack binary data ) -You get the "outer product", i.e. all combinations. - -(demo) .. nextslide:: -But usually you at least have a conditional in the loop: - -.. code-block:: python - - new_list = [] - for variable in a_list: - if something_is_true: - new_list.append(expression) -You can add a conditional to the comprehension: +File Opening Modes .. code-block:: python - new_list = [expr for var in a_list if something_is_true] + f = open('secrets.txt', [mode]) + 'r', 'w', 'a' + 'rb', 'wb', 'ab' + r+, w+, a+ + r+b, w+b, a+b -(demo) +These follow the Unix conventions, and aren't all that well documented +in the Python docs. But these BSD docs make it pretty clear: -.. nextslide:: +http://www.manpagez.com/man/3/fopen/ -Examples: +**Gotcha** -- 'w' modes always clear the file -.. code-block:: ipython +.. nextslide:: Text File Notes - In [341]: [x**2 for x in range(3)] - Out[341]: [0, 1, 4] +Text is default - In [342]: [x+y for x in range(3) for y in range(5,7)] - Out[342]: [5, 6, 6, 7, 7, 8] + * Newlines are translated: ``\r\n -> \n`` + * -- reading and writing! + * Use \*nix-style in your code: ``\n`` - In [343]: [x*2 for x in range(6) if not x%2] - Out[343]: [0, 4, 8] +Gotcha: + * no difference between text and binary on \*nix + * breaks on Windows -.. nextslide:: +File Reading +------------ -Remember this from earlier today? +Reading part of a file .. code-block:: python - [name for name in dir(__builtin__) if "Error" in name] - ['ArithmeticError', - 'AssertionError', - 'AttributeError', - 'BufferError', - 'EOFError', - .... + header_size = 4096 + f = open('secrets.txt') + secret_header = f.read(header_size) + secret_rest = f.read() + f.close() +.. nextslide:: -Set Comprehensions ------------------- -You can do it with sets, too: +Common Idioms .. code-block:: python - new_set = { value for variable in a_sequence } - + for line in open('secrets.txt'): + print(line) -same as for loop: +(the file object is an iterator!) .. code-block:: python - new_set = set() - for key in a_list: - new_set.add(value) - + f = open('secrets.txt') + while True: + line = f.readline() + if not line: + break + do_something_with_line() .. nextslide:: -Example: finding all the vowels in a string... - -.. code-block:: ipython - - In [19]: s = "a not very long string" - - In [20]: vowels = set('aeiou') - - In [21]: { l for l in s if l in vowels } - Out[21]: {'a', 'e', 'i', 'o'} - -Side note: why did I do ``set('aeiou')`` rather than just `aeiou` ? - - -Dict Comprehensions -------------------- - -Also with dictionaries +We will learn more about the keyword with later, but for now, just understand +the syntax and the advantage over the try-finally block: .. code-block:: python - new_dict = { key:value for variable in a_sequence} + with open('workfile', 'r') as f: + read_data = f.read() + f.closed + True - -same as for loop: +File Writing +------------ .. code-block:: python - new_dict = {} - for key in a_list: - new_dict[key] = value - - - -.. nextslide:: - -Example - -.. code-block:: ipython - - In [22]: { i: "this_%i"%i for i in range(5) } - Out[22]: {0: 'this_0', 1: 'this_1', 2: 'this_2', - 3: 'this_3', 4: 'this_4'} + outfile = open('output.txt', 'w') + for i in range(10): + outfile.write("this is line: %i\n"%i) + outfile.close() + with open('output.txt', 'w') as f: + for i in range(10): + f.write("this is line: %i\n"%i) -(not as useful with the ``dict()`` constructor...) - -=== -LAB -=== - -List comps exercises: - -:ref:`exercise_comprehensions` - - - -Lightning Talk ----------------- - -.. rst-class:: medium - -| -| Tiffany Ku -| - - -======= -Testing -======= - -.. rst-class:: build left -.. container:: - - You've already seen some a very basic testing strategy. - - You've written some tests using that strategy. - - These tests were pretty basic, and a bit awkward in places (testing error - conditions in particular). - - .. rst-class:: centered - - **It gets better** - -Test Runners +File Methods ------------ -So far our tests have been limited to code in an ``if __name__ == "__main__":`` -block. - -.. rst-class:: build - -* They are run only when the file is executed -* They are always run when the file is executed -* You can't do anything else when the file is executed without running tests. - -.. rst-class:: build -.. container:: - - This is not optimal. - - Python provides testing systems to help. - - -Standard Library: ``unittest`` -------------------------------- - -The original testing system in Python. - -``import unittest`` - -More or less a port of ``Junit`` from Java - -A bit verbose: you have to write classes & methods - -(And we haven't covered that yet!) - - -Using ``unittest`` -------------------- - -You write subclasses of the ``unittest.TestCase`` class: +Commonly Used Methods .. code-block:: python - # in test.py - import unittest - - class MyTests(unittest.TestCase): - def test_tautology(self): - self.assertEquals(1, 1) + f.read() f.readline() f.readlines() -Then you run the tests by using the ``main`` function from the ``unittest`` -module: - -.. code-block:: python + f.write(str) f.writelines(seq) - # in test.py - if __name__ == '__main__': - unittest.main() + f.seek(offset) f.tell() # for binary files, mostly -.. nextslide:: Testing Your Code + f.close() -This way, you can write your code in one file and test it from another: +Stream IO +--------- .. code-block:: python - # in my_mod.py - def my_func(val1, val2): - return val1 * val2 - - # in test_my_mod.py - import unittest - from my_mod import my_func - - class MyFuncTestCase(unittest.TestCase): - def test_my_func(self): - test_vals = (2, 3) - expected = reduce(lambda x, y: x * y, test_vals) - actual = my_func(*test_vals) - self.assertEquals(expected, actual) - - if __name__ == '__main__': - unittest.main() - -.. nextslide:: Advantages of ``unittest`` - -.. rst-class:: build -.. container:: - - The ``unittest`` module is pretty full featured - - It comes with the standard Python distribution, no installation required. - - It provides a wide variety of assertions for testing all sorts of situations. - - It allows for a setup and tear down workflow both before and after all tests and before and after each test. - - It's well known and well understood. - -.. nextslide:: Disadvantages: - -.. rst-class:: build -.. container:: - - - It's Object Oriented, and quite heavy. - - - modeled after Java's ``junit`` and it shows... - - It uses the framework design pattern, so knowing how to use the features - means learning what to override. + In [417]: import io + In [420]: f = io.StringIO() + In [421]: f.write("somestuff") + In [422]: f.seek(0) + In [423]: f.read() + Out[423]: 'somestuff' + Out[424]: stuff = f.getvalue() + Out[425]: f.close() - Needing to override means you have to be cautious. +(handy for testing file handling code...) - Test discovery is both inflexible and brittle. +There is also cStringIO -- a bit faster. - And there is no built-in parameterized testing. - -Other Options -------------- - -There are several other options for running tests in Python. - -* `Nose`: https://nose.readthedocs.org/ - -* `pytest`: http://pytest.org/latest/ - -* ... (many frameworks supply their own test runners) - -Both are very capable and widely used. I have a personal preference for pytest -- so we'll use it for this class +.. code-block:: python -Installing ``pytest`` ---------------------- + from cStringIO import StringIO -The first step is to install the package: +Paths +----- -.. code-block:: bash +Paths are generally handled with simple strings (or Unicode strings) - $ python3 -m pip install pytest +Relative paths: -Once this is complete, you should have a ``py.test`` command you can run -at the command line: +.. code-block:: python -.. code-block:: bash + 'secret.txt' + './secret.txt' - $ py.test +Absolute paths: -If you have any tests in your repository, that will find and run them. +.. code-block:: python -.. rst-class:: build -.. container:: + '/home/chris/secret.txt' - **Do you?** -Pre-existing Tests ------------------- +Either work with ``open()`` , etc. -Let's take a look at some examples. +(working directory only makes sense with command-line programs...) -``IntroToPython\Examples\Session05`` +os module +---------- -`` $ py.test`` +.. code-block:: python -You can also run py.test on a particular test file: + os.getcwd() + os.chdir(path) + os.path.abspath() + os.path.relpath() -``py.test test_this.py`` -The results you should have seen when you ran ``py.test`` above come -partly from these files. +.. nextslide:: os.path module -Let's take a few minutes to look these files over. +.. code-block:: python -[demo] + os.path.split() + os.path.splitext() + os.path.basename() + os.path.dirname() + os.path.join() -.. nextslide:: What's Happening Here. -When you run the ``py.test`` command, ``pytest`` starts in your current -working directory and searches the filesystem for things that might be tests. +(all platform independent) -It follows some simple rules: +.. nextslide:: directories -.. rst-class:: build +.. code-block:: python -* Any python file that starts with ``test_`` or ``_test`` is imported. -* Any functions in them that start with ``test_`` are run as tests. -* Any classes that start with ``Test`` are treated similarly, with methods that begin with ``test_`` treated as tests. + os.listdir() + os.mkdir() + os.walk() +(higher level stuff in ``shutil`` module) -.. nextslide:: pytest +pathlib +------- -This test running framework is simple, flexible and configurable. +``pathlib`` is a package for handling paths in an OO way: -`Read the documentation`_ for more information. +http://pathlib.readthedocs.org/en/pep428/ -.. _Read the documentation: http://pytest.org/latest/getting-started.html#getstarted +All the stuff in os.path and more: -.. nextslide:: Test Driven Development +.. code-block:: ipython -What we've just done here is the first step in what is called **Test Driven -Development**. + In [64]: import pathlib + In [65]: pth = pathlib.Path('./') + In [66]: pth.is_dir() + Out[66]: True + In [67]: pth.absolute() + Out[67]: PosixPath('/Users/Chris/PythonStuff/UWPCE/IntroPython2015') + In [68]: for f in pth.iterdir(): + print(f) + junk2.txt + junkfile.txt + ... + +Lab: Files +---------- -A bunch of tests exist, but the code to make them pass does not yet exist. +In the class repo, in: -The red you see in the terminal when we run our tests is a goad to us to write -the code that fixes these tests. +``Examples\students.txt`` -Let's do that next! +You will find the list I generated of all the students in the class, and +what programming languages they have used in the past. -=== -LAB -=== +Write a little script that reads that file, and generates a list of all +the languages that have been used. -Pick an example from codingbat: +Extra credit: keep track of how many students specified each language. -``http://codingbat.com`` -Do a bit of test-driven development on it: - * run something on the web site. - * write a few tests using the examples from the site. - * then write the function, and fix it 'till it passes the tests. -Do at least two of these... -========= Homework ========= Catch up! --------- - * Finish the LABs from today - - Exceptions lab * Catch up from last week. @@ -852,9 +598,33 @@ Catch up! - https://docs.python.org/3.5/library/collections.html - here's a good overview: https://pymotw.com/3/collections/ -==================================== -Material to review before next week: -==================================== + +Paths and File Processing +-------------------------- + +* write a program which prints the full path to all files in the current + directory, one per line + +* write a program which copies a file from a source, to a destination + (without using shutil, or the OS copy command) + + - advanced: make it work for any size file: i.e. don't read the entire + contents of the file into memory at once. + + - Note that if you want it to do any kind of file, you need to open the files in binary mode: + ``open(filename, 'rb')`` (or ``'wb'`` for writing.) + +* update mailroom from last week to: + + - Use dicts where appropriate + - Write a full set of letters to everyone to individual files on disk + - See if you can use a dict to switch between the users selections + - Try to use a dict and the .format() method to do the letter as one + big template -- rather than building up a big string in parts. + + +Material to review before next week +----------------------------------- * Dive into Python3: 7.2 -- 7.3 http://www.diveintopython3.net/iterators.html#defining-classes @@ -865,7 +635,7 @@ Material to review before next week: * LPTHW: 40 -- 44 http://learnpythonthehardway.org/book/ex40.html -[note that in py3 you dont need to inherit from object] +[Note that in py3 you don't need to inherit from object] Talk by Raymond Hettinger: diff --git a/slides_sources/source/session06.rst b/slides_sources/source/session06.rst index 63aac57..58c2c2e 100644 --- a/slides_sources/source/session06.rst +++ b/slides_sources/source/session06.rst @@ -1,681 +1,644 @@ -.. include:: include.rst - -******************************************************************** -Session Six: Advanced Argument Passing, lambda, functions as objects -******************************************************************** - -====================== -Lightning Talks Today: -====================== -.. rst-class:: medium +.. include:: include.rst - Gabriel Meringolo +Session Six: Exceptions, Testing and Advanced Argument Passing +************************************************************** - Joseph Cardenas - Marc Teale -================ -Review/Questions -================ +Announcements +============= -Review of Previous Class ------------------------- +Review & Questions +================== -* Exceptions +Homework +======== -* Comprehensions +Code review -- let's take a look. -* Testing +Lightning talks =============== -Homework review -=============== - -Homework Questions? - -Notes from Homework: --------------------- -Comparing to "singletons": - -Use: +| |lightning-session06a| +| |lightning-session06b| +| |lightning-session06c| +| |lightning-session06d| +| |lightning-session06e| +| -``if something is None`` -Not: +Framing +======= -``if something == None`` +You've just started a new job, or you've inherited a project as a contractor. Your task is to migrate a system from Python 2.something to Python 3.something. All of the frameworks and major libraries in the system are years behind current versions. There are thousands of lines of code spread across dozens of modules. And you're moving from Oracle to Postgres. What do you do? -(also ``True`` and ``False``) +You are the CTO of a new big data company. Your CEO wants you to open the your Python API so that third-party developers, your clients, can supply their own functions to crunch data on your systems. What do you do? -rich comparisons: numpy -(demo) -.. nextslide:: +Exceptions +========== -Binary mode for files: +What might go wrong here? .. code-block:: python - infile = open(infilename, 'rb') - outfile = open(outfilename, 'wb') + try: + do_something() + f = open('missing.txt') + process(f) # never called if file missing + except IOError: + print("couldn't open missing.txt") -| -| +Exceptions +---------- -You don't actually need to use the result of a list comp: +Use Exceptions, rather than your own tests: + +Don't do this: .. code-block:: python - for i, st in zip( divisors, sets): - [ st.add(j) for j in range(21) if not j%i ] + do_something() + if os.path.exists('missing.txt'): + f = open('missing.txt') + process(f) # never called if file missing + +It will almost always work -- but the almost will drive you crazy .. nextslide:: -Apropos of today's topics: +Example from homework -Python functions are objects, so if you dont call them, you do'nt get an error, you jsut get the function object, ususally not what you want:: +.. code-block:: python - elif donor_name.lower == "exit": + if num_in.isdigit(): + num_in = int(num_in) -this is comparing the string ``lower`` method to the string "exit" and theyare never going to be equal! +but -- ``int(num_in)`` will only work if the string can be converted to an integer. -That should be:: +So you can do - elif donor_name.lower() == "exit": +.. code-block:: python -This is actually a pretty common typo -- keep an eye out for it when you get strange errors, or something just doesn't seem to be getting triggered. + try: + num_in = int(num_in) + except ValueError: + print("Input must be an integer, try again.") -============================ -Test Driven development demo -============================ +Or let the Exception be raised.... -We did some of this last class -- but I want to really drive it home :-) -In ``Examples/Session06/test_cigar_party.py`` +.. nextslide:: EAFP -========================= -Advanced Argument Passing -========================= +"it's Easier to Ask Forgiveness than Permission" -This is a very, very nift Python feature -- it really lets you write dynamic programs. + -- Grace Hopper -Keyword arguments ------------------ -When defining a function, you can specify only what you need -- in any order +http://www.youtube.com/watch?v=AZDWveIdqjY -.. code-block:: ipython +(PyCon talk by Alex Martelli) - In [151]: def fun(x=0, y=0, z=0): - print(x,y,z) - .....: - In [152]: fun(1,2,3) - 1 2 3 - In [153]: fun(1, z=3) - 1 0 3 - In [154]: fun(z=3, y=2) - 0 2 3 +.. nextslide:: Do you catch all Exceptions? +For simple scripts, let exceptions happen. -.. nextslide:: +Only handle the exception if the code can and will do something about it. +(much better debugging info when an error does occur) -A Common Idiom: +Exceptions -- finally +--------------------- .. code-block:: python - def fun(x, y=None): - if y is None: - do_something_different - go_on_here + try: + do_something() + f = open('missing.txt') + process(f) # never called if file missing + except IOError: + print("couldn't open missing.txt") + finally: + do_some_clean-up +The ``finally:`` clause will always run -.. nextslide:: - -Can set defaults to variables - -.. code-block:: ipython - - In [156]: y = 4 - In [157]: def fun(x=y): - print("x is:", x) - .....: - In [158]: fun() - x is: 4 - - -.. nextslide:: +Exceptions -- else +------------------- -Defaults are evaluated when the function is defined +.. code-block:: python -.. code-block:: ipython + try: + do_something() + f = open('missing.txt') + except IOError: + print("couldn't open missing.txt") + else: + process(f) # only called if there was no exception - In [156]: y = 4 - In [157]: def fun(x=y): - print("x is:", x) - .....: - In [158]: fun() - x is: 4 - In [159]: y = 6 - In [160]: fun() - x is: 4 +Advantage: -This is a **very** important point -- I will repeat it! +you know where the Exception came from +Exceptions -- using them +------------------------ -Function arguments in variables -------------------------------- +.. code-block:: python -function arguments are really just + try: + do_something() + f = open('missing.txt') + except IOError as the_error: + print(the_error) + the_error.extra_info = "some more information" + raise -* a tuple (positional arguments) -* a dict (keyword arguments) +Particularly useful if you catch more than one exception: .. code-block:: python - def f(x, y, w=0, h=0): - print("position: {}, {} -- shape: {}, {}".format(x, y, w, h)) + except (IOError, BufferError, OSError) as the_error: + do_something_with (the_error) - position = (3,4) - size = {'h': 10, 'w': 20} +Raising Exceptions +------------------- - >>> f(*position, **size) - position: 3, 4 -- shape: 20, 10 +.. code-block:: python + def divide(a,b): + if b == 0: + raise ZeroDivisionError("b can not be zero") + else: + return a / b -Function parameters in variables --------------------------------- -You can also pull the parameters out in the function as a tuple and a dict: +when you call it: .. code-block:: ipython - def f(*args, **kwargs): - print("the positional arguments are:", args) - print("the keyword arguments are:", kwargs) + In [515]: divide (12,0) + ZeroDivisionError: b can not be zero - In [389]: f(2, 3, this=5, that=7) - the positional arguments are: (2, 3) - the keyword arguments are: {'this': 5, 'that': 7} +Built in Exceptions +------------------- -This can be very powerful... +You can create your own custom exceptions -Passing a dict to str.format() -------------------------------- +But... -Now that you know that keyword args are really a dict, -you know how this nifty trick works: +.. code-block:: python -The string ``format()`` method takes keyword arguments: + exp = \ + [name for name in dir(__builtin__) if "Error" in name] + len(exp) + 32 -.. code-block:: ipython - In [24]: "My name is {first} {last}".format(last="Barker", first="Chris") - Out[24]: 'My name is Chris Barker' +For the most part, you can/should use a built in one -Build a dict of the keys and values: +.. nextslide:: -.. code-block:: ipython +Choose the best match you can for the built in Exception you raise. - In [25]: d = {"last":"Barker", "first":"Chris"} +Example (from last week's exercises):: -And pass to ``format()``with ``**`` + if (not isinstance(m, int)) or (not isinstance(n, int)): + raise ValueError -.. code-block:: ipython +Is it the *value* or the input the problem here? - In [26]: "My name is {first} {last}".format(**d) - Out[26]: 'My name is Chris Barker' +Nope: the *type* is the problem:: -LAB ----- + if (not isinstance(m, int)) or (not isinstance(n, int)): + raise TypeError -.. rst-class:: medium +but should you be checking type anyway? (EAFP) - keyword arguments: +Lab: Exceptions +--------------- -* Write a function that has four optional parameters (with defaults): +A number of you already did this -- so do it at home if you haven't - - fore_color - - back_color - - link_color - - visited_color +:ref:`exercise_exceptions_lab` -* Have it print the colors (use strings for the colors) -* Call it with a couple different parameters set -* Have it pull the parameters out with ``*args, **kwargs`` - - and print those -Lightning Talks ----------------- -.. rst-class:: medium - | - | Gabriel Meringolo - | - | Joseph Cardenas - | +Testing +======= -===================================== -A bit more on mutability (and copies) -===================================== +.. rst-class:: build left +.. container:: -mutable objects ----------------- + You've already seen some a very basic testing strategy. -We've talked about this: mutable objects can have their contents changed in place. + You've written some tests using that strategy. -Immutable objects can not. + These tests were pretty basic, and a bit awkward in places (testing error + conditions in particular). -This has implications when you have a container with mutable objects in it: + .. rst-class:: centered -.. code-block:: ipython + **It gets better** - In [28]: list1 = [ [1,2,3], ['a','b'] ] +Test Runners +------------ -one way to make a copy of a list: +So far our tests have been limited to code in an ``if __name__ == "__main__":`` +block. -.. code-block:: ipython +.. rst-class:: build - In [29]: list2 = list1[:] +* They are run only when the file is executed +* They are always run when the file is executed +* You can't do anything else when the file is executed without running tests. - In [30]: list2 is list1 - Out[30]: False +.. rst-class:: build +.. container:: -they are different lists. + This is not optimal. -.. nextslide:: + Python provides testing systems to help. -What if we set an element to a new value? +Standard Library: ``unittest`` +------------------------------- -.. code-block:: ipython +The original testing system in Python. - In [31]: list1[0] = [5,6,7] +``import unittest`` - In [32]: list1 - Out[32]: [[5, 6, 7], ['a', 'b']] +More or less a port of ``Junit`` from Java - In [33]: list2 - Out[33]: [[1, 2, 3], ['a', 'b']] +A bit verbose: you have to write classes & methods -So they are independent. +(And we haven't covered that yet!) -.. nextslide:: +Using ``unittest`` +------------------- -But what if we mutate an element? +You write subclasses of the ``unittest.TestCase`` class: -.. code-block:: ipython +.. code-block:: python - In [34]: list1[1].append('c') + # in test.py + import unittest - In [35]: list1 - Out[35]: [[5, 6, 7], ['a', 'b', 'c']] + class MyTests(unittest.TestCase): + def test_tautology(self): + self.assertEquals(1, 1) - In [36]: list2 - Out[36]: [[1, 2, 3], ['a', 'b', 'c']] +Then you run the tests by using the ``main`` function from the ``unittest`` +module: -uuh oh! mutating an element in one list mutated the one in the other list. +.. code-block:: python -.. nextslide:: + # in test.py + if __name__ == '__main__': + unittest.main() -Why is that? +.. nextslide:: Testing Your Code -.. code-block:: ipython +This way, you can write your code in one file and test it from another: - In [38]: list1[1] is list2[1] - Out[38]: True +.. code-block:: python -The elements are the same object! + # in my_mod.py + def my_func(val1, val2): + return val1 * val2 -This is known as a "shallow" copy -- Python doesn't want to copy more than it needs to, so in this case, it makes a new list, but does not make copies of the contents. + # in test_my_mod.py + import unittest + from my_mod import my_func -Same for dicts (and any container type -- even tuples!) + class MyFuncTestCase(unittest.TestCase): + def test_my_func(self): + test_vals = (2, 3) + expected = reduce(lambda x, y: x * y, test_vals) + actual = my_func(*test_vals) + self.assertEquals(expected, actual) -If the elements are immutable, it doesn't really make a differnce -- but be very careful with mutable elements. + if __name__ == '__main__': + unittest.main() +.. nextslide:: Advantages of ``unittest`` -The copy module ----------------- +.. rst-class:: build +.. container:: -most objects have a way to make copies (``dict.copy()`` for instance). + The ``unittest`` module is pretty full featured -but if not, you can use the ``copy`` module to make a copy: + It comes with the standard Python distribution, no installation required. -.. code-block:: ipython + It provides a wide variety of assertions for testing all sorts of situations. - In [39]: import copy + It allows for a setup and tear down workflow both before and after all tests and before and after each test. - In [40]: list3 = copy.copy(list2) + It's well known and well understood. - In [41]: list3 - Out[41]: [[1, 2, 3], ['a', 'b', 'c']] +.. nextslide:: Disadvantages: -This is also a shallow copy. +.. rst-class:: build +.. container:: -.. nextslide:: -But there is another option: + It's Object Oriented, and quite heavy. -.. code-block:: ipython - - In [3]: list1 - Out[3]: [[1, 2, 3], ['a', 'b', 'c']] + - modeled after Java's ``junit`` and it shows... - In [4]: list2 = copy.deepcopy(list1) + It uses the framework design pattern, so knowing how to use the features + means learning what to override. - In [5]: list1[0].append(4) + Needing to override means you have to be cautious. - In [6]: list1 - Out[6]: [[1, 2, 3, 4], ['a', 'b', 'c']] + Test discovery is both inflexible and brittle. - In [7]: list2 - Out[7]: [[1, 2, 3], ['a', 'b', 'c']] + And there is no built-in parameterized testing. -``deepcopy`` recurses through the object, making copies of everything as it goes. +Other Options +------------- -.. nextslide:: +There are several other options for running tests in Python. +* `Nose`: https://nose.readthedocs.org/ -I happened on this thread on stack overflow: +* `pytest`: http://pytest.org/latest/ -http://stackoverflow.com/questions/3975376/understanding-dict-copy-shallow-or-deep +* ... And many frameworks supply their own test runners -The OP is pretty confused -- can you sort it out? +Both are very capable and widely used. I have a personal preference for pytest -- so we'll use it for this class -Make sure you understand the difference between a reference, a shallow copy, and a deep copy. +Installing ``pytest`` +--------------------- -Mutables as default arguments: ------------------------------- +The first step is to install the package: -Another "gotcha" is using mutables as default arguments: +.. code-block:: bash -.. code-block:: ipython + $ python3 -m pip install pytest - In [11]: def fun(x, a=[]): - ....: a.append(x) - ....: print(a) - ....: +Once this is complete, you should have a ``py.test`` command you can run +at the command line: -This makes sense: maybe you'd pass in a specific list, but if not, the default is an empty list. +.. code-block:: bash -But: + $ py.test -.. code-block:: ipython +If you have any tests in your repository, that will find and run them. - In [12]: fun(3) - [3] +.. rst-class:: build +.. container:: - In [13]: fun(4) - [3, 4] + **Do you?** -Huh?! +Pre-existing Tests +------------------ -.. nextslide:: +Let's take a look at some examples. -Remember that that default argument is defined when the function is created: there will be only one list, and every time the function is called, that same list is used. +``IntroToPython\Examples\Session05`` +`` $ py.test`` -The solution: +You can also run py.test on a particular test file: -The standard practice for such a mutable default argument: +``py.test test_this.py`` -.. code-block:: ipython +The results you should have seen when you ran ``py.test`` above come +partly from these files. - In [15]: def fun(x, a=None): - ....: if a is None: - ....: a = [] - ....: a.append(x) - ....: print(a) - In [16]: fun(3) - [3] - In [17]: fun(4) - [4] +Let's take a few minutes to look these files over. -You get a new list every time the function is called +.. nextslide:: What's Happening Here. +When you run the ``py.test`` command, ``pytest`` starts in your current +working directory and searches the filesystem for things that might be tests. +It follows some simple rules: -=================== -Anonymous functions -=================== +.. rst-class:: build -lambda ------- +* Any python file that starts with ``test_`` or ``_test`` is imported. +* Any functions in them that start with ``test_`` are run as tests. +* Any classes that start with ``Test`` are treated similarly, with methods that begin with ``test_`` treated as tests. -.. code-block:: ipython - In [171]: f = lambda x, y: x+y - In [172]: f(2,3) - Out[172]: 5 +.. nextslide:: pytest -Content of function can only be an expression -- not a statement +This test running framework is simple, flexible and configurable. -Anyone remember what the difference is? +`Read the documentation`_ for more information. -Called "Anonymous": it doesn't get a name. +.. _Read the documentation: http://pytest.org/latest/getting-started.html#getstarted -.. nextslide:: +.. nextslide:: Test Driven Development -It's a python object, it can be stored in a list or other container +What we've just done here is the first step in what is called **Test Driven +Development**. -.. code-block:: ipython +A bunch of tests exist, but the code to make them pass does not yet exist. - In [7]: l = [lambda x, y: x+y] - In [8]: type(l[0]) - Out[8]: function +The red you see in the terminal when we run our tests is a goad to us to write +the code that fixes these tests. +Let's do that next! -And you can call it: +Test Driven development demo +---------------------------- -.. code-block:: ipython +In ``Examples/Session05/test_cigar_party.py`` - In [9]: l[0](3,4) - Out[9]: 7 +Lab: Testing +------------ -Functions as first class objects ---------------------------------- +Pick an example from codingbat: -You can do that with "regular" functions too: +``http://codingbat.com`` -.. code-block:: ipython +Do a bit of test-driven development on it: - In [12]: def fun(x,y): - ....: return x+y - ....: - In [13]: l = [fun] - In [14]: type(l[0]) - Out[14]: function - In [15]: l[0](3,4) - Out[15]: 7 + * run something on the web site. + * write a few tests using the examples from the site. + * then write the function, and fix it 'till it passes the tests. +Do at least two of them. +Advanced Argument Passing +========================= -====================== -Functional Programming -====================== +Calling a function +------------------ -No real consensus about what that means. +Python functions are objects, so if you don't call them, you don't get an error, you just get the function object, usually not what you want:: -But there are some "classic" methods available in Python. + elif donor_name.lower == "exit": -map ---- +This is comparing the string ``lower`` method to the string "exit" and they are never going to be equal! -``map`` "maps" a function onto a sequence of objects -- It applies the function to each item in the list, returning another list +That should be:: + elif donor_name.lower() == "exit": -.. code-block:: ipython +This is actually a pretty common typo -- keep an eye out for it when you get strange errors, or something just doesn't seem to be getting triggered. - In [23]: l = [2, 5, 7, 12, 6, 4] - In [24]: def fun(x): - return x*2 + 10 - In [25]: map(fun, l) - Out[25]: [14, 20, 24, 34, 22, 18] +Keyword arguments +----------------- -But if it's a small function, and you only need it once: +When defining a function, you can specify only what you need -- in any order .. code-block:: ipython - In [26]: map(lambda x: x*2 + 10, l) - Out[26]: [14, 20, 24, 34, 22, 18] + In [151]: def fun(x=0, y=0, z=0): + print(x,y,z) + .....: + In [152]: fun(1,2,3) + 1 2 3 + In [153]: fun(1, z=3) + 1 0 3 + In [154]: fun(z=3, y=2) + 0 2 3 -filter ------- +.. nextslide:: -``filter`` "filters" a sequence of objects with a boolean function -- -It keeps only those for which the function is True -- filtering our the rest. -To get only the even numbers: +A Common Idiom: -.. code-block:: ipython +.. code-block:: python - In [27]: l = [2, 5, 7, 12, 6, 4] - In [28]: filter(lambda x: not x%2, l) - Out[28]: [2, 12, 6, 4] + def fun(x, y=None): + if y is None: + do_something_different + go_on_here -If you pass ``None`` to ``filter()``, you get only items that evaluate to true: -.. code-block:: ipython +.. nextslide:: - In [1]: l = [1, 0, 2.3, 0.0, 'text', '', [1,2], [], False, True, None ] +Can set defaults to variables - In [2]: filter(None, l) - Out[2]: [1, 2.3, 'text', [1, 2], True] +.. code-block:: ipython + In [156]: y = 4 + In [157]: def fun(x=y): + print("x is:", x) + .....: + In [158]: fun() + x is: 4 -reduce ------- -``reduce`` "reduces" a sequence of objects to a single object with a function that combines two arguments +.. nextslide:: -To get the sum: +Defaults are evaluated when the function is defined .. code-block:: ipython - In [30]: l = [2, 5, 7, 12, 6, 4] - In [31]: reduce(lambda x,y: x+y, l) - Out[31]: 36 + In [156]: y = 4 + In [157]: def fun(x=y): + print("x is:", x) + .....: + In [158]: fun() + x is: 4 + In [159]: y = 6 + In [160]: fun() + x is: 4 -To get the product: +Function arguments in variables +------------------------------- -.. code-block:: ipython +function arguments are really just - In [32]: reduce(lambda x,y: x*y, l) - Out[32]: 20160 +* a tuple (positional arguments) +* a dict (keyword arguments) -or +.. code-block:: python -.. code-block:: ipython + def f(x, y, w=0, h=0): + print("position: {}, {} -- shape: {}, {}".format(x, y, w, h)) - In [13]: import operator - In [14]: reduce(operator.mul, l) - Out[14]: 20160 + position = (3,4) + size = {'h': 10, 'w': 20} -Comprehensions --------------- + >>> f(*position, **size) + position: 3, 4 -- shape: 20, 10 -Couldn't you do all this with comprehensions? +Function parameters in variables +-------------------------------- -Yes: +You can also pull the parameters out in the function as a tuple and a dict: .. code-block:: ipython - In [33]: [x+2 + 10 for x in l] - Out[33]: [14, 17, 19, 24, 18, 16] - - In [34]: [x for x in l if not x%2] - Out[34]: [2, 12, 6, 4] - - In [6]: l - Out[6]: [1, 0, 2.3, 0.0, 'text', '', [1, 2], [], False, True, None] - In [7]: [i for i in l if i] - Out[7]: [1, 2.3, 'text', [1, 2], True] - -(Except Reduce) - -But Guido thinks almost all uses of reduce are really ``sum()`` - -Functional Programming ----------------------- + def f(*args, **kwargs): + print("the positional arguments are:", args) + print("the keyword arguments are:", kwargs) -Comprehensions and map, filter, reduce are all "functional programming" approaches} + In [389]: f(2, 3, this=5, that=7) + the positional arguments are: (2, 3) + the keyword arguments are: {'this': 5, 'that': 7} -``map, filter`` and ``reduce`` pre-date comprehensions in Python's history +This can be very powerful... -Some people like that syntax better +Passing a dict to str.format() +------------------------------- -And "map-reduce" is a big concept these days for parallel processing of "Big Data" in NoSQL databases. +Now that you know that keyword args are really a dict, +you know how this nifty trick works: -(Hadoop, MongoDB, etc.) +The string ``format()`` method takes keyword arguments: +.. code-block:: ipython -A bit more about lambda ------------------------- + In [24]: "My name is {first} {last}".format(last="Barker", first="Chris") + Out[24]: 'My name is Chris Barker' -It is very useful for specifying sorting as well: +Build a dict of the keys and values: .. code-block:: ipython - In [55]: lst = [("Chris","Barker"), ("Fred", "Jones"), ("Zola", "Adams")] - - In [56]: lst.sort() + In [25]: d = {"last":"Barker", "first":"Chris"} - In [57]: lst - Out[57]: [('Chris', 'Barker'), ('Fred', 'Jones'), ('Zola', 'Adams')] +And pass to ``format()``with ``**`` - In [58]: lst.sort(key=lambda x: x[1]) +.. code-block:: ipython - In [59]: lst - Out[59]: [('Zola', 'Adams'), ('Chris', 'Barker'), ('Fred', 'Jones')] + In [26]: "My name is {first} {last}".format(**d) + Out[26]: 'My name is Chris Barker' -lambda in keyword arguments ----------------------------- +Lab: Keyword Arguments +---------------------- -.. code-block:: ipython +.. rst-class:: medium - In [186]: l = [] - In [187]: for i in range(3): - l.append(lambda x, e=i: x**e) - .....: - In [189]: for f in l: - print(f(3)) - 1 - 3 - 9 + keyword arguments: -Note when the keyword argument is evaluated: this turns out to be very handy! +* Write a function that has four optional parameters (with defaults): -=== -LAB -=== + - fore_color + - back_color + - link_color + - visited_color -Here's an exercise to try out some of this: +* Have it print the colors (use strings for the colors) +* Call it with a couple different parameters set +* Have it pull the parameters out with ``*args, **kwargs`` + - and print those -:ref:`exercise_lambda_magic` -Lightning Talk --------------- -.. rst-class:: medium +Switch/case +----------- -| -| Marc Teale -| +Python does not have a switch/case statement. Why not? -============== -dict as switch -============== +https://www.python.org/dev/peps/pep-3103/ What to use instead of "switch-case"? @@ -695,12 +658,12 @@ A number of languages have a "switch-case" construct:: return "nothing"; }; -How do you spell this in python? +How do you say this in Python? ``if-elif`` chains -------------------- +------------------ -The obvious way to spell it is a chain of ``elif`` statements: +The obvious way to say it is a chain of ``elif`` statements: .. code-block:: python @@ -715,154 +678,59 @@ The obvious way to spell it is a chain of ``elif`` statements: And there is nothing wrong with that, but.... -.. nextslide:: +Dict as switch +-------------- -The ``elif`` chain is neither elegant nor efficient. There are a number of ways to spell it in python -- but one elgant one is to use a dict: +The ``elif`` chain is neither elegant nor efficient. There are a number of ways to say it in python -- but one elegant one is to use a dict: .. code-block:: python arg_dict = {0:"zero", 1:"one", 2: "two"} dict.get(argument, "nothing") -Simple, elegant, and fast. +Simple, elegant and fast. You can do a dispatch table by putting functions as the value. Example: Chris' mailroom2 solution. -============================== -Closures and function Currying -============================== - -Defining specialized functions on the fly - -Closures --------- - -"Closures" and "Currying" are cool CS terms for what is really just defining functions on the fly. - -you can find a "proper" definition here: - -https://en.wikipedia.org/wiki/Closure_(computer_programming) - -but I even have trouble following that. - -So let's go straight to an example: - -.. nextslide:: - -.. code-block:: python - - def counter(start_at=0): - count = [start_at] - def incr(): - count[0] += 1 - return count[0] - return incr -What's going on here? -We have stored the ``start_at`` value in a list. -Then defined a function, ``incr`` that adds one to the value in the list, and returns that value. - -[ Quiz: why is it: ``count = [start_at]``, rather than just ``count=start_at`` ] - -.. nextslide:: - -So what type of object do you get when you call ``counter()``? - -.. code-block:: ipython - - In [37]: c = counter(start_at=5) - - In [38]: type(c) - Out[38]: function - -So we get a function back -- makes sense. The ``def`` defines a function, and that function is what's getting returned. - -Being a function, we can, of course, call it: - -.. code-block:: ipython - - In [39]: c() - Out[39]: 6 - - In [40]: c() - Out[40]: 7 - -Each time is it called, it increments the value by one. - -.. nextslide:: - -But what happens if we call ``counter()`` multiple times? - -.. code-block:: ipython - - In [41]: c1 = counter(5) - - In [42]: c2 = counter(10) - - In [43]: c1() - Out[43]: 6 - - In [44]: c2() - Out[44]: 11 - -So each time ``counter()`` is called, a new function is created. And that function has its own copy of the ``count`` object. This is what makes in a "closure" -- it carries with it the scope in which is was created. - -the returned ``incr`` function is a "curried" function -- a function with some parameters pre-specified. - -``functools.partial`` +Switch with functions --------------------- -The ``functools`` module in the standard library provides utilities for working with functions: - -https://docs.python.org/3.5/library/functools.html - -Creating a curried function turns out to be common enough that the ``functools.partial`` function provides an optimized way to do it: - -What functools.partial does is: - - * Makes a new version of a function with one or more arguments already filled in. - * The new version of a function documents itself. +What would this be like if you used functions instead? Think of the possibilities. -Example: - -.. code-block:: python - - def power(base, exponent): - """returns based raised to the give exponent""" - return base ** exponent - -Simple enough. but what if we wanted a specialized ``square`` and ``cube`` function? +.. code-block:: ipython -We can use ``functools.partial`` to *partially* evaluate the function, giving us a specialized version: + In [11]: def my_zero_func(): + return "I'm zero" + + In [12]: def my_one_func(): + return "I'm one" + + In [13]: switch_func_dict = { + 0: my_zero_func, + 1: my_one_func, + } + + In [14]: switch_func_dict.get(0)() + Out[14]: "I'm zero" -square = partial(power, exponent=2) -cube = partial(power, exponent=3) -=== -LAB -=== +Lab: Functions as objects +------------------------- -Let's use some of this ability to use functions a objects for something useful: +Let's use some of this ability to use functions as objects for something useful: :ref:`exercise_trapezoidal_rule` -Some reading on these topics: +Review framing questions +======================== -http://www.pydanny.com/python-partials-are-fun.html -https://pymotw.com/2/functools/ - -http://www.programiz.com/python-programming/closure - -https://www.clear.rice.edu/comp130/12spring/curry/ - -======== Homework ======== -Finish up the Labs - +Finish the Labs diff --git a/slides_sources/source/session07.rst b/slides_sources/source/session07.rst index ac73377..27af62c 100644 --- a/slides_sources/source/session07.rst +++ b/slides_sources/source/session07.rst @@ -1,42 +1,26 @@ -.. include:: include.rst - -*************************** -Object Oriented Programming -*************************** - -.. rst-class:: medium centered - -.. container:: - - Classes - - Instances - Class and instance attributes - Subclassing +.. include:: include.rst - Overriding methods +Session Seven: Object Oriented Programming +****************************************** -================ -Review/Questions -================ +Announcements +============= -Review of Previous Class ------------------------- +Review & Questions +================== -.. rst-class:: medium - Advanced Argument passing +Homework Review +=============== - Lambda +Code review -- let's take a look. - Functions as Objects -Homework review ---------------- -Homework Questions? +Homework Review: Trapezoid +-------------------------- Did you all get a trapedzoidal rule function working? @@ -44,7 +28,6 @@ Anyone get the "passing through of arguments"? How about the adaptive solutions? - Notes on Floating point ----------------------- @@ -68,65 +51,35 @@ Some notes about FP issues: https://docs.python.org/3.5/tutorial/floatingpoint.html -Code Review ------------ - -Anyone unsatisfied with their solution -- or stuck? - -Let's do a code review! - - -Lightning Talks Today: ------------------------ - -.. rst-class:: medium - - Eric Vegors - - Ian Cote - - Masako Tebbetts -=========================== -Object Oriented Programming -=========================== - -A Core approach to organizing code. - -I'm going to go through this fast. - -So we can get to the actual coding. - - -Object Oriented Programming ---------------------------- - -More about Python implementation than OO design/strengths/weaknesses - -One reason for this: - -Folks can't even agree on what OO "really" means +Lightning Talks +=============== -See: The Quarks of Object-Oriented Development +| |lightning-session07a| +| |lightning-session07b| +| |lightning-session07c| +| |lightning-session07d| +| |lightning-session07e| +| - - Deborah J. Armstrong +Framing +======= -http://agp.hx0.ru/oop/quarks.pdf +In the Beginning there was the GOTO. +And in fact, there wasn't even that. -.. nextslide:: -Is Python a "True" Object-Oriented Language? -(Doesn't support full encapsulation, doesn't *require* -classes, etc...) +Programming Paradigms +===================== -.. nextslide:: +https://en.wikipedia.org/wiki/Programming_paradigm -.. rst-class:: center large - I don't Care! +Software Design +--------------- Good software design is about code re-use, clean separation of concerns, refactorability, testability, etc... @@ -135,19 +88,7 @@ OO can help with all that, but: * It doesn't guarantee it * It can get in the way -.. nextslide:: - -Python is a Dynamic Language - -That clashes with "pure" OO - -Think in terms of what makes sense for your project - -- not any one paradigm of software design. - - -.. nextslide:: - -So what is "object oriented programming"? +What is Object Oriented Programming? | "Objects can be thought of as wrapping their data @@ -159,56 +100,52 @@ So what is "object oriented programming"? http://en.wikipedia.org/wiki/Object-oriented_programming + .. nextslide:: Even simpler: - "Objects are data and the functions that act on them in one place." This is the core of "encapsulation" -In Python: just another namespace. - -.. nextslide:: -The OO buzzwords: - - * data abstraction - * encapsulation - * modularity - * polymorphism - * inheritance +The Dominant Model +------------------ -Python does all of this, though it doesn't enforce it. +OO is the dominant model for the past couple decades, but it is not the only model, and languages such as Python increasingly mix and blend among models. -.. nextslide:: +Object Oriented Concepts +------------------------ -You can do OO in C +.. rst-class:: medium centered -(see the GTK+ project) +.. container:: + Classes -"OO languages" give you some handy tools to make it easier (and safer): + Instances or Objects - * polymorphism (duck typing gives you this anyway) - * inheritance + Encapsulation + Class and instance attributes -.. nextslide:: + Subclassing -OO is the dominant model for the past couple decades + Overriding methods -You will need to use it: + Operator Overloading -- It's a good idea for a lot of problems + Polymorphism -- You'll need to work with OO packages + Dynamic Dispatch -(Even a fair bit of the standard library is Object Oriented) + + -.. nextslide:: Some definitions +Definitions +----------- class A category of objects: particular data and behavior: A "circle" (same as a type in python) @@ -217,7 +154,7 @@ instance A particular object of a class: a specific circle object - The general case of a instance -- really any value (in Python anyway) + The general case of an instance -- really any value (in Python anyway) attribute Something that belongs to an object (or class): generally thought of @@ -226,17 +163,79 @@ attribute method A function that belongs to a class +Python and OO +------------- + +Is Python a "True" Object-Oriented Language? + +What are its strengths and weaknesses vis-a-vis OO? + +It does not support full encapsulation, i.e., it does not require classes, etc. + + .. nextslide:: -.. rst-class:: center +Folks can't even agree on what OO "really" means - Note that in python, functions are first class objects, so a method *is* an attribute +See: The Quarks of Object-Oriented Development + - Deborah J. Armstrong + +http://agp.hx0.ru/oop/quarks.pdf + + +.. nextslide:: + +Think in terms of what makes sense for your project + -- not any one paradigm of software design. + + +.. nextslide:: + +OO Buzzwords + + * data abstraction + * encapsulation + * modularity + * polymorphism + * inheritance + +Python provides for all of this, though it doesn't enforce or require any of it. + +Python's roots +-------------- + +| C +| C with Classes (aka C++) +| Modula2 +| + + +You can do OO in C +------------------ + +Which today is not considered an OO Language. + +See the GTK+ project. + +OO languages give you some handy tools to make it easier (and safer): + + * polymorphism (duck typing gives you this) + * inheritance + +You will need to understand OO +------------------------------ + +- It's a good idea for a lot of problems + +- You'll need to work with OO packages + +(Even a fair bit of the standard library is Object Oriented) -============== Python Classes ============== + .. rst-class:: left The ``class`` statement @@ -255,8 +254,7 @@ Python Classes It is created when the statement is run -- much like ``def`` -Python Classes --------------- +A simple class About the simplest class you can write @@ -275,9 +273,8 @@ About the simplest class you can write >>> p.x 1 -.. nextslide:: - -Basic Structure of a real class: +Basic Structure of a class +-------------------------- .. code-block:: python @@ -298,9 +295,8 @@ Basic Structure of a real class: see: ``Examples/Session07/simple_classes.py`` -.. nextslide:: - The Initializer +--------------- The ``__init__`` special method is called when a new instance of a class is created. @@ -320,8 +316,8 @@ It gets the arguments passed when you call the class object: Point(x, y) -.. nextslide:: - +Self +---- What is this ``self`` thing? @@ -335,7 +331,6 @@ The instance of the class is passed as the first parameter for every method. def a_function(self, x, y): ... - Does this look familiar from C-style procedural programming? @@ -355,7 +350,8 @@ That's where all the instance-specific data is. self.x = x self.y = y -.. nextslide:: +Class Attributes +---------------- Anything assigned in the class scope is a class attribute -- every instance of the class shares the same one. @@ -375,13 +371,11 @@ The class is one namespace, the instance is another. >>> p3.get_color() 'red' - class attributes are accessed with ``self`` also. -.. nextslide:: - -Typical methods: +Typical methods +--------------- .. code-block:: python @@ -399,9 +393,9 @@ Methods take some parameters, manipulate the attributes in ``self``. They may or may not return something useful. -.. nextslide:: -Gotcha! +Arity Gotcha +------------ .. code-block:: python @@ -418,10 +412,16 @@ Huh???? I only gave 2 ``self`` is implicitly passed in for you by python. -(demo of bound vs. unbound methods) +Functions (methods) are First Class +----------------------------------- -LAB ----- +.. rst-class:: center + + Note that in python, functions are first class objects, so a method *is* an attribute + + +LAB: Classes +------------ Let's say you need to render some html... @@ -435,26 +435,12 @@ Details in: :ref:`exercise_html_renderer` -Let's get a start with step 1. in class. - -I'll give you a few minutes to think about it -- then we'll get started as a group. - - -Lightning Talks ----------------- +Do Step 1. in class and then wait to do the rest until after discussing Subclassing and Inheritance. -.. rst-class:: medium -| -| Eric Vegors -| -| Ian Cote -| -| Masako Tebbetts -======================= -Subclassing/Inheritance -======================= +Subclassing & Inheritance +========================= Inheritance ----------- @@ -535,21 +521,11 @@ all the instances will have the new method Here's a program design suggestion: -""" - -Whenever you override a method, the interface of the new method should be the same as the old. It should takethe same parameters, return the same type, and obey the same preconditions and postconditions. +Whenever you override a method, the interface of the new method should be the same as the old. It should take the same parameters, return the same type, and obey the same preconditions and postconditions. If you obey this rule, you will find that any function designed to work with an instance of a superclass, like a Deck, will also work with instances of subclasses like a Hand or PokerHand. If you violate this rule, your code will collapse like (sorry) a house of cards. -""" - -| -| [ThinkPython 18.10] -| -| ( Demo of class vs. instance attributes ) - -=================== More on Subclassing =================== @@ -577,6 +553,7 @@ exception to: "don't change the method signature" rule. More subclassing ---------------- + You can also call the superclass' other methods: .. code-block:: python @@ -595,7 +572,6 @@ You can also call the superclass' other methods: There is nothing special about ``__init__`` except that it gets called automatically when you instantiate an instance. - When to Subclass ---------------- @@ -621,7 +597,6 @@ or You only want to subclass list if your class could be used anywhere a list can be used. - Attribute resolution order -------------------------- @@ -644,7 +619,6 @@ https://www.python.org/download/releases/2.3/mro/ http://python-history.blogspot.com/2010/06/method-resolution-order.html - What are Python classes, really? -------------------------------- @@ -663,7 +637,6 @@ Python classes are: That's about it -- really! - Type-Based dispatch ------------------- @@ -676,61 +649,15 @@ You'll see code that looks like this: else: Do_something_else - -Usually better to use "duck typing" (polymorphism) - -But when it's called for: +When it's called for: * ``isinstance()`` * ``issubclass()`` -.. nextslide:: - -GvR: "Five Minute Multi- methods in Python": - -http://www.artima.com/weblogs/viewpost.jsp?thread=101605 - -https://www.python.org/download/releases/2.3/mro/ - -http://python-history.blogspot.com/2010/06/method-resolution-order.html - - -Wrap Up -------- - -Thinking OO in Python: - -Think about what makes sense for your code: - -* Code re-use -* Clean APIs -* ... - -Don't be a slave to what OO is *supposed* to look like. - -Let OO work for you, not *create* work for you - -.. nextslide:: - -OO in Python: - -The Art of Subclassing: *Raymond Hettinger* - -http://pyvideo.org/video/879/the-art-of-subclassing - -"classes are for code re-use -- not creating taxonomies" - -Stop Writing Classes: *Jack Diederich* - -http://pyvideo.org/video/880/stop-writing-classes - -"If your class has only two methods -- and one of them is ``__init__`` --- you don't need a class" -=== -LAB -=== +LAB: Subclassing & Inheritance +------------------------------ .. rst-class:: left medium @@ -747,162 +674,87 @@ Now we have a base class, and we can: These are the core OO approaches +Review framing questions +======================== -=================== -More on Subclassing -=================== - -.. rst-class:: left - - This is a great talk (yes, I'm repeating): - - The Art of Subclassing: *Raymond Hettinger* - - http://pyvideo.org/video/879/the-art-of-subclassing - - If you haven't watched it, It's well worth your time - -What's a Subclass For? ----------------------- - -The most salient points from that video are as follows: - -* **Subclassing is not for Specialization** - -* **Subclassing is for Reusing Code** - -* **Bear in mind that the subclass is in charge** - - -Multiple Inheritance --------------------- - -Multiple inheritance: Inheriting from more than one class - -Simply provide more than one parent. - -.. code-block:: python - - class Combined(Super1, Super2, Super3): - def __init__(self, something, something else): - # some custom initialization here. - Super1.__init__(self, ......) - Super2.__init__(self, ......) - Super3.__init__(self, ......) - # possibly more custom initialization - -(calls to the super class ``__init__`` are optional -- case dependent) - -.. nextslide:: Method Resolution Order - -.. code-block:: python - - class Combined(Super1, Super2, Super3) - -Attributes are located bottom-to-top, left-to-right - -* Is it an instance attribute ? -* Is it a class attribute ? -* Is it a superclass attribute ? - - - Is it an attribute of the left-most superclass? - - Is it an attribute of the next superclass? - - and so on up the hierarchy... - -* Is it a super-superclass attribute ? -* ... also left to right ... - -http://python-history.blogspot.com/2010/06/method-resolution-order.html - -.. nextslide:: Mix-ins - -So why would you want to do this? One reason: *mixins* - -Provides an subset of expected functionality in a re-usable package. +Think about OO in Python: -Huh? this is why -- - -Hierarchies are not always simple: - -* Animal +Think about what makes sense for your code: - * Mammal +* Code re-use +* Clean APIs +* ... - * GiveBirth() +Don't be a slave to what OO is *supposed* to look like. - * Bird +Let OO work for you, not *create* work for you - * LayEggs() -Where do you put a Platypus? +Homework +======== -Real World Example: `FloatCanvas`_ +Let's say you need to render some html. -.. _FloatCanvas: https://github.com/svn2github/wxPython/blob/master/3rdParty/FloatCanvas/floatcanvas/FloatCanvas.py#L485 +The goal is to build a set of classes that render an html +page. +We'll start with a single class, then add some sub-classes +to specialize the behavior -``super()`` ------------ +:ref:`exercise_html_renderer` -``super()``: use it to call a superclass method, rather than explicitly calling -the unbound method on the superclass. -instead of: +Readings +======== -.. code-block:: python - class A(B): - def __init__(self, *args, **kwargs) - B.__init__(self, *argw, **kwargs) - ... +The Art of Subclassing +---------------------- -You can do: +The Art of Subclassing by *Raymond Hettinger* -.. code-block:: python +http://pyvideo.org/video/879/the-art-of-subclassing - class A(B): - def __init__(self, *args, **kwargs) - super().__init__(*argw, **kwargs) - ... +The most salient points from that video are as follows: -.. nextslide:: Caveats +* **Subclassing is not for Specialization** -Caution: There are some subtle differences with multiple inheritance. +* **Classes and subclassing are for code re-use -- not creating taxonomies** -You can use explicit calling to ensure that the 'right' method is called. +* **Bear in mind that the subclass is in charge** -.. rst-class:: medium - **Background** +Stop Writing Classes +-------------------- -Two seminal articles about ``super()``: +Stop Writing Classes by *Jack Diederich* -"Super Considered Harmful" -- James Knight +http://pyvideo.org/video/880/stop-writing-classes -https://fuhm.net/super-harmful/ +"If your class has only two methods -- and one of them is ``__init__`` +-- you don't need a class" -"super() considered super!" -- Raymond Hettinger -http://rhettinger.wordpress.com/2011/05/26/super-considered-super/ +Python Class Toolkit +-------------------- -(Both worth reading....) +Python Class Toolkit by *Raymond Hettinger* -======== -Homework -======== +https://youtu.be/HTLu2DFOdTg -Complete your html renderer. +https://speakerdeck.com/pyconslides/pythons-class-development-toolkit-by-raymond-hettinger -Watch those videos: -Python class toolkit: *Raymond Hettinger* -- https://youtu.be/HTLu2DFOdTg -https://speakerdeck.com/pyconslides/pythons-class-development-toolkit-by-raymond-hettinger +Multiple Inheritance and the Diamond Problem +-------------------------------------------- -The Art of Subclassing: *Raymond Hettinger* -- http://pyvideo.org/video/879/the-art-of-subclassing +https://en.wikipedia.org/wiki/Multiple_inheritance -Stop Writing Classes: *Jack Diederich* -- http://pyvideo.org/video/880/stop-writing-classes +https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem -Read up on super() +Method Resolution Order +https://www.python.org/download/releases/2.3/mro/ +http://python-history.blogspot.com/2010/06/method-resolution-order.html diff --git a/slides_sources/source/session08.rst b/slides_sources/source/session08.rst index 66eec31..1b43fc0 100644 --- a/slides_sources/source/session08.rst +++ b/slides_sources/source/session08.rst @@ -1,60 +1,28 @@ -.. include:: include.rst - -************************************************************************** -Session Eight: More OO: Properties, Special methods. -************************************************************************** - - -================ -Review/Questions -================ - -Review of Previous Class ------------------------- - -* Basic OO Concepts - * Classes - * class vs. instance attributes - * subclassing - * overriding methods / attributes +.. include:: include.rst -Lightning Talks Today: ------------------------ -.. rst-class:: medium +Session Eight: Object Oriented Programming 2 +******************************************** - Robert Ryan Leslie +Object Oriented Programming continued... - Ryan Morin +Announcements +============= -Personal Project ------------------ -The bulk of the homework for the rest of the class will be a personal project: +Review & Questions +================== -* It can be for fun, or something you need for your job. -* It should be large enough to take a few weeks homework time to do. -* **It should demostrate that you can do something useful with python.** -* It should follow PEP8 (https://www.python.org/dev/peps/pep-0008) -* It should have unit tests! -* Ideally, it will be in version control (gitHub) -* I don't require any specific python features (i.e. classes): use - what is appropriate for your project -* Due the Friday after the last class (December 11) +Homework +======== -| -| By next week, send me a project proposal: short and sweet. -| +Code review -- let's take a look. -Homework review ---------------- -* html renderer -* Test-driven development Homework Notes: --------------- @@ -78,683 +46,404 @@ empty, then the loop is a do-nothing operation: * anyone stuck that wants to work through your code? -========== -Properties -========== - -.. rst-class:: left -.. container:: - - One of the strengths of Python is lack of clutter. - - Attributes are simple and concise: - - .. code-block:: ipython - - In [5]: class C: - def __init__(self): - self.x = 5 - In [6]: c = C() - In [7]: c.x - Out[7]: 5 - In [8]: c.x = 8 - In [9]: c.x - Out[9]: 8 - - -Getter and Setters? -------------------- - -But what if you need to add behavior later? - -.. rst-class:: build - -* do some calculation -* check data validity -* keep things in sync - - -.. nextslide:: - -.. code-block:: ipython - - In [5]: class C: - ...: def __init__(self): - ...: self.x = 5 - ...: def get_x(self): - ...: return self.x - ...: def set_x(self, x): - ...: self.x = x - ...: - In [6]: c = C() - In [7]: c.get_x() - Out[7]: 5 - In [8]: c.set_x(8) - In [9]: c.get_x() - Out[9]: 8 - - This is ugly and verbose -- `Java`_? - -.. _Java: http://dirtsimple.org/2004/12/python-is-not-java.html - -properties ------------ - -.. code-block:: ipython +Lightning Talks +=============== - class C: - _x = None - @property - def x(self): - return self._x - @x.setter - def x(self, value): - self._x = value +| |lightning-session08a| +| |lightning-session08b| +| |lightning-session08c| +| |lightning-session08d| +| |lightning-session08e| +| - In [28]: c = C() - In [30]: c.x = 5 - In [31]: print(c.x) - 5 -Now the interface is like simple attribute access! +Framing +======= -.. nextslide:: -What's up with the "@" symbols? +Multiple Inheritance +==================== -Those are "decorations" it's a syntax for wrapping functions up with something special. +Multiple inheritance: Inheriting from more than one class. -We'll cover that in detail in a couple weeks, but for now -- just copy the syntax. +Simply provide more than one parent. .. code-block:: python - @property - def x(self): + class Combined(Parent1, Parent2, Parent3): + def __init__(self, something, something else): + # some custom initialization here. + Parent1.__init__(self, ......) + Parent2.__init__(self, ......) + Parent3.__init__(self, ......) + # possibly more custom initialization -means: make a property called x with this as the "getter". +Calls to the parent class ``__init__`` are optional and case dependent. -.. code-block:: python - @x.setter - def x(self, value): -means: make the "setter" of the 'x' property this new function +Purpose +------- -"Read Only" Attributes ----------------------- +What was the purpose behind inheritance? -You do not need to define a setter. If you don't, you get a "read only" attribute: +Code reuse. -.. code-block:: ipython - In [11]: class D(): - ....: def __init__(self, x=5): - ....: self._x = 5 - ....: @property - ....: def getx(self): - ....: """I am read only""" - ....: return self._x - ....: - In [12]: d = D() - In [13]: d.x - Out[13]: 5 - In [14]: d.x = 6 - --------------------------------------------------------------------------- - AttributeError Traceback (most recent call last) - in () - ----> 1 d.x = 6 - AttributeError: can't set attribute +What is the purpose behind multiple inheritance? -Deleters ---------- +Code reuse. -If you want to do something special when a property is deleted, you can define -a deleter is well: -.. code-block:: ipython +What wasn't the purpose of inheritance? - In [11]: class D(): - ....: def __init__(self, x=5): - ....: self._x = 5 - ....: @property - ....: def x(self): - ....: return self._x - ....: @x.deleter - ....: def x(self): - ....: del self._x +Building massive class hierarchies for their own sake. -If you leave this out, the property can't be deleted, which is usually -what you want. -.. rst-class:: centered +What isn't the purpose of multiple inheritance? -[demo: :download:`properties_example.py <../../Examples/Session08/properties_example.py>`] +Building massive class hierarchies for their own sake. -=== -LAB -=== +Python's Multiple Inheritance Model +----------------------------------- -Let's use some of this to build a nice class to represent a Circle. +Cooperative Multiple Inheritance -For now, Let's do steps 1-4 of: +Emphasis on cooperative! -:ref:`exercise_circle_class` +* Play by the rules and everybody benefits (parents, descendants). +* Play by the rules and nobody gets hurt (yourself, mostly). +* We're all adults here. -Lightning talks: ------------------ +What could go wrong? -.. rst-class:: medium - Robert Ryan Leslie - Ryan Morin +The Diamond Problem +------------------- +With Python "new style" classes everything is descended from 'object'. Thus, the moment you invoke multiple inheritance you have the diamond problem. -======================== -Static and Class Methods -======================== +https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem -.. rst-class:: left build -.. container:: - You've seen how methods of a class are *bound* to an instance when it is - created. - And you've seen how the argument ``self`` is then automatically passed to - the method when it is called. +``super()`` +----------- - And you've seen how you can call *unbound* methods on a class object so - long as you pass an instance of that class as the first argument. +``super()``: use it to call a superclass method, rather than explicitly calling the unbound method on the superclass. - | +instead of: - .. rst-class:: centered +.. code-block:: python - **But what if you don't want or need an instance?** + class A(B): + def __init__(self, *args, **kwargs) + B.__init__(self, *argw, **kwargs) + ... +You can do: -Static Methods --------------- +.. code-block:: python -A *static method* is a method that doesn't get self: + class A(B): + def __init__(self, *args, **kwargs) + super().__init__(*argw, **kwargs) + ... -.. code-block:: ipython +MRO: Method Resolution Order +---------------------------- - In [36]: class StaticAdder: +.. code-block:: python - ....: @staticmethod - ....: def add(a, b): - ....: return a + b - ....: + class Combined(Super1, Super2, Super3) - In [37]: StaticAdder.add(3, 6) - Out[37]: 9 +Attributes are located bottom-to-top, left-to-right -.. rst-class:: centered +* Is it an instance attribute ? +* Is it a class attribute ? +* Is it a superclass attribute ? -[demo: :download:`static_method.py <../../Examples/Session08/static_method.py>`] + - Is it an attribute of the left-most superclass? + - Is it an attribute of the next superclass? + - and so on up the hierarchy... +* Is it a super-superclass attribute ? +* ... also left to right ... -.. nextslide:: Why? +http://python-history.blogspot.com/2010/06/method-resolution-order.html -.. rst-class:: build -.. container:: +Super's Superpowers +------------------- - Where are static methods useful? +It works out -- dynamically at runtime -- which classes are in the delegation order. - Usually they aren't +Do not be afraid. And be very afraid. - 99% of the time, it's better just to write a module-level function - An example from the Standard Library (tarfile.py): - .. code-block:: python +Dependency Injection +-------------------- - class TarInfo: - # ... - @staticmethod - def _create_payload(payload): - """Return the string payload filled with zero bytes - up to the next 512 byte border. - """ - blocks, remainder = divmod(len(payload), BLOCKSIZE) - if remainder > 0: - payload += (BLOCKSIZE - remainder) * NUL - return payload +Super() is the right way to do dependency injection. +https://en.wikipedia.org/wiki/Dependency_injection -Class Methods -------------- +Compare with Monkey Patching as done in other languages. -A class method gets the class object, rather than an instance, as the first -argument +https://en.wikipedia.org/wiki/Monkey_patch -.. code-block:: ipython - In [41]: class Classy: - ....: x = 2 - ....: @classmethod - ....: def a_class_method(cls, y): - ....: print("in a class method: ", cls) - ....: return y ** cls.x - ....: - In [42]: Classy.a_class_method(4) - in a class method: - Out[42]: 16 -.. rst-class:: centered +Argument Passing +---------------- -[demo: :download:`class_method.py <../../Examples/Session08/class_method.py>`] +Remember that super does not only delegate to your superclass, it delegates to any class in the MRO. +Therefore you must be prepared to call any other class's method in the hierarchy and be prepared to be called from any other class's method. -Why? ----- +The general rule is to pass all arguments you received on to the super function. If classes can take differing arguments, accept *args and **kwargs. -.. rst-class:: build -.. container:: - Unlike static methods, class methods are quite common. +Two seminal articles +-------------------- - They have the advantage of being friendly to subclassing. +"Super Considered Harmful" -- James Knight - Consider this: +https://fuhm.net/super-harmful/ - .. code-block:: ipython +"Super() considered super!" -- Raymond Hettinger - In [44]: class SubClassy(Classy): - ....: x = 3 - ....: +http://rhettinger.wordpress.com/2011/05/26/super-considered-super/ - In [45]: SubClassy.a_class_method(4) - in a class method: - Out[45]: 64 +(Both worth reading....) -Alternate Constructors ------------------------ +Composition +=========== -Because of this friendliness to subclassing, class methods are often used to -build alternate constructors. -Consider the case of wanting to build a dictionary with a given iterable of -keys: -.. code-block:: ipython +Composition vs Inheritance +-------------------------- - In [57]: d = dict([1,2,3]) - --------------------------------------------------------------------------- - TypeError Traceback (most recent call last) - in () - ----> 1 d = dict([1,2,3]) +Composition does virtually the same thing as multiple inheritance, in the sense that it allows your class to reuse the functionality of other classes. + +With inheritance you are thinking in terms of 'is-a' relationships. - TypeError: cannot convert dictionary update sequence element #0 to a sequence +With composition you are thinking in terms of 'has-a' relationships. +Composition is more explicit than inheritance and it avoids the complexity of super(). It of course also gains nothing from super()'s superpowers. -.. nextslide:: ``dict.fromkeys()`` -The stock constructor for a dictionary won't work this way. So the dict object -implements an alternate constructor that *can*. +An example +---------- .. code-block:: python - @classmethod - def fromkeys(cls, iterable, value=None): - '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. - If not specified, the value defaults to None. - ''' - self = cls() - for key in iterable: - self[key] = value - return self + class Other(object): -(this is actually from the OrderedDict implementation in ``collections.py``) + def __init__(self): + print("Other __init__()") -See also datetime.datetime.now(), etc.... -.. nextslide:: Curious? + class MyComposedClass(object): + """ I inherit from object """ -Properties, Static Methods and Class Methods are powerful features of Python's -OO model. + def __init__(self): + self.other = Other() # I contain Other() -They are implemented using an underlying structure called *descriptors* +Remember: 'has-a' not 'is-a' -`Here is a low level look`_ at how the descriptor protocol works. -The cool part is that this mechanism is available to you, the programmer, as -well. -.. _Here is a low level look: https://docs.python.org/2/howto/descriptor.html +Properties +========== +https://en.wikipedia.org/wiki/Property_%28programming%29#Python -For the Circle Lab: use a class method to make an alternate constructor that takes -the diameter instead. -=============== -Special Methods -=============== +Attributes are clear and concise +-------------------------------- .. rst-class:: left .. container:: - Special methods (also called *magic* methods) are the secret sauce to Python's Duck typing. - - Defining the appropriate special methods in your classes is how you make your class act like standard classes. - -What's in a Name? ------------------ - -We've seen at least one special method so far:: - - __init__ - -It's all in the double underscores... - -Pronounced "dunder" (or "under-under") - -try: ``dir(2)`` or ``dir(list)`` - -.. nextslide:: Generally Useful Special Methods + One of the strengths of Python is lack of clutter. -Most classes should at least have these special methods: + .. code-block:: ipython -``object.__str__``: - Called by the str() built-in function and by the print function to compute - the *informal* string representation of an object. + In [5]: class C: + def __init__(self): + self.x = 5 + In [6]: c = C() + In [7]: c.x + Out[7]: 5 + In [8]: c.x = 8 + In [9]: c.x + Out[9]: 8 -``object.__repr__``: - Called by the repr() built-in function to compute the *official* string representation of an object. - (ideally: ``eval( repr(something) ) == something``) +And we want to maintain this clarity. -(demo) +Getter and Setters +------------------ -Protocols ----------- +But what if you need to add behavior later? .. rst-class:: build -.. container:: - - The set of special methods needed to emulate a particular type of Python object is called a *protocol*. - - Your classes can "become" like Python built-in classes by implementing the - methods in a given protocol. - - Remember, these are more *guidelines* than laws. Implement what you need. - - -.. nextslide:: The Numerics Protocol - -Do you want your class to behave like a number? Implement these methods: - -.. code-block:: python - - object.__add__(self, other) - object.__sub__(self, other) - object.__mul__(self, other) - object.__floordiv__(self, other) - object.__mod__(self, other) - object.__divmod__(self, other) - object.__pow__(self, other[, modulo]) - object.__lshift__(self, other) - object.__rshift__(self, other) - object.__and__(self, other) - object.__xor__(self, other) - object.__or__(self, other) - -.. nextslide:: The Container Protocol - -Want to make a container type? Here's what you need: - -.. code-block:: python - - object.__len__(self) - object.__getitem__(self, key) - object.__setitem__(self, key, value) - object.__delitem__(self, key) - object.__iter__(self) - object.__reversed__(self) - object.__contains__(self, item) - object.__getslice__(self, i, j) - object.__setslice__(self, i, j, sequence) - object.__delslice__(self, i, j) - - -.. nextslide:: An Example - -Each of these methods supports a common Python operation. - -For example, to make '+' work with a sequence type in a vector-like fashion, -implement ``__add__``: - -.. code-block:: python - - def __add__(self, v): - """return the element-wise vector sum of self and v - """ - assert len(self) == len(v) - return vector([x1 + x2 for x1, x2 in zip(self, v)]) - -.. rst-class:: centered - -[a more complete example may be seen :download:`here <../../Examples/Session08/vector.py>`] - - -.. nextslide:: Summary - -Use special methods when you want your class to act like a "standard" class in -some way. - -Look up the special methods you need and define them. - -There's more to read about the details of implementing these methods: - -* https://docs.python.org/3.5/reference/datamodel.html#special-method-names -* http://www.rafekettler.com/magicmethods.html - -=== -LAB -=== - -Let's complete our nifty Circle class: -Steps 5-8 of: - -:ref:`exercise_circle_class` - - -========================= -Emulating Standard types -========================= - -.. rst-class:: medium - - Making your classes behave like the built-ins - - -Callable classes ------------------ - -We've been using functions a lot: - -.. code-block:: python - - def my_fun(something): - do_something - ... - return something - -And then we can call it: - -.. code-block:: python +* do some calculation +* check data validity +* keep things in sync - result = my_fun(some_arguments) .. nextslide:: -But what if we need to store some data to know how to evaluate that function? - -Example: a function that computes a quadratic function: - -.. math:: - - y = a x^2 + bx + c - -You could pass in a, b and c each time: - -.. code-block:: python - - def quadratic(x, a, b, c): - return a * x**2 + b * x + c +.. code-block:: ipython -But what if you are using the same a, b, and c numerous times? + In [5]: class C: + ...: def __init__(self): + ...: self.x = 5 + ...: def get_x(self): + ...: return self.x + ...: def set_x(self, x): + ...: self.x = x + ...: + In [6]: c = C() + In [7]: c.get_x() + Out[7]: 5 + In [8]: c.set_x(8) + In [9]: c.get_x() + Out[9]: 8 -Or what if you need to pass this in to something -(like map) that requires a function that takes a single argument? -"Callables" ------------ +This is verbose -- `Java`_? -Various places in python expect a "callable" -- something that you can -call like a function: +.. _Java: http://dirtsimple.org/2004/12/python-is-not-java.html -.. code-block:: python +Properties +---------- - a_result = something(some_arguments) +.. code-block:: ipython -"something" in this case is often a function, but can be anything else -that is "callable". + class C: + _x = None + @property + def x(self): + return self._x + @x.setter + def x(self, value): + self._x = value -What have we been introduced to recently that is "callable", but not a -function object? + In [28]: c = C() + In [30]: c.x = 5 + In [31]: print(c.x) + 5 -Custom callable objects ------------------------- +Now the interface is like simple attribute access! -The trick is one of Python's "magic methods" +Decorators +---------- -.. code-block:: python +What's up with the "@" symbols? - __call__(*args, **kwargs) +Those are "decorations" it is a syntax for wrapping functions up with something special. -If you define a ``__call__`` method in your class, it will be used when -code "calls" an instance of your class: +We will cover decorators in detail in another part of the program, but for now just copy the syntax. .. code-block:: python - class Callable: - def __init__(self, .....) - some_initilization - def __call__(self, some_parameters) + @property + def x(self): -Then you can do: +means: make a property called x with this as the "getter". .. code-block:: python - callable_instance = Callable(some_arguments) - - result = callable_instance(some_arguments) - - -Writing your own sequence type -------------------------------- - -Python has a handful of nifty sequence types built in: - - * lists - * tuples - * strings - * ... - -But what if you need a sequence that isn't built in? - -A Sparse array --------------- - -Example: Sparse Array - -Sometimes we have data sets that are "sparse" -- i.e. most of the values are zero. - -So you may not want to store a huge bunch of zeros. - -But you do want the array to look like a regular old sequence. - -So how do you do that? - -The Sequence protocol ----------------------- - -You can make your class look like a regular python sequence by defining -the set of special methods you need: - -https://docs.python.org/3/reference/datamodel.html#emulating-container-types - -and + @x.setter + def x(self, value): -http://www.rafekettler.com/magicmethods.html#sequence +means: make the "setter" of the 'x' property this new function -The key ones are: +Read Only Attributes +-------------------- -+-------------------+-----------------------+ -| ``__len__`` | for ``len(sequence)`` | -+-------------------+-----------------------+ -| ``__getitem__`` | for ``x = seq[i]`` | -+-------------------+-----------------------+ -| ``__setitem__`` | for ``seq[i] = x`` | -+-------------------+-----------------------+ -| ``__delitem__`` | for ``del seq[i]`` | -+-------------------+-----------------------+ -| ``__contains__`` | for ``x in seq`` | -+-------------------+-----------------------+ +You do not need to define a setter. If you don't, you get a "read only" attribute: -==== -LAB -==== +.. code-block:: ipython -.. rst-class:: medium + In [11]: class D(): + ....: def __init__(self, x=5): + ....: self._x = 5 + ....: @property + ....: def getx(self): + ....: """I am read only""" + ....: return self._x + ....: + In [12]: d = D() + In [13]: d.x + Out[13]: 5 + In [14]: d.x = 6 + --------------------------------------------------------------------------- + AttributeError Traceback (most recent call last) + in () + ----> 1 d.x = 6 + AttributeError: can't set attribute - Let's do the previous motivating examples. +Deleters +--------- -Callables: ------------ +If you want to do something special when a property is deleted, you can define a deleter as well: -Write a class for a quadratic equation. +.. code-block:: ipython -* The initializer for that class should take the parameters: ``a, b, c`` + In [11]: class D(): + ....: def __init__(self, x=5): + ....: self._x = 5 + ....: @property + ....: def x(self): + ....: return self._x + ....: @x.deleter + ....: def x(self): + ....: del self._x -* It should store those parameters as attributes. +If you leave this out, the property can't be deleted, which is usually +what you want. -* The resulting instance should evaluate the function when called, and return the result: +.. rst-class:: centered +[demo: :download:`properties_example.py <../../Examples/Session08/properties_example.py>`] -.. code-block:: python +LAB: Properties, class methods, special methods +=============================================== - my_quad = Quadratic(a=2, b=3, c=1) +Let's use some of this to build a nice class to represent a Circle. - my_quad(0) +For now, Let's do steps 1-4 of: -Sparse Array: -------------- +:ref:`exercise_circle_class` -Write a class for a sparse array: -:ref:`exercise_sparse_array` +Review framing questions +======================== -======== Homework ======== -.. rst-class:: left +Complete the Circle class - Complete the Circle class +Complete the Sparse Array class - Complete the Sparse Array class +Refactor mailroom to use classes. - Decide what you are going to do for your project, and send me a simple proposal. Get started if you can. - Good book: - Python 3 Object Oriented Programming: *Dusty Phillips* +Readings +======== + +Python 3 Object Oriented Programming: *Dusty Phillips* - (Dusty is a local boy and co-founder of PuPPy) +(Dusty is a local boy and co-founder of PuPPy) diff --git a/slides_sources/source/session09.rst b/slides_sources/source/session09.rst index 550ff50..e72d248 100644 --- a/slides_sources/source/session09.rst +++ b/slides_sources/source/session09.rst @@ -1,418 +1,551 @@ + + .. include:: include.rst -************************************************** -Session Nine: Iterators, Iterables, and Generators -************************************************** +Session Nine: Object Oriented Programming 3 +******************************************* -.. rst-class:: large centered -The tools of Pythonicity +Announcements +============= -====================== -Lightning Talks Today: -====================== +Lightning talk schedule -.. rst-class:: medium +Please Upload your lightning talk materials to your student directory. - Erica Winberry +PYCON +----- - Robert Jenkins +https://us.pycon.org/2016/ - Kathleen Devlin +This class qualifies any of us to go under the student rate. -================ -Review/Questions -================ +Review & Questions +================== -Review of complete sparse array class +Questions emailed in over the week. -========================= -Iterators and Generators -========================= +Homework +======== -.. rst-class:: medium +Code review -- let's take a look. - What goes on in those for loops? -Iterators and Iterables ------------------------ -Iteration is one of the main reasons Python code is so readable: +Lightning Talks +=============== -.. code-block:: python +| |lightning-session09a| +| |lightning-session09b| +| |lightning-session09c| +| |lightning-session09d| +| |lightning-session09e| +| |lightning-session09f| +| |lightning-session09g| +| |lightning-session09h| +| |lightning-session09i| +| |lightning-session09j| +| - for x in just_about_anything: - do_stuff(x) +Framing +======= -An iterable is anything that can be looped over sequentially, so it does not have to be -a "sequence": list, tuple, etc. For example, a string is iterable. -An iterator is an iterable that remembers state. All sequences are iterable, but -not all sequences are iterators. To make a sequence an iterator, you can call it with iter: +Static and Class Methods +======================== -.. code-block:: python +.. rst-class:: left build +.. container:: - my_iter = iter(my_sequence) + You've seen how methods of a class are *bound* to an instance when it is + created. -Iterator Types: + And you've seen how the argument ``self`` is then automatically passed to + the method when it is called. -https://docs.python.org/3/library/stdtypes.html#iterator-types + And you've seen how you can call *unbound* methods on a class object so + long as you pass an instance of that class as the first argument. -Iterables ---------- + | -To make an object iterable, you simply have to implement the __getitem__ method. + .. rst-class:: centered -.. code-block:: python + **But what if you don't want or need an instance?** - class T: - def __getitem__(self, position): - if position > 5: - raise IndexError - return position +Static Methods +-------------- -Demo +A *static method* is a method that doesn't get self: +.. code-block:: ipython -``iter()`` ------------ + In [36]: class StaticAdder: -How do you get the iterator object from an "iterable"? + ....: @staticmethod + ....: def add(a, b): + ....: return a + b + ....: -The iter function will make any iterable an iterator. It first looks for the __iter__ -method, and if none is found, uses get_item to create the iterator. + In [37]: StaticAdder.add(3, 6) + Out[37]: 9 -The ``iter()`` function: +.. rst-class:: centered -.. code-block:: ipython +[demo: :download:`static_method.py <../../Examples/Session08/static_method.py>`] - In [20]: iter([2,3,4]) - Out[20]: - In [21]: iter("a string") - Out[21]: +.. nextslide:: Why? - In [22]: iter( ('a', 'tuple') ) - Out[22]: +.. rst-class:: build +.. container:: + Where are static methods useful? -List as an Iterator: --------------------- + Usually they aren't. It is often better just to write a module-level function. + + An example from the Standard Library (tarfile.py): + + .. code-block:: python + + class TarInfo: + # ... + @staticmethod + def _create_payload(payload): + """Return the string payload filled with zero bytes + up to the next 512 byte border. + """ + blocks, remainder = divmod(len(payload), BLOCKSIZE) + if remainder > 0: + payload += (BLOCKSIZE - remainder) * NUL + return payload + +Class Methods +------------- + +A class method gets the class object, rather than an instance, as the first +argument .. code-block:: ipython - In [10]: a_list = [1,2,3] + In [41]: class Classy: + ....: x = 2 + ....: @classmethod + ....: def a_class_method(cls, y): + ....: print("in a class method: ", cls) + ....: return y ** cls.x + ....: + In [42]: Classy.a_class_method(4) + in a class method: + Out[42]: 16 - In [11]: list_iter = iter(a_list) +.. rst-class:: centered - In [12]: next(list_iter) - Out[12]: 1 +[demo: :download:`class_method.py <../../Examples/Session08/class_method.py>`] - In [13]: next(list_iter) - Out[13]: 2 - In [14]: next(list_iter) - Out[14]: 3 +Why? +---- - In [15]: next(list_iter) - -------------------------------------------------- - StopIteration Traceback (most recent call last) - in () - ----> 1 next(list_iter) - StopIteration: +.. rst-class:: build +.. container:: + Unlike static methods, class methods are quite common. -The Iterator Protocol ----------------------- + They have the advantage of being friendly to subclassing. -The main thing that differentiates an iterator from an iterable (sequence) is that an iterator saves state. + Consider this: -An iterator must have the following methods: + .. code-block:: ipython -.. code-block:: python + In [44]: class SubClassy(Classy): + ....: x = 3 + ....: - an_iterator.__iter__() + In [45]: SubClassy.a_class_method(4) + in a class method: + Out[45]: 64 -Returns the iterator object itself. +Alternate Constructors +----------------------- -.. code-block:: python +Because of this friendliness to subclassing, class methods are often used to +build alternate constructors. + +Consider the case of wanting to build a dictionary with a given iterable of +keys: + +.. code-block:: ipython - an_iterator.__next__() + In [57]: d = dict([1,2,3]) + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 d = dict([1,2,3]) -Returns the next item from the container. If there are no further items, -raises the ``StopIteration`` exception. + TypeError: cannot convert dictionary update sequence element #0 to a sequence -Making an Iterator -------------------- +.. nextslide:: ``dict.fromkeys()`` -A simple version of ``range()`` +The stock constructor for a dictionary won't work this way. So the dict object +implements an alternate constructor that *can*. .. code-block:: python - class IterateMe_1: - def __init__(self, stop=5): - self.current = 0 - self.stop = stop - def __iter__(self): - return self - def __next__(self): - if self.current < self.stop: - self.current += 1 - return self.current - else: - raise StopIteration - -(demo: :download:`iterator_1.py <../../Examples/Session09/iterator_1.py>`) - -What does ``for`` do? ----------------------- + @classmethod + def fromkeys(cls, iterable, value=None): + '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. + If not specified, the value defaults to None. + ''' + self = cls() + for key in iterable: + self[key] = value + return self -Now that we know the iterator protocol, we can write something like a for loop: +(this is actually from the OrderedDict implementation in ``collections.py``) +See also datetime.datetime.now(), etc.... -:download:`my_for.py <../../Examples/Session09/my_for.py>` +.. nextslide:: Curious? -.. code-block:: python +Properties, Static Methods and Class Methods are powerful features of Python's +OO model. - def my_for(an_iterable, func): - """ - Emulation of a for loop. +They are implemented using an underlying structure called *descriptors* - func() will be called with each item in an_iterable - """ - # equiv of "for i in l:" - iterator = iter(an_iterable) - while True: - try: - i = next(iterator) - except StopIteration: - break - func(i) +`Here is a low level look`_ at how the descriptor protocol works. +The cool part is that this mechanism is available to you, the programmer, as +well. -Itertools ---------- +.. _Here is a low level look: https://docs.python.org/2/howto/descriptor.html -``itertools`` is a collection of utilities that make it easy to -build an iterator that iterates over sequences in various common ways -http://docs.python.org/3/library/itertools.html +For the Circle Lab: use a class method to make an alternate constructor that takes +the diameter instead. -NOTE: -iteratables are not *only* for ``for`` +Special Methods & Protocols +=========================== -They can be used with anything that expects an iterable: +.. rst-class:: left +.. container:: -``sum``, ``tuple``, ``sorted``, and ``list`` + Special methods (also called *magic* methods) are the secret sauce to Python's Duck typing. + Defining the appropriate special methods in your classes is how you make your class act like standard classes. -LAB ------ +What's in a Name? +----------------- -In the ``Examples/session09`` dir, you will find: -:download:`iterator_1.py <../../Examples/Session09/iterator_1.py>` +We've seen at least one special method so far:: -* Extend (``iterator_1.py`` ) to be more like ``range()`` -- add three input parameters: ``iterator_2(start, stop, step=1)`` + __init__ -* What happens if you break from a loop and try to pick it up again: +It's all in the double underscores... -.. code-block:: python +Pronounced "dunder" (or "under-under") - it = IterateMe_2(2, 20, 2) - for i in it: - if i > 10: break - print(i) +try: ``dir(2)`` or ``dir(list)`` -.. code-block:: python +Generally Useful Special Methods +-------------------------------- - for i in it: - print(i) +Most classes should at least have these special methods: -* Does ``range()`` behave the same? +``object.__str__``: + Called by the str() built-in function and by the print function to compute + the *informal* string representation of an object. - - make yours match ``range()`` +``object.__repr__``: + Called by the repr() built-in function to compute the *official* string representation of an object. - - is range an iterator or an iteratable? + (ideally: ``eval( repr(something) ) == something``) -Generators +Protocols ---------- -Generators +.. rst-class:: build +.. container:: + + The set of special methods needed to emulate a particular type of Python object is called a *protocol*. + + Your classes can "become" like Python built-in classes by implementing the methods in a given protocol. + + Remember, these are more *guidelines* than laws. Implement what you need. + +The Numerics Protocol +--------------------- -* give you an iterator object -* no access to the underlying data ... if it even exists +Do you want your class to behave like a number? Implement these methods: +.. code-block:: python -Conceptually: - Iterators are about various ways to loop over data. + object.__add__(self, other) + object.__sub__(self, other) + object.__mul__(self, other) + object.__floordiv__(self, other) + object.__mod__(self, other) + object.__divmod__(self, other) + object.__pow__(self, other[, modulo]) + object.__lshift__(self, other) + object.__rshift__(self, other) + object.__and__(self, other) + object.__xor__(self, other) + object.__or__(self, other) + +The Container Protocol +---------------------- - Generators can generate the data on the fly. +Want to make a container type? Here's what you need: -Practically: - You can use either one either way (and a generator is one type of iterator). +.. code-block:: python - Generators do some of the book-keeping for you -- simpler syntax. + object.__len__(self) + object.__getitem__(self, key) + object.__setitem__(self, key, value) + object.__delitem__(self, key) + object.__iter__(self) + object.__reversed__(self) + object.__contains__(self, item) + object.__getslice__(self, i, j) + object.__setslice__(self, i, j, sequence) + object.__delslice__(self, i, j) + +An Example +---------- -yield ------- +Each of these methods supports a common Python operation. -``yield`` is a way to make a quickie generator with a function: +For example, to make '+' work with a sequence type in a vector-like fashion, +implement ``__add__``: .. code-block:: python - def a_generator_function(params): - some_stuff - yield something + def __add__(self, v): + """return the element-wise vector sum of self and v + """ + assert len(self) == len(v) + return vector([x1 + x2 for x1, x2 in zip(self, v)]) + +.. rst-class:: centered -Generator functions "yield" a value, rather than returning a value. +[a more complete example may be seen :download:`here <../../Examples/Session08/vector.py>`] -State is preserved in between yields. +Protocols in Summary +-------------------- + +Use special methods when you want your class to act like a "standard" class in some way. + +Look up the special methods you need and define them. + +There's more to read about the details of implementing these methods: + +* https://docs.python.org/3.5/reference/datamodel.html#special-method-names +* http://www.rafekettler.com/magicmethods.html + +LAB: Properties, class methods, special methods continued +========================================================= + +Let's complete our Circle class: + +Steps 5-8 of: + +:ref:`exercise_circle_class` + + +Emulating Standard types +========================= +.. rst-class:: medium -.. nextslide:: generator functions + Making your classes behave like the built-ins -A function with ``yield`` in it is a "factory" for a generator +Callable classes +----------------- -Each time you call it, you get a new generator: +We've been using functions a lot: .. code-block:: python - gen_a = a_generator() - gen_b = a_generator() + def my_fun(something): + do_something + ... + return something + +And then we can call it: -Each instance keeps its own state. +.. code-block:: python -Really just a shorthand for an iterator class that does the book keeping for you. + result = my_fun(some_arguments) .. nextslide:: -An example: like ``range()`` +But what if we need to store some data to know how to evaluate that function? + +Example: a function that computes a quadratic function: + +.. math:: + + y = a x^2 + bx + c + +You could pass in a, b and c each time: .. code-block:: python - def y_range(start, stop, step=1): - i = start - while i < stop: - yield i - i += step + def quadratic(x, a, b, c): + return a * x**2 + b * x + c -Real World Example from FloatCanvas: +But what if you are using the same a, b, and c numerous times? -https://github.com/svn2github/wxPython/blob/master/3rdParty/FloatCanvas/floatcanvas/FloatCanvas.py#L100 +Or what if you need to pass this in to something +(like map) that requires a function that takes a single argument? +"Callables" +----------- -.. nextslide:: +Various places in python expect a "callable" -- something that you can +call like a function: -Note: +.. code-block:: python -.. code-block:: ipython + a_result = something(some_arguments) - In [164]: gen = y_range(2,6) - In [165]: type(gen) - Out[165]: generator - In [166]: dir(gen) - Out[166]: - ... - '__iter__', - ... - '__next__', +"something" in this case is often a function, but can be anything else +that is "callable". +What have we been introduced to recently that is "callable", but not a +function object? -So the generator **is** an iterator +Custom callable objects +------------------------ -Note: A generator function can also be a method in a class +The trick is one of Python's "magic methods" +.. code-block:: python -.. More about iterators and generators: + __call__(*args, **kwargs) -.. http://www.learningpython.com/2009/02/23/iterators-iterables-and-generators-oh-my/ +If you define a ``__call__`` method in your class, it will be used when +code "calls" an instance of your class: -:download:`yield_example.py <../../Examples/Session09/yield_example.py>` +.. code-block:: python -generator comprehension ------------------------ + class Callable: + def __init__(self, .....) + some_initilization + def __call__(self, some_parameters) -yet another way to make a generator: +Then you can do: .. code-block:: python - >>> [x * 2 for x in [1, 2, 3]] - [2, 4, 6] - >>> (x * 2 for x in [1, 2, 3]) - at 0x10911bf50> - >>> for n in (x * 2 for x in [1, 2, 3]): - ... print n - ... 2 4 6 + callable_instance = Callable(some_arguments) + result = callable_instance(some_arguments) -More interesting if [1, 2, 3] is also a generator +Writing your own sequence type +------------------------------ -LAB ----- +Python has a handful of nifty sequence types built in: -Write a few generators: + * lists + * tuples + * strings + * ... -* Sum of integers -* Doubler -* Fibonacci sequence -* Prime numbers +But what if you need a sequence that isn't built in? -(test code in -:download:`test_generator.py <../../Examples/Session09/test_generator.py>`) +A Sparse array +-------------- -Descriptions: +Example: Sparse Array -Sum of the integers: - keep adding the next integer +Sometimes we have data sets that are "sparse" -- i.e. most of the values are zero. - 0 + 1 + 2 + 3 + 4 + 5 + ... +So you may not want to store a huge bunch of zeros. - so the sequence is: +But you do want the array to look like a regular old sequence. - 0, 1, 3, 6, 10, 15 ..... +So how do you do that? -.. nextslide:: +The Sequence protocol +---------------------- + +You can make your class look like a regular python sequence by defining +the set of special methods you need: + +https://docs.python.org/3/reference/datamodel.html#emulating-container-types + +and + +http://www.rafekettler.com/magicmethods.html#sequence + +The key ones are: + ++-------------------+-----------------------+ +| ``__len__`` | for ``len(sequence)`` | ++-------------------+-----------------------+ +| ``__getitem__`` | for ``x = seq[i]`` | ++-------------------+-----------------------+ +| ``__setitem__`` | for ``seq[i] = x`` | ++-------------------+-----------------------+ +| ``__delitem__`` | for ``del seq[i]`` | ++-------------------+-----------------------+ +| ``__contains__`` | for ``x in seq`` | ++-------------------+-----------------------+ + +LAB: Callables & Sparse Arrays +------------------------------ -Doubler: - Each value is double the previous value: +Callables +--------- + +Write a class for a quadratic equation. + +* The initializer for that class should take the parameters: ``a, b, c`` - 1, 2, 4, 8, 16, 32, +* It should store those parameters as attributes. -Fibonacci sequence: - The fibonacci sequence as a generator: +* The resulting instance should evaluate the function when called, and return the result: - f(n) = f(n-1) + f(n-2) - 1, 1, 2, 3, 5, 8, 13, 21, 34... +.. code-block:: python -Prime numbers: - Generate the prime numbers (numbers only divisible by them self and 1): + my_quad = Quadratic(a=2, b=3, c=1) - 2, 3, 5, 7, 11, 13, 17, 19, 23... + my_quad(0) -Others to try: - Try x^2, x^3, counting by threes, x^e, counting by minus seven, ... +Sparse Array +------------ +Write a class for a sparse array: -========== -Next Week -========== +:ref:`exercise_sparse_array` -Decorators and Context managers -- fun stuff! +Review framing questions +======================== -Cris Ewing will come by to talk about the second quarter -web development class Homework ---------- +======== + +Finish up the labs. + +Bring your questions to office hours. + + +Readings +======== + +Descriptors +----------- + +Hettinger on Descriptors -Finish up the labs +https://docs.python.org/2/howto/descriptor.html -Work on your project -- not much time left! -And *do* let me know what you're doing if you haven't yet! diff --git a/slides_sources/source/session10.rst b/slides_sources/source/session10.rst index 59e5bba..cde256c 100644 --- a/slides_sources/source/session10.rst +++ b/slides_sources/source/session10.rst @@ -1,811 +1,739 @@ + + .. include:: include.rst -******************************************************* -Session Ten: Decorators and Context Managers -- Wrap Up -******************************************************* +Session Ten: Functional Programming +*********************************** -===================== -Web Development Class -===================== -.. rst-class:: large centered +Announcements +============= - Internet Programming in Python +Review & Questions +================== - Cris Ewing +Homework +======== -================ -Review/Questions -================ +Code review -- let's take a look. -Review of Previous Class ------------------------- -Iterators +Lightning Talks +=============== + +| |lightning-session10a| +| |lightning-session10b| +| |lightning-session10c| +| |lightning-session10d| +| |lightning-session10e| +| |lightning-session10f| +| |lightning-session10g| +| |lightning-session10h| +| |lightning-session10i| +| |lightning-session10j| +| -Generators +Framing +======= -Projects --------- +Functional Programming +====================== -Due Dec Friday, Dec 11th, 11:59pm PST +No real consensus about what that means. -.. rst-class:: medium +But there are some "classic" methods available in Python. - (that's three days!) +map +--- -Push to github or email them to me. +``map`` "maps" a function onto a sequence of objects -- It applies the function to each item in the list, returning another list -====================== -Lightning Talks Today: -====================== -.. rst-class:: medium +.. code-block:: ipython - Austin Scara + In [23]: l = [2, 5, 7, 12, 6, 4] + In [24]: def fun(x): + return x*2 + 10 + In [25]: map(fun, l) + Out[25]: [14, 20, 24, 34, 22, 18] - Marty Pitts +But if it's a small function, and you only need it once: -============ -Code Review? -============ +.. code-block:: ipython -.. rst-class:: left + In [26]: map(lambda x: x*2 + 10, l) + Out[26]: [14, 20, 24, 34, 22, 18] + +filter +------ - Do you think you've "got" iterators, iterables, and generators? +``filter`` "filters" a sequence of objects with a boolean function -- +It keeps only those for which the function is True -- filtering our the rest. - Options: +To get only the even numbers: - 1) Look at someone's code. +.. code-block:: ipython - 2) look at some of my code. + In [27]: l = [2, 5, 7, 12, 6, 4] + In [28]: filter(lambda x: not x%2, l) + Out[28]: [2, 12, 6, 4] - 3) Go over someone's project code -- anyone stuck on something? +If you pass ``None`` to ``filter()``, you get only items that evaluate to true: +.. code-block:: ipython -========== -Decorators -========== + In [1]: l = [1, 0, 2.3, 0.0, 'text', '', [1,2], [], False, True, None ] -**A Short Reminder** + In [2]: filter(None, l) + Out[2]: [1, 2.3, 'text', [1, 2], True] -.. rst-class:: left +reduce +------ + +``reduce`` "reduces" a sequence of objects to a single object with a function that combines two arguments - Functions are things that generate values based on input (arguments). +To get the sum: - In Python, functions are first-class objects. +.. code-block:: ipython - This means that you can bind names to them, pass them around, etc, just like - other objects. + In [30]: l = [2, 5, 7, 12, 6, 4] + In [31]: reduce(lambda x,y: x+y, l) + Out[31]: 36 - Because of this fact, you can write functions that take functions as - arguments and/or return functions as values: - .. code-block:: python +To get the product: - def substitute(a_function): - def new_function(*args, **kwargs): - return "I'm not that other function" - return new_function +.. code-block:: ipython + In [32]: reduce(lambda x,y: x*y, l) + Out[32]: 20160 -A Definition ------------- +or -There are many things you can do with a simple pattern like this one. -So many, that we give it a special name: +.. code-block:: ipython -.. rst-class:: centered medium + In [13]: import operator + In [14]: reduce(operator.mul, l) + Out[14]: 20160 -**Decorator** +Comprehensions +-------------- -.. rst-class:: build centered +Couldn't you do all this with comprehensions? - "A decorator is a function that takes a function as an argument and - returns a function as a return value." +Yes: - That's nice and all, but why is that useful? +.. code-block:: ipython -An Example ----------- + In [33]: [x+2 + 10 for x in l] + Out[33]: [14, 17, 19, 24, 18, 16] -Imagine you are trying to debug a module with a number of functions like this -one: + In [34]: [x for x in l if not x%2] + Out[34]: [2, 12, 6, 4] + + In [6]: l + Out[6]: [1, 0, 2.3, 0.0, 'text', '', [1, 2], [], False, True, None] + In [7]: [i for i in l if i] + Out[7]: [1, 2.3, 'text', [1, 2], True] + +(Except Reduce) + +But Guido thinks almost all uses of reduce are really ``sum()`` + +Functional Programming +---------------------- + +Comprehensions and map, filter, reduce are all "functional programming" approaches} + +``map, filter`` and ``reduce`` pre-date comprehensions in Python's history + +Some people like that syntax better + +And "map-reduce" is a big concept these days for parallel processing of "Big Data" in NoSQL databases. + +(Hadoop, MongoDB, etc.) + +Comprehensions +============== + +List comprehensions +------------------- + +A bit of functional programming + +consider this common ``for`` loop structure: .. code-block:: python - def add(a, b): - return a + b + new_list = [] + for variable in a_list: + new_list.append(expression) -.. rst-class:: build -.. container:: +This can be expressed with a single line using a "list comprehension" - You want to see when each function is called, with what arguments and - with what result. So you rewrite each function as follows: +.. code-block:: python - .. code-block:: python + new_list = [expression for variable in a_list] - def add(a, b): - print("Function 'add' called with args: {}, {}".format(a, b) ) - result = a + b - print("\tResult --> {}".format(result)) - return result .. nextslide:: -That's not particularly nice, especially if you have lots of functions -in your module. +What about nested for loops? -Now imagine we defined the following, more generic *decorator*: +.. code-block:: python + + new_list = [] + for var in a_list: + for var2 in a_list2: + new_list.append(expression) + +Can also be expressed in one line: .. code-block:: python - def logged_func(func): - def logged(*args, **kwargs): - print("Function {} called".format(func.__name__)) - if args: - print("\twith args: {}".format(args)) - if kwargs: - print("\twith kwargs: {}".format(kwargs)) - result = func(*args, **kwargs) - print("\t Result --> {}".format(result)) - return result - return logged + new_list = [exp for var in a_list for var2 in a_list2] -(demo) +You get the "outer product", i.e. all combinations. .. nextslide:: -We could then make logging versions of our module functions: +But usually you at least have a conditional in the loop: .. code-block:: python - logging_add = logged_func(add) + new_list = [] + for variable in a_list: + if something_is_true: + new_list.append(expression) -Then, where we want to see the results, we can use the logged version: +You can add a conditional to the comprehension: -.. code-block:: ipython +.. code-block:: python - In [37]: logging_add(3, 4) - Function 'add' called - with args: (3, 4) - Result --> 7 - Out[37]: 7 + new_list = [expr for var in a_list if something_is_true] -.. rst-class:: build -.. container:: +.. nextslide:: - This is nice, but we have to call the new function wherever we originally - had the old one. +Examples: - It'd be nicer if we could just call the old function and have it log. +.. code-block:: ipython + + In [341]: [x**2 for x in range(3)] + Out[341]: [0, 1, 4] + + In [342]: [x+y for x in range(3) for y in range(5,7)] + Out[342]: [5, 6, 6, 7, 7, 8] + + In [343]: [x*2 for x in range(6) if not x%2] + Out[343]: [0, 4, 8] .. nextslide:: -Remembering that you can easily rebind symbols in Python using *assignment -statements* leads you to this form: +Get creative.... .. code-block:: python - def logged_func(func): - # implemented above + [name for name in dir(__builtin__) if "Error" in name] + ['ArithmeticError', + 'AssertionError', + 'AttributeError', + 'BufferError', + 'EOFError', + .... - def add(a, b): - return a + b - add = logged_func(add) +Set Comprehensions +------------------ -.. rst-class:: build -.. container:: +You can do it with sets, too: - And now you can simply use the code you've already written and calls to - ``add`` will be logged: +.. code-block:: python - .. code-block:: ipython + new_set = { value for variable in a_sequence } - In [41]: add(3, 4) - Function 'add' called - with args: (3, 4) - Result --> 7 - Out[41]: 7 -Syntax ------- +same as for loop: -Rebinding the name of a function to the result of calling a decorator on that -function is called **decoration**. +.. code-block:: python -Because this is so common, Python provides a special operator to perform it -more *declaratively*: the ``@`` operator -- I told you I'd eventually explain what was going on under the hood with that wierd `@` symbol: + new_set = set() + for key in a_list: + new_set.add(value) -.. code-block:: python - def add(a, b): - return a + b - add = logged_func(add) +.. nextslide:: - @logged_func - def add(a, b): - return a + b +Example: finding all the vowels in a string... -The declarative form (called a decorator expression) is far more common, but both have the identical result, and can be used interchangeably. +.. code-block:: ipython -(demo) + In [19]: s = "a not very long string" -Callables ---------- + In [20]: vowels = set('aeiou') -Our original definition of a *decorator* was nice and simple, but a tiny bit -incomplete. + In [21]: { l for l in s if l in vowels } + Out[21]: {'a', 'e', 'i', 'o'} -In reality, decorators can be used with anything that is *callable*. +Side note: why did I do ``set('aeiou')`` rather than just `aeiou` ? -Remember from two weeks ago, a *callable* is a function, a method on a class, -or a class that implements the ``__call__`` special method. +Dict Comprehensions +------------------- -So in fact the definition should be updated as follows: +Also with dictionaries -.. rst-class:: centered medium +.. code-block:: python -A decorator is a callable that takes a callable as an argument and -returns a callable as a return value. + new_dict = { key:value for variable in a_sequence} -An Example ----------- -Consider a decorator that would save the results of calling an expensive -function with given arguments: +same as for loop: .. code-block:: python - class Memoize: - """ - memoize decorator from avinash.vora - http://avinashv.net/2008/04/python-decorators-syntactic-sugar/ - """ - def __init__(self, function): # runs when memoize class is called - self.function = function - self.memoized = {} - - def __call__(self, *args): # runs when memoize instance is called - try: - return self.memoized[args] - except KeyError: - self.memoized[args] = self.function(*args) - return self.memoized[args] + new_dict = {} + for key in a_list: + new_dict[key] = value + + .. nextslide:: -Let's try that out with a potentially expensive function: +Example .. code-block:: ipython - In [56]: @Memoize - ....: def sum2x(n): - ....: return sum(2 * i for i in xrange(n)) - ....: + In [22]: { i: "this_%i"%i for i in range(5) } + Out[22]: {0: 'this_0', 1: 'this_1', 2: 'this_2', + 3: 'this_3', 4: 'this_4'} - In [57]: sum2x(10000000) - Out[57]: 99999990000000 - In [58]: sum2x(10000000) - Out[58]: 99999990000000 +(not as useful with the ``dict()`` constructor...) -It's nice to see that in action, but what if we want to know *exactly* how much difference it made? +=== +LAB +=== -Nested Decorators ------------------ +List comps exercises: -You can stack decorator expressions. The result is like calling each decorator in order, from bottom to top: +:ref:`exercise_comprehensions` -.. code-block:: python - @decorator_two - @decorator_one - def func(x): - pass - # is exactly equal to: - def func(x): - pass - func = decorator_two(decorator_one(func)) +Lightning Talk +---------------- -.. nextslide:: +.. rst-class:: medium -Let's define another decorator that will time how long a given call takes: +Anonymous functions +=================== -.. code-block:: python +lambda +------ + +.. code-block:: ipython + + In [171]: f = lambda x, y: x+y + In [172]: f(2,3) + Out[172]: 5 - import time - def timed_func(func): - def timed(*args, **kwargs): - start = time.time() - result = func(*args, **kwargs) - elapsed = time.time() - start - print("time expired: {}".format(elapsed)) - return result - return timed +Content of function can only be an expression -- not a statement + +Anyone remember what the difference is? + +Called "Anonymous": it doesn't get a name. .. nextslide:: -And now we can use this new decorator stacked along with our memoizing -decorator: +It's a python object, it can be stored in a list or other container .. code-block:: ipython - In [71]: @timed_func - ....: @Memoize - ....: def sum2x(n): - ....: return sum(2 * i for i in xrange(n)) - In [72]: sum2x(10000000) - time expired: 0.997071027756 - Out[72]: 99999990000000 - In [73]: sum2x(10000000) - time expired: 4.05311584473e-06 - Out[73]: 99999990000000 + In [7]: l = [lambda x, y: x+y] + In [8]: type(l[0]) + Out[8]: function -Examples from the Standard Library ----------------------------------- +And you can call it: -It's going to be a lot more common for you to use pre-defined decorators than -for you to be writing your own. +.. code-block:: ipython -We've seen a few already: + In [9]: l[0](3,4) + Out[9]: 7 -.. nextslide:: +Functions as first class objects +--------------------------------- -For example, ``@staticmethod`` and ``@classmethod`` can also be used as simple -callables, without the nifty decorator expression: +You can do that with "regular" functions too: -.. code-block:: python +.. code-block:: ipython - # the way we saw last week: - class C(object): - @staticmethod - def add(a, b): - return a + b + In [12]: def fun(x,y): + ....: return x+y + ....: + In [13]: l = [fun] + In [14]: type(l[0]) + Out[14]: function + In [15]: l[0](3,4) + Out[15]: 7 -Is exactly the same as: -.. code-block:: python +A bit more about lambda +------------------------ - class C(object): - def add(a, b): - return a + b - add = staticmethod(add) +It is very useful for specifying sorting as well: -Note that the "``def``" binds the name ``add``, then the next line -rebinds it. +.. code-block:: ipython + In [55]: lst = [("Chris","Barker"), ("Fred", "Jones"), ("Zola", "Adams")] -.. nextslide:: + In [56]: lst.sort() -The ``classmethod()`` builtin can do the same thing: + In [57]: lst + Out[57]: [('Chris', 'Barker'), ('Fred', 'Jones'), ('Zola', 'Adams')] -.. code-block:: python + In [58]: lst.sort(key=lambda x: x[1]) - # in declarative style - class C(object): - @classmethod - def from_iterable(cls, seq): - # method body + In [59]: lst + Out[59]: [('Zola', 'Adams'), ('Chris', 'Barker'), ('Fred', 'Jones')] - # in imperative style: - class C(object): - def from_iterable(cls, seq): - # method body - from_iterable = classmethod(from_iterable) +lambda in keyword arguments +--------------------------- +.. code-block:: ipython -property() ------------ + In [186]: l = [] + In [187]: for i in range(3): + l.append(lambda x, e=i: x**e) + .....: + In [189]: for f in l: + print(f(3)) + 1 + 3 + 9 -Remember the property() built in? +Note when the keyword argument is evaluated: this turns out to be very handy! -Perhaps most commonly, you'll see the ``property()`` builtin used this way. +Lab: Lambda +=========== -Two weeks ago we saw this code: +Here's an exercise to try out some of this: -.. code-block:: python +:ref:`exercise_lambda_magic` - class C(object): - def __init__(self): - self._x = None - @property - def x(self): - return self._x - @x.setter - def x(self, value): - self._x = value - @x.deleter - def x(self): - del self._x -.. nextslide:: +Closures and function Currying +============================== -But this could also be accomplished like so: +Defining specialized functions on the fly -.. code-block:: python +Closures +-------- + +"Closures" and "Currying" are cool CS terms for what is really just defining functions on the fly. - class C(object): - def __init__(self): - self._x = None - def getx(self): - return self._x - def setx(self, value): - self._x = value - def delx(self): - del self._x - x = property(getx, setx, delx, - "I'm the 'x' property.") +you can find a "proper" definition here: +http://en.wikipedia.org/wiki/Closure_(computer_programming) -:download:`Examples/Session10/property_ugly.py <../../Examples/Session10/property_ugly.py>` +but I even have trouble following that. +So let's go straight to an example: .. nextslide:: -Note that in this case, the decorator object returned by the property decorator -itself implements additional decorators as attributes on the returned method -object. So you could actually do this: +.. code-block:: python + def counter(start_at=0): + count = [start_at] + def incr(): + count[0] += 1 + return count[0] + return incr -.. code-block:: python +What's going on here? - class C(object): - def __init__(self): - self._x = None - def x(self): - return self._x - x = property(x) - def _set_x(self, value): - self._x = value - x = x.setter(_set_x) - def _del_x(self): - del self._x - x = x.deleter(_del_x) - -But that's getting really ugly! +We have stored the ``start_at`` value in a list. -LAB ----- +Then defined a function, ``incr`` that adds one to the value in the list, and returns that value. -**p_wrapper Decorator** +[ Quiz: why is it: ``count = [start_at]``, rather than just ``count=start_at`` ] -Write a simple decorator you can apply to a function that returns a string. +.. nextslide:: -Decorating such a function should result in the original output, wrapped by an -HTML 'p' tag: +So what type of object do you get when you call ``counter()``? .. code-block:: ipython - In [4]: @p_wrapper - ...: def return_a_string(string): - ...: return string - ...: + In [37]: c = counter(start_at=5) - In [5]: return_a_string("this is a string") - Out[5]: '

this is a string

' + In [38]: type(c) + Out[38]: function -simple test code in -:download:`Examples/Session10/test_p_wrapper.py <../../Examples/Session10/test_p_wrapper.py>` +So we get a function back -- makes sense. The ``def`` defines a function, and that function is what's getting returned. +Being a function, we can, of course, call it: -Lightning Talks ----------------- +.. code-block:: ipython -.. rst-class:: medium + In [39]: c() + Out[39]: 6 -| -| Austin Scara -| -| Marty Pitts -| + In [40]: c() + Out[40]: 7 + +Each time is it called, it increments the value by one. + +.. nextslide:: +But what happens if we call ``counter()`` multiple times? -================= -Context Managers -================= +.. code-block:: ipython -**Repetition in code stinks (DRY!)** + In [41]: c1 = counter(5) -.. rst-class:: left build -.. container:: + In [42]: c2 = counter(10) + In [43]: c1() + Out[43]: 6 - A large source of repetition in code deals with the handling of external - resources. + In [44]: c2() + Out[44]: 11 - As an example, how many times do you think you might type the following - code: +So each time ``counter()`` is called, a new function is created. And that function has its own copy of the ``count`` object. This is what makes in a "closure" -- it carries with it the scope in which is was created. - .. code-block:: python +the returned ``incr`` function is a "curried" function -- a function with some parameters pre-specified. - file_handle = open('filename.txt', 'r') - file_content = file_handle.read() - file_handle.close() - # do some stuff with the contents +``functools.partial`` +--------------------- - What happens if you forget to call ``.close()``? +The ``functools`` module in the standard library provides utilities for working with functions: - What happens if reading the file raises an exception? +https://docs.python.org/3.5/library/functools.html +Creating a curried function turns out to be common enough that the ``functools.partial`` function provides an optimized way to do it: -Resource Handling ------------------ +What functools.partial does is: -Leaving an open file handle laying around is bad enough. What if the resource -is a network connection, or a database cursor? + * Makes a new version of a function with one or more arguments already filled in. + * The new version of a function documents itself. -You can write more robust code for handling your resources: +Example: .. code-block:: python - try: - file_handle = open('filename.txt', 'r') - file_content = file_handle.read() - finally: - file_handle.close() - # do something with file_content here + def power(base, exponent): + """returns based raised to the give exponent""" + return base ** exponent -But what exceptions do you want to catch? And do you really want to have to -remember to type all that **every** time you open a resource? +Simple enough. but what if we wanted a specialized ``square`` and ``cube`` function? -.. nextslide:: It Gets Better +We can use ``functools.partial`` to *partially* evaluate the function, giving us a specialized version: -Starting in version 2.5, Python provides a structure for reducing the -repetition needed to handle resources like this. +square = partial(power, exponent=2) +cube = partial(power, exponent=3) -.. rst-class:: centered +Recursion +--------- -**Context Managers** +You've seen functions that call other functions. -You can encapsulate the setup, error handling and teardown of resources in a -few simple steps. +If a function calls *itself*, we call that **recursion** -The key is to use the ``with`` statement. +Like with other functions, a call within a call establishes a *call stack* -``with`` a little help ----------------------- +With recursion, if you are not careful, this stack can get *very* deep. -Since the introduction of the ``with`` statement in `pep343`_, the above six -lines of defensive code have been replaced with this simple form: +Python has a maximum limit to how much it can recurse. This is intended to +save your machine from running out of RAM. -.. code-block:: python +.. nextslide:: Recursion can be Useful - with open('filename', 'r') as file_handle: - file_content = file_handle.read() - # do something with file_content +Recursion is especially useful for a particular set of problems. -``open`` builtin is defined as a *context manager*. +For example, take the case of the *factorial* function. -The resource it returnes (``file_handle``) is automatically and reliably closed -when the code block ends. +In mathematics, the *factorial* of an integer is the result of multiplying that +integer by every integer smaller than it down to 1. -.. _pep343: http://legacy.python.org/dev/peps/pep-0343/ +:: -.. nextslide:: A Growing Trend + 5! == 5 * 4 * 3 * 2 * 1 -At this point in Python history, many functions you might expect to behave this -way do: +We can use a recursive function nicely to model this mathematical function -* ``open`` and works as a context manager. -* networks connections via ``socket`` do as well. -* most implementations of database wrappers can open connections or cursors as - context managers. -* ... -* But what if you are working with a library that doesn't support this - (``urllib``)? -Close It Automatically ----------------------- -There are a couple of ways you can go. +Lab: Fibonacci +============== -If the resource in questions has a ``.close()`` method, then you can simply use -the ``closing`` context manager from ``contextlib`` to handle the issue: +Let's write a few functions in class: -** check example for py3 -- urlib depricated! +:ref:`exercise_fibonacci` -.. code-block:: python - import urllib - from contextlib import closing - with closing(urllib.urlopen('http://google.com/')) as web_connection: - # do something with the open resource - # and here, it will be closed automatically +Where we've been.... +==================== -But what if the thing doesn't have a ``close()`` method, or you're creating -the thing and it shouldn't have a close() method? -Do It Yourself --------------- -You can also define a context manager of your own. +Python 100 +---------- -The interface is simple. It must be a class that implements two -more of the nifty python *special methods* +.. rst-class:: left -**__enter__(self)** Called when the ``with`` statement is run, it should return something to work with in the created context. + Once upon a time, there was a little scripting language called Python. -**__exit__(self, e_type, e_val, e_traceback)** Clean-up that needs to happen is implemented here. + Python 100, this course, is designed to provide the basics or the core of the language. -The arguments will be the exception raised in the context. + By the end of this course you should be able to "create something useful" with Python. -If the exception will be handled here, return True. If not, return False. -Let's see this in action to get a sense of what happens. -An Example +Python 200 ---------- -Consider this code: +.. rst-class:: left -.. code-block:: python + Also known as Internet Programming with Python, Python 200 is designed to provide the basics of web programming. - class Context(object): - """from Doug Hellmann, PyMOTW - http://pymotw.com/2/contextlib/#module-contextlib - """ - def __init__(self, handle_error): - print('__init__({})'.format(handle_error)) - self.handle_error = handle_error + Here, already, you're going to run into Python language constructs that were once upon a time considered "optional." - def __enter__(self): - print('__enter__()') - return self +Python 300 +---------- - def __exit__(self, exc_type, exc_val, exc_tb): - print('__exit__({}, {}, {})'.format(exc_type, exc_val, exc_tb)) - return self.handle_error +.. rst-class:: left -:download:`Examples/Session10/context_managers.py <../../Examples/Session10/context_managers.py>` + "As soon as an optional advanced language feature is used by anyone in an organization, it is no longer optional--it is effectively imposed on everyone in the organization. The same holds true for externally developed software you use in your systems--if the software’s author uses an advanced or extraneous language feature, it’s no longer entirely optional for you, because you have to understand the feature to reuse or change the code." + "Generators, decorators, slots, properties, descriptors, metaclasses, context managers, closures, super, namespace packages, unicode, function annotations, relative imports, keyword-only arguments, class and static methods, and even obscure applications of comprehensions and operator overloading.... -.. nextslide:: + If any person or program you need to work with uses such tools, they automatically become part of your required knowledge base too. The net effect of such over-engineering is to either escalate learning requirements radically, or foster a user base that only partially understands the tools they employ. This is obviously less than ideal for those hoping to use Python in simpler ways, and contradictory to the scripting motif." -This class doesn't do much of anything, but playing with it can help -clarify the order in which things happen: + -- Mark Lutz on Optional Language Features -.. code-block:: ipython +. . . and where we're going +--------------------------- - In [46]: with Context(True) as foo: - ....: print('This is in the context') - ....: raise RuntimeError('this is the error message') - __init__(True) - __enter__() - This is in the context - __exit__(, this is the error message, ) +.. rst-class:: left -.. rst-class:: build -.. container:: + We've been learning to drive this car called Python. You'll learn more about how to drive it in Python 200. - Because the exit method returns True, the raised error is 'handled'. + In Python 300 we give you the tools to become a mechanic. -.. nextslide:: + In the meantime you should at least be familiar with some of these language constructs.... -What if we try with ``False``? +Where could you go from here? +============================= -.. code-block:: ipython - In [47]: with Context(False) as foo: - ....: print('This is in the context') - ....: raise RuntimeError('this is the error message') - __init__(False) - __enter__() - This is in the context - __exit__(, this is the error message, ) - --------------------------------------------------------------------------- - RuntimeError Traceback (most recent call last) - in () - 1 with Context(False) as foo: - 2 print 'This is in the context' - ----> 3 raise RuntimeError('this is the error message') - 4 - RuntimeError: this is the error message - -The ``contextmanager`` decorator + +Know Python's built-in functions -------------------------------- -``contextlib.contextmanager`` turns generator functions into context managers. +https://docs.python.org/3/library/functions.html -Consider this code: +Many of these should at this point be familiar. -.. code-block:: python +Get to know the others. - from contextlib import contextmanager - - @contextmanager - def context(boolean): - print("__init__ code here") - try: - print("__enter__ code goes here") - yield object() - except Exception as e: - print("errors handled here") - if not boolean: - raise e - finally: - print("__exit__ cleanup goes here") -.. nextslide:: -The code is similar to the class defined previously. +Scan the PEPs +------------- -And using it has similar results. We can handle errors: +Python Enhancement Proposals -.. code-block:: ipython +https://www.python.org/dev/peps/ - In [96]: with context(True): - ....: print("in the context") - ....: raise RuntimeError("error raised") - ....: - __init__ code here - __enter__ code goes here - in the context - errors handled here - __exit__ cleanup goes here +Know what sorts of topics are discussed. Find the ones that interest you and could assist in your work. -.. nextslide:: +These will provided clarity into the sorts of problems the language designers are trying to solve, how they choose to solve them, and the tradeoffs they needed to make. PEPs also provide hints to alternative solutions. -Or, we can allow them to propagate: -.. code-block:: ipython - In [51]: with context(False): - ....: print("in the context") - ....: raise RuntimeError("error raised") - __init__ code here - __enter__ code goes here - in the context - errors handled here - __exit__ cleanup goes here - --------------------------------------------------------------------------- - RuntimeError Traceback (most recent call last) - in () - 1 with context(False): - 2 print "in the context" - ----> 3 raise RuntimeError("error raised") - 4 - RuntimeError: error raised +Scan What's New +--------------- +When a new version of Python is released, scan the release notes. -LAB ----- -**Timing Context Manager** +https://docs.python.org/3/whatsnew/ -Create a context manager that will print the elapsed time taken to -run all the code inside the context: -.. code-block:: ipython - In [3]: with Timer() as t: - ...: for i in range(100000): - ...: i = i ** 20 - ...: - this code took 0.206805 seconds +Read the source +--------------- -**Extra Credit**: allow the ``Timer`` context manager to take a file-like -object as an argument (the default should be sys.stdout). The results of the -timing should be printed to the file-like object. +https://www.python.org/downloads/source/ -Projects --------- +Let's say you want to learn more about lambda or classes. Search the code for related terms to see how the pros do it. + + +Contribute to a project +----------------------- + +Go to github.com and search for something that interests you. + +https://github.com/explore + +https://github.com/search?q=python + + + +Go to Meetups +------------- + +http://www.meetup.com/topics/python/ + + + +Take Py200 and Py300 +-------------------- + +Py200 -- Internet Programming in Python + +http://www.pce.uw.edu/courses/internet-programming-python.html + + +Py300 -- Systems Development in Python + +http://www.pce.uw.edu/courses/system-development-python.html + + + +Review framing questions +======================== + + +Readings +======== + + + +Functools +--------- + +https://pymotw.com/2/functools/ + +http://www.pydanny.com/python-partials-are-fun.html + + + +Closures & Currying +------------------- + +http://www.programiz.com/python-programming/closure + +https://www.clear.rice.edu/comp130/12spring/curry/ -Projects due this Friday. We'll review them over the weekend. -To turn in: - * Put up it up gitHub, and do a pull request - * Put it in its own gitHub repository and point me to it. - * zip up the code an email it to me. -Please do the online course evaluation +Multi-methods in Python +----------------------- -Anyone want office hours Thursday evening? +GvR on Multi-methods -Keep writing Python! \ No newline at end of file +http://www.artima.com/weblogs/viewpost.jsp?thread=101605 diff --git a/students/Boundb3/.ipynb_checkpoints/Jupyter_test-checkpoint.ipynb b/students/Boundb3/.ipynb_checkpoints/Jupyter_test-checkpoint.ipynb new file mode 100644 index 0000000..1eb2197 --- /dev/null +++ b/students/Boundb3/.ipynb_checkpoints/Jupyter_test-checkpoint.ipynb @@ -0,0 +1,34 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "test" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3.0 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/students/Boundb3/LightningTalk/PyTalk_Excel_and_Python.ipynb b/students/Boundb3/LightningTalk/PyTalk_Excel_and_Python.ipynb new file mode 100644 index 0000000..ce6eb6a --- /dev/null +++ b/students/Boundb3/LightningTalk/PyTalk_Excel_and_Python.ipynb @@ -0,0 +1,565 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Pytalk: Excel and Python " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Brennen Bounds:\n", + " Source Reference: Automate the Boring Stuff with Python (Chapt 12)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "### do your pip install openpyxl: then..." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import openpyxl\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "wb = openpyxl.load_workbook(\"example.xlsx\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Access Data inside an excel spreadsheet" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['Sheet-fruit', 'Sheet2', 'Sheet3']" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "wb.get_sheet_names()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "openpyxl.workbook.workbook.Workbook" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(wb)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ws = wb.active\n", + "ws\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "openpyxl.worksheet.worksheet.Worksheet" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(ws)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Checking cell contents" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "datetime.datetime(2015, 4, 5, 13, 34)" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a1 = ws[\"A1\"]\n", + "a1.value" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ws.cell(row = 1, column = 2)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Apples'" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ws.cell(row = 1, column = 2).value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Verify sheet contents" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ws.max_row" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Access a column or row of data" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "((, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ))" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tuple(ws[\"A1\":\"C7\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# by Row" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A1 2015-04-05 13:34:00\n", + "B1 Apples\n", + "C1 73\n", + "**rowbreak**\n", + "A2 2015-04-05 03:41:00\n", + "B2 Cherries\n", + "C2 85\n", + "**rowbreak**\n", + "A3 2015-04-06 12:46:00\n", + "B3 Pears\n", + "C3 14\n", + "**rowbreak**\n", + "A4 2015-04-08 08:59:00\n", + "B4 Oranges\n", + "C4 52\n", + "**rowbreak**\n", + "A5 2015-04-10 02:07:00\n", + "B5 Apples\n", + "C5 152\n", + "**rowbreak**\n", + "A6 2015-04-10 18:10:00\n", + "B6 Bananas\n", + "C6 23\n", + "**rowbreak**\n", + "A7 2015-04-10 02:40:00\n", + "B7 Strawberries\n", + "C7 98\n", + "**rowbreak**\n" + ] + } + ], + "source": [ + "for rowofcellObjects in ws[\"A1\":\"C7\"]:\n", + " for cellObj in rowofcellObjects:\n", + " print (cellObj.coordinate, cellObj.value)\n", + " print( \"**rowbreak**\") \n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# by Column" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " )" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ws.columns[1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterate to get the cell level data retreived from sections of data" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "'tuple' object has no attribute 'values'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mws\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcolumns\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'values'" + ] + } + ], + "source": [ + "ws.columns[1].values() # can't directly grab the data, need to iterate over the group to convert to a python class\n" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Apples\n", + "Cherries\n", + "Pears\n", + "Oranges\n", + "Apples\n", + "Bananas\n", + "Strawberries\n" + ] + } + ], + "source": [ + "for cellObj in ws.columns[1]:\n", + " print(cellObj.value)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# I can use the column or rows attributes to get a slice of data" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "((,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ),\n", + " (,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ),\n", + " (,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ))" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ws.columns[1:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# So, now we can capture data into a Python structure like a list" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Apples\n", + "Cherries\n", + "Pears\n", + "Oranges\n", + "Apples\n", + "Bananas\n", + "Strawberries\n", + "['Apples', 'Cherries', 'Pears', 'Oranges', 'Apples', 'Bananas', 'Strawberries']\n" + ] + } + ], + "source": [ + "fruits = []\n", + "for row in range(1,ws.max_row+1): #start the range at 1 for row one, would use row 2 if their was a header\n", + " fruit = ws[\"B\"+str(row)].value #add the value in the row to a string\n", + " fruits.append(fruit) # use python ways to convert that individual string data into a list\n", + " print(fruit)\n", + "print(fruits)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# You can also write data to an excel file, but that is another topic. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "#I hope you enjoyed seeing the ease of pulling data from an MS Excel file so you can use your python skills or excel skills\n", + "interchangably between the two.\n", + "\n", + "#pip install openypxl is a library that can do that for you!\n", + "\n", + "# also, yes, we can bring in and write results or formulas in an excell sheet, but only one or the other\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/Boundb3/LightningTalk/example.xlsx b/students/Boundb3/LightningTalk/example.xlsx new file mode 100644 index 0000000..2210270 Binary files /dev/null and b/students/Boundb3/LightningTalk/example.xlsx differ diff --git a/students/Boundb3/Pytalk/PyTalk_Excel_and_Python.ipynb b/students/Boundb3/Pytalk/PyTalk_Excel_and_Python.ipynb new file mode 100644 index 0000000..ca36185 --- /dev/null +++ b/students/Boundb3/Pytalk/PyTalk_Excel_and_Python.ipynb @@ -0,0 +1,526 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Pytalk: Excel and Python " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Brennen Bounds:\n", + " Source Reference: Automate the Boring Stuff with Python (Chapt 12)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "### do your pip install openpyxl: then..." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import openpyxl" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "wb = openpyxl.load_workbook(\"example.xlsx\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Access Data inside an excel spreadsheet" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Sheet-fruit', 'Sheet2', 'Sheet3']" + ] + }, + "execution_count": 4, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "wb.get_sheet_names()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "openpyxl.workbook.workbook.Workbook" + ] + }, + "execution_count": 6, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "type(wb)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 24, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "ws = wb.active\n", + "ws" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "openpyxl.worksheet.worksheet.Worksheet" + ] + }, + "execution_count": 13, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "type(ws)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Checking cell contents" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "datetime.datetime(2015, 4, 5, 13, 34)" + ] + }, + "execution_count": 15, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "a1 = ws[\"A1\"]\n", + "a1.value" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 16, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "ws.cell(row = 1, column = 2)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Apples'" + ] + }, + "execution_count": 17, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "ws.cell(row = 1, column = 2).value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Verify sheet contents" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 22, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "ws.max_row" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Access a column or row of data" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "((, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ),\n", + " (, , ))" + ] + }, + "execution_count": 27, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "tuple(ws[\"A1\":\"C7\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# by Row" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A1 2015-04-05 13:34:00\n", + "B1 Apples\n", + "C1 73\n", + "**rowbreak**\n", + "A2 2015-04-05 03:41:00\n", + "B2 Cherries\n", + "C2 85\n", + "**rowbreak**\n", + "A3 2015-04-06 12:46:00\n", + "B3 Pears\n", + "C3 14\n", + "**rowbreak**\n", + "A4 2015-04-08 08:59:00\n", + "B4 Oranges\n", + "C4 52\n", + "**rowbreak**\n", + "A5 2015-04-10 02:07:00\n", + "B5 Apples\n", + "C5 152\n", + "**rowbreak**\n", + "A6 2015-04-10 18:10:00\n", + "B6 Bananas\n", + "C6 23\n", + "**rowbreak**\n", + "A7 2015-04-10 02:40:00\n", + "B7 Strawberries\n", + "C7 98\n", + "**rowbreak**\n" + ] + } + ], + "source": [ + "for rowofcellObjects in ws[\"A1\":\"C7\"]:\n", + " for cellObj in rowofcellObjects:\n", + " print (cellObj.coordinate, cellObj.value)\n", + " print( \"**rowbreak**\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# by Column" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " )" + ] + }, + "execution_count": 35, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "ws.columns[1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Iterate to get the cell level data retreived from sections of data" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "'tuple' object has no attribute 'values'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mws\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcolumns\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'values'" + ] + } + ], + "source": [ + "ws.columns[1].values() # can't directly grab the data, need to iterate over the group to convert to a python class" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Apples\n", + "Cherries\n", + "Pears\n", + "Oranges\n", + "Apples\n", + "Bananas\n", + "Strawberries\n" + ] + } + ], + "source": [ + "for cellObj in ws.columns[1]:\n", + " print(cellObj.value)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# I can use the column or rows attributes to get a slice of data" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "((,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ),\n", + " (,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ),\n", + " (,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ,\n", + " ))" + ] + }, + "execution_count": 40, + "output_type": "execute_result", + "metadata": {} + } + ], + "source": [ + "ws.columns[1:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# So, now we can capture data into a Python structure like a list" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Apples\n", + "Cherries\n", + "Pears\n", + "Oranges\n", + "Apples\n", + "Bananas\n", + "Strawberries\n", + "['Apples', 'Cherries', 'Pears', 'Oranges', 'Apples', 'Bananas', 'Strawberries']\n" + ] + } + ], + "source": [ + "fruits = []\n", + "for row in range(1,ws.max_row+1): #start the range at 1 for row one, would use row 2 if their was a header\n", + " fruit = ws[\"B\"+str(row)].value #add the value in the row to a string\n", + " fruits.append(fruit) # use python ways to convert that individual string data into a list\n", + " print(fruit)\n", + "print(fruits)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# You can also write data to an excel file, but that is another topic. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#I hope you enjoyed seeing the ease of pulling data from an MS Excel file so you can use your python skills or excel skills\n", + "interchangably between the two.\n", + "\n", + "#pip install openypxl is a library that can do that for you!\n", + "\n", + "# also, yes, we can bring in and write results or formulas in an excell sheet, but only one or the other" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3.0 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/students/Boundb3/Pytalk/example.xlsx b/students/Boundb3/Pytalk/example.xlsx new file mode 100644 index 0000000..2210270 Binary files /dev/null and b/students/Boundb3/Pytalk/example.xlsx differ diff --git a/students/Boundb3/Session 01/Fizzbuzz - b3.py b/students/Boundb3/Session 01/Fizzbuzz - b3.py new file mode 100644 index 0000000..cc1ed3e --- /dev/null +++ b/students/Boundb3/Session 01/Fizzbuzz - b3.py @@ -0,0 +1,24 @@ +# print out the numbers from 1 to n, but replace numbers divisible by 3 with "Fizz", +# numbers divisible by 5 with "Buzz". Numbers divisible by both factors should display "FizzBuzz. +# The function should be named FizzBuzz and be able to accept a natural number as argument + + + +def FizzBuzz(n): + for i in range(n): #since the assignment says 'from 1 to 100 inclusive, how can you change range to include the number 100? + a = "" + if (i+1)%3 == 0: # what is the +1 used for here? + print("Fizz", end="") + a = "true" + + if (i+1)%5 == 0: # to run multiple 'if statments' in one function, use elif + print("Buzz",end="") + a = "true" + + if a == "true": + print("") + else: + print(i+1) + + +FizzBuzz(100) diff --git a/students/Boundb3/Session 01/Jupyter_test.ipynb b/students/Boundb3/Session 01/Jupyter_test.ipynb new file mode 100644 index 0000000..5508d32 --- /dev/null +++ b/students/Boundb3/Session 01/Jupyter_test.ipynb @@ -0,0 +1,32 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "ipython magics - gogle this\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/Boundb3/Session 01/Lab 2 Money.py b/students/Boundb3/Session 01/Lab 2 Money.py new file mode 100644 index 0000000..b51a4a7 --- /dev/null +++ b/students/Boundb3/Session 01/Lab 2 Money.py @@ -0,0 +1,99 @@ +#Brennen Bounds +#Python: Rick Riehle Hsi-Kai Yang +#Jan 20,2016 + + +# This is program to determine whether a mix of coins can make EXACTLY one dollar. +# Your program should prompt users to enter the number of pennies, nickels, dimes, and quarters. +# If the total value of the coins entered is equal to one dollar, +# the program should congratulate users for winning the game. +# Otherwise, the program should display a message indicating whether the amount entered +# was more than or less than a dollar. + + +'''variables: +coin = placeholder +answer = receipt of coin value from def +p = penny +n = nickel +d = dime +q = quarter +money = value of all of the change +ttlanswer = money variable rounded to 2 decimals''' + + + +import math + +#routine to collect the number of coins from a user for a coin type + + +def get_quantity(coin = .5): + count = 0 + coin = .05 + while type(coin) != int: + try: + coin = int(input("\tHow many (of these types of coin) do you have?")) + + except (TypeError, ValueError) as e: + print ("Your entry: ", e, " is not a positive whole number. Please enter a positive whole number.") + count +=1 + if count > 5: + print("Sorry, your entry does not match. Let's quit the game") + break + if coin < 0: + print("Really? I don't think you have negative coins. You need to enter a positive whole number. Try this coin again.") + get_quantity() + return coin + + + +#Welcome +print ("\n\t\tWelcome Money Player! \n\n This challenge will determine if your spare change \n " + "equals one dollar exactly -- or not. Ready....? Let's try!") +print ("\n\nYou can tell me the number of each coin type you have, " + "and I will test the value to see how close you are to 1 dollar.") + + +# get coin quantities from user +print("I will ask you what quantity of coins you have for each coin type: penny, nickel, dime and quarter.") +for i in range (4): + print("\n") + if i == 0: + print("\tLet's start with pennies.") + if i == 1: + print("\tOk, next, lets think nickels.") + if i == 2: + print("\tOk, next, how about dimes?") + if i == 3: + print("\tOk, and lastly, quarters.") + + answer = get_quantity() + print("\t\tThanks - got it. You had ", answer, "of those coins.") + +# assign value to the coin quantity + + if i == 0: + p = answer + if i == 1: + n = answer + if i== 2: + d = answer + if i == 3: + q = answer + +# calculate total value and limit to 2 decimals + +money = (p*.01) + (n*.05) + (d * .10) + (q*.25) +ttlanswer = math.ceil(money*100)/100 + +# share results with user + +if money == 1.00: + print("\n\tCongratulations you hit 1.00 Dollar on the nose!!") +elif money > 1.00: + print("\n\tYour change totals to: $", ttlanswer, ". It is $", (ttlanswer - int(1)), "over one dollar.") +elif money < 1.00: + print("\n\tYour change totals to: $", ttlanswer, ". It is $", (int(1) - ttlanswer), "under one dollar.") +else: + print("\n\tI don't think this worked right. Tell my programmer to take a look under the hood. Thanks, goodbye.") \ No newline at end of file diff --git a/students/Boundb3/Session 01/break_me.py b/students/Boundb3/Session 01/break_me.py new file mode 100644 index 0000000..fcfa04e --- /dev/null +++ b/students/Boundb3/Session 01/break_me.py @@ -0,0 +1,14 @@ +# name error - happy not defined +# count = happy + +# type error - cant divide a string by zero +# "this" / 0 + +# needs a : at the end of the line and () around the 10 +#for i in range 10: + +#8 is an integer, not a list, so need a list to append +an_Int = 8 +an_Int.append(4) + + diff --git a/students/Boundb3/Session 01/files size.py b/students/Boundb3/Session 01/files size.py new file mode 100644 index 0000000..5c5f942 --- /dev/null +++ b/students/Boundb3/Session 01/files size.py @@ -0,0 +1,65 @@ +'''Convert file sizes to human-readable form. + +Available functions: +approximate_size(size, a_kilobyte_is_1024_bytes) + takes a file size and returns a human-readable string + +Examples: +>>> approximate_size(1024) +'1.0 KiB' +>>> approximate_size(1000, False) +'1.0 KB' + +''' + +SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], + 1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']} + +def approximate_size(size, a_kilobyte_is_1024_bytes=True): + '''Convert a file size to human-readable form. + + Keyword arguments: + size -- file size in bytes + a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024 + if False, use multiples of 1000 + + Returns: string + + ''' + if size < 0: + raise ValueError('number must be non-negative') + + multiple = 1024 if a_kilobyte_is_1024_bytes else 1000 + for suffix in SUFFIXES[multiple]: + size /= multiple + if size < multiple: + return '{0:.1f} {1}'.format(size, suffix) + + raise ValueError('number too large') + +if __name__ == '__main__': + print(approximate_size(1000000000000, False)) + print(approximate_size(1000000000000)) + + # Copyright (c) 2009, Mark Pilgrim, All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. diff --git a/students/Boundb3/Session 01/first test file b/students/Boundb3/Session 01/first test file new file mode 100644 index 0000000..a6499f8 --- /dev/null +++ b/students/Boundb3/Session 01/first test file @@ -0,0 +1,16 @@ +def test(a): + if a == 5: + print("that's the value I'm looking for!") + elif a == 7: + print("that's an OK number") + else: + print("that number won't do!") + + test(5) +that's the value I'm looking for! + +In [14]: test(7) +that's an OK number + +In [15]: test(14) +that number won't do! \ No newline at end of file diff --git a/students/Boundb3/Session 01/lab 2 money redict.py b/students/Boundb3/Session 01/lab 2 money redict.py new file mode 100644 index 0000000..f909fea --- /dev/null +++ b/students/Boundb3/Session 01/lab 2 money redict.py @@ -0,0 +1,93 @@ +#Brennen Bounds +#Python: Rick Riehle Hsi-Kai Yang +#Jan 20,2016 + + +#Staring DICTIONARY - but order of access to ask the values is random!!*** + +# This is program to determine whether a mix of coins can make EXACTLY one dollar. +# Your program should prompt users to enter the number of pennies, nickels, dimes, and quarters. +# If the total value of the coins entered is equal to one dollar, +# the program should congratulate users for winning the game. +# Otherwise, the program should display a message indicating whether the amount entered +# was more than or less than a dollar. + + +'''variables: +coin = local placeholder in def +answer = receipt of coin value from def + +''' + +#money = value of all of the change +#ttlanswer = money variable rounded to 2 decimals''' + +#coindict={} a dictionary to hold the 4 types of coins and their quantity (default value of zero for each key) + +count = 0 +import math + +#routine to collect the number of coins from a user for a coin type + +def get_quantity(coin = .5): + count = 0 + + while type(coin) != int: + try: + coin = int(input("\tType how many you have here:")) + + except (TypeError, ValueError) as e: + print ("Your entry: ", e, " is not a positive whole number. Please enter a positive whole number.") + coin = .5 + count +=1 + if count == 5: + print("Sorry, your entry was not a whole number. Let's quit the game. Good bye?") + quit() + if coin < 0: + print("Really? I don't think you have negative coins. You need to enter a positive whole number. Try this coin again.") + coin = .5 + print(locals()) + return coin + + + +#Welcome +print ("\n\t\tWelcome Money Player! \n\n This challenge will determine if your spare change \n " + "equals one dollar exactly -- or not. Ready....? Let's try!") +print ("\n\nYou can tell me the number of each coin type you have, " + "and I will test the value to see how close you are to 1 dollar.") + + +print("I will ask you what quantity of coins you have for each coin type: penny, nickel, dime and quarter.") + + +# set coin types and establish default quantities +coindict = {"pennies": 0 ,"nickles": 0,"dimes": 0,"quarters": 0} + + +# collect coin quantites from user *** note a dictionary will produce question in a random order -- +# so be careful to watch the coin type in the question + +for i in coindict: # this will be a random key value out of the total number of items in the dictionary + print("\n") + print("\tOk, how many" , i, "do you have?" ) #and "i" here is actually the name of the dictionary key + answer = get_quantity() + print("\t\tThanks - got it. You had ", answer, i,".") + coindict[i] = answer # condict[i] is the key name, and we are assigning a new value (to replace 0)to that key here + +# calculate total value and limit to 2 decimals +# use a dictionary format to call the value of the dictionary key pair by calling the dictionary key + +money = (coindict.get("pennies") * .01) + (coindict.get("nickles") * .05) + (coindict.get("dimes") *.10) + (coindict.get("quarters") *.25) +ttlanswer = math.ceil(money * 100) / 100 + +# share results with user + +if ttlanswer == 1.00: + print("\n\tCongratulations you hit EXACTLY $1.00 on the nose!!") +elif ttlanswer > 1.00: + print("\n\tYour change totals to: $", ttlanswer, ". It is $", (ttlanswer - int(1)), "over one dollar.") +elif ttlanswer < 1.00: + print("\n\tYour change totals to: $", ttlanswer, ". It is $", (int(1) - ttlanswer), "under one dollar.") +else: + print("\n\tI don't think this worked right. Tell my programmer to take a look under the hood. Thanks, goodbye.") diff --git a/students/Boundb3/Session 01/lab 2 money retest.py b/students/Boundb3/Session 01/lab 2 money retest.py new file mode 100644 index 0000000..92d2b5c --- /dev/null +++ b/students/Boundb3/Session 01/lab 2 money retest.py @@ -0,0 +1,93 @@ +#Brennen Bounds +#Python: Rick Riehle Hsi-Kai Yang +#Jan 20,2016 + + +#Staring LISTS*** + +# This is program to determine whether a mix of coins can make EXACTLY one dollar. +# Your program should prompt users to enter the number of pennies, nickels, dimes, and quarters. +# If the total value of the coins entered is equal to one dollar, +# the program should congratulate users for winning the game. +# Otherwise, the program should display a message indicating whether the amount entered +# was more than or less than a dollar. + + +'''variables: +coin = placeholder +answer = receipt of coin value from def + + +''' + +#money = value of all of the change +#ttlanswer = money variable rounded to 2 decimals''' + +coinlist=[] +coincount=[] + +count = 0 + +import math + + +#routine to collect the number of coins from a user for a coin type + + +def get_quantity(coin = .5): + count = 0 + + while type(coin) != int: + try: + coin = int(input("\tType how many you have here:")) + + except (TypeError, ValueError) as e: + print ("Your entry: ", e, " is not a positive whole number. Please enter a positive whole number.") + coin = .5 + count +=1 + if count == 5: + print("Sorry, your entry was not a whole number. Let's quit the game. Good bye?") + quit() + if coin < 0: + print("Really? I don't think you have negative coins. You need to enter a positive whole number. Try this coin again.") + coin = .5 + return coin + + + +#Welcome +print ("\n\t\tWelcome Money Player! \n\n This challenge will determine if your spare change \n " + "equals one dollar exactly -- or not. Ready....? Let's try!") +print ("\n\nYou can tell me the number of each coin type you have, " + "and I will test the value to see how close you are to 1 dollar.") + + +# get coin quantities from user +print("I will ask you what quantity of coins you have for each coin type: penny, nickel, dime and quarter.") +coinlist = ["pennies","nickles","dimes","quarters"] +coincount = [0,0,0,0] + +length = len(coinlist) + +for i in range(length): #this value needs to be a number + print("\n") + print("\tOk, how many" , coinlist[i], "do you have?" ) + answer = get_quantity() + print("\t\tThanks - got it. You had ", answer, coinlist[i],".") + coincount[i] = answer + +# calculate total value and limit to 2 decimals + +money = (coincount[0]*.01) + (coincount[1]*.05) + (coincount[2] * .10) + (coincount[3]*.25) +ttlanswer = math.ceil(money * 100) / 100 + +# share results with user + +if ttlanswer == 1.00: + print("\n\tCongratulations you hit EXACTLY $1.00 on the nose!!") +elif ttlanswer > 1.00: + print("\n\tYour change totals to: $", ttlanswer, ". It is $", (ttlanswer - int(1)), "over one dollar.") +elif ttlanswer < 1.00: + print("\n\tYour change totals to: $", ttlanswer, ". It is $", (int(1) - ttlanswer), "under one dollar.") +else: + print("\n\tI don't think this worked right. Tell my programmer to take a look under the hood. Thanks, goodbye.") diff --git a/students/Boundb3/Session 01/play jan 20 2016.py b/students/Boundb3/Session 01/play jan 20 2016.py new file mode 100644 index 0000000..efca996 --- /dev/null +++ b/students/Boundb3/Session 01/play jan 20 2016.py @@ -0,0 +1 @@ +import \ No newline at end of file diff --git a/students/Boundb3/Session 02/Week2Play.py b/students/Boundb3/Session 02/Week2Play.py new file mode 100644 index 0000000..df711bc --- /dev/null +++ b/students/Boundb3/Session 02/Week2Play.py @@ -0,0 +1,18 @@ +'''def is_it_true(xyz): + if(xyz): + print("yes there was something there") + else: + print("nothing was passed in") + +is_it_true([4]) + +''' + +def do_twice(f,printstuff): + f(printstuff) + f(printstuff) + +def print_spam(b): + print(b) + +do_twice(print_spam,"printthiss") diff --git a/students/Boundb3/Session 02/mypolygon.py b/students/Boundb3/Session 02/mypolygon.py new file mode 100644 index 0000000..97f2b09 --- /dev/null +++ b/students/Boundb3/Session 02/mypolygon.py @@ -0,0 +1,59 @@ + +import turtle +bob = turtle.Turtle() +alice = turtle.Turtle() + + +def rectangle(t,length,width): + + for i in range(2): + t.fd(length) + t.lt(90) + t.fd(width) + t.lt(90) + print(bob) + turtle.mainloop() + +def mypolygon(t,sides,length): + angle = 360 /sides + t.fd(length/8) + for i in range(sides): + t.fd(length) + t.lt(angle) + print(alice) + turtle.mainloop() + + +def mycircle(t,radius,sides): + t.fd(radius) + for i in range(sides): + t.fd(radius*3/2) + t.lt(360/sides) + print(alice) + turtle.mainloop() + + +import math + + +def polygon(t, n, length): + angle = 360 / n + for i in range(n): + t.fd(length) + t.lt(angle) + + + +def circle(t,r): + circumference = 2*math.pi*r + n=50 + length = circumference/n + polygon(t,n,length) + + + + +#rectangle(bob,100,25) +#mycircle(alice,10,30) +#polygon(bob,7,70) +circle(bob,40) \ No newline at end of file diff --git a/students/Boundb3/Session 02/play_recursion.py b/students/Boundb3/Session 02/play_recursion.py new file mode 100644 index 0000000..a72510c --- /dev/null +++ b/students/Boundb3/Session 02/play_recursion.py @@ -0,0 +1,12 @@ + + +def countdown(n): + if n < 0: + print("plastoff") + else: + print(n) + countdown(n-1) + return n + +a=countdown(4) +print ("you started the countdown with {} ".format(a)) diff --git a/students/Boundb3/Session 02/series.py b/students/Boundb3/Session 02/series.py new file mode 100644 index 0000000..fb4cb5b --- /dev/null +++ b/students/Boundb3/Session 02/series.py @@ -0,0 +1,72 @@ + +''' + +Brennen Bounds +Python 100a + +Create a new module series.py in the session02 folder in your student folder. +In it, add a function called "fibonacci". + +The function should have one parameter n. +The function should return the nth value in the fibonacci series. + +add a new function "lucas" that returns the nth value in the lucas numbers series. + +then add a third function called sum_series with one required parameter and two optional parameters. +The required parameter will determine which element in the series to print. +The two optional parameters will have default values of 0 and 1 and will determine +the first two values for the series to be produced. + +Calling this function with no optional parameters will produce numbers from the fibonacci series. +Calling it with the optional arguments 2 and 1 will produce values from the lucas numbers. +Other values for the optional parameters will produce other series. + +Ensure that your function has a well-formed docstring + +''' + +def fibinacci_n(n): + """Return the nth value in a fibinacci series.""" + a,b =0,1 + #print (a) + for i in range(n-1): + a,b = b, a+b + #print (a) + return a + + +def lucas_n(n): + """Return the nth value in a Lucas series.""" + a,b =2,1 + #print (a) + for i in range(n-1): + a,b = b, a+b + #print (a) + return a + + +def sum_series(n, startnum1=0,startnum2=1): + """Return the nth value in a additive summation series given the two starting numbers. + The default series is the fibinacci series.""" + startnum1, startnum2 = startnum1, startnum2 + #print (a) + for i in range(n-1): + startnum1,startnum2 = startnum2, startnum1+startnum2 + #print (a) + return startnum1 + + +n = int(input("Type in the number of the nth value in the sequence you want.")) +assert (n>0), "Need to have a positve number for the nth value." + +startnum1 = int(input("Type in the starting number.")) +startnum2 = int(input("Type in the second starting number.")) +assert (startnum1 > 0 or startnum2 > 0), "Both starting numbers cannont have zero values." + +print("\n",fibinacci_n.__doc__, ":") +print ("\tThe", n, "'th number in the fibinacci sequence is: ", fibinacci_n(n)) +print("\n",lucas_n.__doc__, ":") +print ("\tThe", n, "'th number in the lucas sequence is: ",lucas_n(n)) +print("\n",sum_series.__doc__) +print ("\tThe", n, "'th number in a made up series is:",sum_series(n,startnum1,startnum2), "(for starting numbers:)",startnum1,startnum2) + diff --git a/students/Boundb3/Session 03/B_upMailroom.py b/students/Boundb3/Session 03/B_upMailroom.py new file mode 100644 index 0000000..1cc1138 --- /dev/null +++ b/students/Boundb3/Session 03/B_upMailroom.py @@ -0,0 +1,418 @@ +""" +#-------------------------------------------------# +# Title: Mailroom - Week3/4 assignment +# Dev: BBounds +# Date: February 14 2016 +#Class: Python 2016a +Instructor: Rick Riehle / TA: Summer Rae +#-------------------------------------------------# + + +Write a small command-line script called mailroom.py. This script should be executable. +The script should accomplish the following goals: + +It should have a data structure that holds a list of your donors and a history of the amounts +they have donated. This structure should be populated at first with at least five donors, with +between 1 and 3 donations each. The script should prompt the user (you) to choose from a menu of 2 actions: + Send a Thank You or Create a Report. + + +If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. + +Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. + +Finally, use string formatting to compose an email thanking the donor for their generous donation. +Print the email to the terminal and return to the original prompt. +It is fine to forget new donors once the script quits running. + +Creating a Report +If the user (you) selected "Create a Report" Print a list of your donors, sorted by total historical donation amount. +Include Donor Name, total donated, number of donations and average donation amount as values in each row. +Using string formatting, format the output rows as nicely as possible. The end result should be tabular +(values in each column should align with those above and below) +After printing this report, return to the original prompt. +At any point, the user should be able to quit their current task and return to the original prompt. ### NEED HELP HERE +From the original prompt, the user should be able to quit the script cleanly + + + +What I was not able to accomplish: + 1. to dig into the list of values and pull, say.. donation #2 of 3 from the list in the dictionary's value. + 2. I was not able to answer all my string formatting goals, but i did get pretty good results. for example, if I + start up a new print string, (continuing from a prior end="" print line, how do I create a buffer to tell the new print line where + to start printing using the format print string details. Also, how do these buffers all line up - for the title row and + detail row to fit (without trial and error) - do I count up the buffer spaces or something? + 3. was not able to get the sum of the dictionary values to fit in a report with the details of the donations in the same report in a simple way. + I had to use nested nested loops. + +""" + +# memo to run the file only if this is a main file + +if __name__ == "__main__": + print("Hi there - this is a main file and you can run this script from here.") +else: + raise Exception("This file was not created to be imported") + +# set up imaginary donor information for use in the script +# input made-up values into a dictionary - very inefficeint - better to pull from a file (but had problems) + +d1 = {("Sally Wood"): [50.00, 100.45, 75.24]} +d2 = {("Jim Nasium"): [150.00, 10.01]} +d3 = {("Bill Fold"): [45.00]} +d4 = {("Alice Wonder"): [10.00, 10.00, 25.02]} +d5 = {("Chuck Wheels"): [25.00, 25,25.14 ]} +d6 = {("No One"): [] } + +dictall ={} +dictall.update(d1) +dictall.update(d2) +dictall.update(d3) +dictall.update(d4) +dictall.update(d5) +dictall.update(d6) + +#play prints +#dictallsort_val = sorted(dictall,key=(dictall.get), reverse = True) # problem: this sorts on the first number, not the sum total + + +#user choice and menu driving functions: + +def pause_foruser(): + waitvalue = input("\nHit any key to proceed.") + +def num_Choice(question="Please input a numerical responce in the appropriate range", low=1, high=10): + """ask for a number within a range from user""" + choiceNum = None + try: + while choiceNum not in range(low, high): + choiceNum = int(input(question)) + except Exception as e: + print("Error in Choice: " + str(e)) + return str(choiceNum) + +def yornore_Choice(question= "Please input 'y' or 'n' for yes/no. "): + """ask for a yes or no answer from user""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + choiceYN = input(question) + if choiceYN == 'y' : print("\tOK - lets do that.", end=" ") + if choiceYN == 'n': print("\tOK - let's not do that. Lets go back.") + + except Exception as e: + print("Error in y/n choice: " + str(e)) + + return str(choiceYN) + +def verify_input (responce_to_check, question = "Is this '{}' correct? Please input 'y' or 'n' "): + """ask for a yes or no confirmation of the accuracy of the user's input""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + #allow user to see if there answer is typed correctly + choiceYN = input(question.format(responce_to_check)).lower() + #print("in verify input function: check to see the value of choice YN", choiceYN) + + if choiceYN == 'y' : + print("\tOK - accepted.", end=" ") + elif choiceYN == 'n': + print("\tOK - try to input that again.") + + return(choiceYN) + + except Exception as e: + print("Error in y/n choice: " + str(e)) + return None + +#core menu function: + +def menu_display(): + """Display the menu of choices""" + print (""" + Menu of Options: + ----------------- + 1) Send a Thank You letter + 2) Add a new Donor + 3) Add new Donations + 4) List Donors' Names + 5) Create a Donor Report + 6) Exit + + """) + +#data task functions: + +def get_donor_info(): + print("Lets get name data of the donor.") + fr_name = str(input("what is the first name of the donor?")).title() + la_name = str(input("what is the last name of the donor?")).title() + full_name = fr_name + " " + la_name + #print("this is the full name:", full_name) + return full_name + +def is_name_in_the_list(fullname,database = dictall): + if fullname.title() in dictall.keys(): + print("That donor is in the donor list.") + return ("yes") + else: + print("That donor is NOT currently in the donor list.") + return fullname + + +def split_fname(fullname): + fname, lname = fullname.split() + return fname + +def split_lname(fullname): + fname, lname = fullname.split() + return lname + +def add_name_to_db(fullname): + #print("in the addname to db function. this is the full name passed to this add name fucntion", fullname) + dictall[fullname] = [] #establish name with empty list for donaation + print("\tAdded {} to the donor database".format(fullname)) + return fullname + +def add_donation(fullname): + donation = None + while type(donation) != float: + try: + donation= float(input("What value of donation would you like to add for {}?".format(fullname))) + except ValueError as e: + print("wrong value type - use $$.CC format without commas") + except Exception as e: + print("please input you donation amount with $$.CC format") + print ("Adding a Donation for $: " , donation) + #print("fullname key's value before", dictall[fullname]) + dictall[fullname] = dictall[fullname] + [donation] + print("Here is a summary of {}'s donations now.".format(split_fname(fullname)), dictall[fullname]) + +def list_out_donors(): + s_dictall = sorted(dictall.items(),reverse = False) + print(""" + \t Donors: + \t--------""") + for donors, values in s_dictall: + print("\t\t",donors) + +def list_out_donors_and_donations(): + s2_dictall = sorted(dictall.items(),reverse = False) + print("{:^15}{:^45}".format("Name","Donations")) + print("-"*15, " "*15, "-"*15) + for k,v in s2_dictall: + print("{:<15} {:>30}".format(k,str(v))) + print("\n"*2) + +def print_report_sumtotal_summary(): + """Report of the total sum of donations per donor.""" + print("\n\nReport of donors by total historical contributions:") + + s2_dictall = sorted(dictall.items(),reverse = False) + + #create a new dictionary with same keyword name and value is the sum of donations + sumvalue_dict ={} + for k, tv in s2_dictall: + sumvalue_dict[k]= sum(tv) + + # now sort on the values in the new dictionary - to give a list of keys (keys only) by sum of donations + s_sumvalue_dict_list = sorted(sumvalue_dict,key=sumvalue_dict.get,reverse = True) + + #various print plays to see values + #print("this is s2 dictall: ", s2_dictall) + #print("this is the sorted value list: s sumvalue dict list ", s_sumvalue_dict_list) + #print("this is the new dictionary sumvalue dict ", sumvalue_dict) + + #begin print table + print("{:^15}{:^45}".format("Name","Donations | Details")) + print("-"*15, " "*15, "-"*20) + #print report contents for sorted donor by value of historical donations + for name in s_sumvalue_dict_list: + #print(name) + for n,v in sumvalue_dict.items(): + #print(n,v) + if name == n: + print("{:<20} {:>20.2f} ".format(name,v,),end="") + for k,l in dictall.items(): + if name == k: + #print("{:>60)}".format(str(dictall[k]))) + print(dictall[k]) + + # print("{:<15} {:>30}".format(k,str(v))) + #print("\n"*2) + + +def print_report(): + """Report of name, count, average, and sum total of donations by donor""" + print("Report of donor name, count, average, and sum total of their donations. " + "Sorted by Name - not able to determine sort by total donations!!!") + s_dictall = sorted(dictall.items(),reverse = False) #sorting list extract of dictionary items (by key alphebetized) + #print("this is s dictall before formatting: ", s_dictall) + print("{:<15}{:<8} {:^8} {:>10} ".format("Name","Count","Average","Sum Total")) + print("{:^38}".format("-"*46)) + for k,v in s_dictall: + if sum(v)>0: + print("{:<15} {:<8} ${:8.2f} ${:>10.2f}".format(k,len(v),(sum(v)/len(v)),sum(v)) ) + else: + print("{:<15} {:<8} ${:8.2f} ${:>10.2f}".format(k,len(v),0.0,sum(v)) ) + + + +def thank_you_email(fullname): + + fname = split_fname(fullname) + print(""" + Dear {}, + + It is such a pleasure to have you as a supporter. + + Your total donations of ${:.2f} have been critical to our mission. + + Regards, + + Duey How + + President """.format(fname,sum(dictall[fullname]))) + + +#start of MAIN + +# program welcome +print("\nWelcome to your Donor Management program.") + +#call the function that cooresponds to the users selection +while(True): + # call the menu screen first + print("\nAll your options operate through this main menu:") + menu_display() + + # call the choice function to get the users choice of action + #print("calling the choice function") #used for testing + strChoice = num_Choice("Please input your selection from 1-6:",1,7) + #verifiy choice selection - for routing tracking for debugging + #print("\n\tYour menu choice was: ",strChoice, "Got it.") + +#menu tasks: + + # if they choose selection 1 - send a thank you letter + if (strChoice == '1'): + print ("made it to choice {} : send a donor thank you letter".format(strChoice)) + + #provide a list for visibility + answer = input("do you want to see a list of donors to remind you of the donor's full name? Enter 'y' if you do.").lower() + if answer == 'y': + print("here is a recent list of donors.") + list_out_donors() + + #run routine to get name of the donor you would like to send a letter + fullname = get_donor_info() + + #let them know if donor is in database or not + check_name = is_name_in_the_list(fullname) + + #print out the thank you letter to screen if user in database + if check_name =="yes": + thank_you_email(fullname) + else: + print("\n {} in not in the database. Unable to write standard letter.".format(fullname)) + + pause_foruser() #pause for user to absorb message + continue + + # if they choose selection 2 - add a new donor + elif(strChoice == '2'): + print ("made it to choice {} : add a new donor".format(strChoice)) + + #start ruitine to collect the first and last name of the donor + new_donor_name = get_donor_info() + print (new_donor_name) + + # allow user to verify they typed the name correctly + happy_new_donor_name_yn = verify_input(new_donor_name) + + #if name is acceptable to user, see if it is already in the database of donors + if happy_new_donor_name_yn == "y": + dbcheck_name = is_name_in_the_list(new_donor_name,dictall) + else: #returning to main menu for re-try a name error (maybe misspelled) + print("Returning to main menu so you can try to re-enter your data.") + continue + + #add if new name is new, or return to menu if not a new name + if dbcheck_name == "yes": + print("That name, {}, is already on the list of donors.".format(dbcheck_name.title())) + continue + else: + print("Adding name to donor list.") + add_name_to_db(new_donor_name) + + + # if they choose selection 3 - add new donations for donor + elif(strChoice == '3'): + print ("made it to choice {}: add donation".format(strChoice)) + + #for user to find name + res = str(input("would you like to see a list of donors and their donations? y/n").lower()) + if res == 'y': + print("Here is list of donors with their current donations on record.") + list_out_donors_and_donations() + + #check to see if list is on the donor list + fullname = str(input("type in the full name of the donor.")) + + #reply from list + fullname_on_list = is_name_in_the_list(fullname) + + #if reply is not on list - prompt user to return to menu + if fullname_on_list == "yes": + res2 = 'n' + res2 = input("would you like to add donation for this user? y/n").lower() + while res2 == 'y': + add_donation(fullname.title()) + res2 = input("would you like to add another donation for this user? y/n").lower() + continue + + #if reply is on the list - then add donation for the user + else: + print("Name not found on donor list. Please enter donor into system first") + continue + + + # if they choose selection 4 - print list of donor names + elif(strChoice == '4'): + print ("made it to choice {} : print list of donor names".format(strChoice)) + + list_out_donors() + + pause_foruser() + continue + + # if they choose selection 5 - output donor report + elif(strChoice == '5'): + print ("You made it to choice {}: Output Donor report".format(strChoice)) + print_report() + print_report_sumtotal_summary() + + + pause_foruser() + continue + # if they choose selection 6 - exit + elif(strChoice == '6'): + print ("You made it to choice {} : exit".format(strChoice)) + choice = yornore_Choice("\tAre you sure you want to exit? ") + if choice == "y": + print("\n\tElvis has left the building. Good bye.") + break + else: + print("\nOK, Lets go back to the menu.") + continue + else: + print("You should not have made it to here. There must be a problem in the while loop.") + break + +#salutation to the user +print("\nSee you next time.") diff --git a/students/Boundb3/Session 03/Mailroom name import technique.py b/students/Boundb3/Session 03/Mailroom name import technique.py new file mode 100644 index 0000000..536614e --- /dev/null +++ b/students/Boundb3/Session 03/Mailroom name import technique.py @@ -0,0 +1,35 @@ +# or compare to a second way to prep the dictionary +objFileName = "C:\Python_100a\IntroPython2016a\students\Boundb3\Textfiles\Mail_List_status_W4.txt" +strData = "" +dicTable = {} + +#read in the lines from text file and populate a dictionary. + # problem *** they are now each strings, not tuple and list for the key and values respectively*** + +objFile = open(objFileName, "r") +for line in objFile: + strData = line # readline() reads a line of the data + lstData = strData.split(":") # divide the data into 2 elements - 1 preped for keys (tuple) and 2nd preped for [list] + dicTable[lstData[0].strip()] = lstData[1].strip() +objFile.close() + +dicTableCopy.update(dicTable) # cant iterate over a dictionary - so this does not work + +for strKey, strValue in dicTablecopy.items(): + print ("type of strKey is", type(strKey), strKey) + nameo = strKey.split(",") + print ("type of nameo is", type(nameo)) + print(nameo[0]," ", nameo[1]," ",nameo[2]) + + + print ("nameo 0 is",nameo[0].strip('""'),"nameo 1 is", nameo[1].strip('""'), "nameo 2 is ", nameo[2].strip('""')) + #print(strKey + " / " + strValue + "\t") + #print("type ofkey",type(strKey)) + print("type ofvalue",type(strValue)) + + + +if "Sally, Wood, Ms." in dicTable.keys(): print("yes we have sally") + + + diff --git a/students/Boundb3/Session 03/Mailroom.py b/students/Boundb3/Session 03/Mailroom.py new file mode 100644 index 0000000..8e1e606 --- /dev/null +++ b/students/Boundb3/Session 03/Mailroom.py @@ -0,0 +1,327 @@ +""" +#-------------------------------------------------# +# Title: Mailroom - Week3/4 assignment +# Dev: BBounds +# Date: February 1 2016 +#Class: Python 2016a +Instructor: Rick Riehle / TA: Summer Rae +#-------------------------------------------------# + + +Write a small command-line script called mailroom.py. This script should be executable. +The script should accomplish the following goals: + +It should have a data structure that holds a list of your donors and a history of the amounts +they have donated. This structure should be populated at first with at least five donors, with + + +between 1 and 3 donations each +The script should prompt the user (you) to choose from a menu of 2 actions: + Send a Thank You or Create a Report. + + +If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. + +Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. + +Finally, use string formatting to compose an email thanking the donor for their generous donation. +Print the email to the terminal and return to the original prompt. +It is fine to forget new donors once the script quits running. + +Creating a Report +If the user (you) selected "Create a Report" Print a list of your donors, sorted by total historical donation amount. +Include Donor Name, total donated, number of donations and average donation amount as values in each row. +Using string formatting, format the output rows as nicely as possible. The end result should be tabular +(values in each column should align with those above and below) +After printing this report, return to the original prompt. +At any point, the user should be able to quit their current task and return to the original prompt. ### NEED HELP HERE +From the original prompt, the user should be able to quit the script cleanly + + +""" +# memo to run the file only if this is a main file + +if __name__ == "__main__": + print("hi there - this is a main file and can run this script directly") +else: + raise Exception("This file was not created to be imported") +# set up imaginary donor information for use in the script +dictall ={} + + +# input made-up values into a dictionary - very inefficeint - better to pull from a file (but had problems) + +d1 = {("Sally", "Wood", "Ms."): [50.00, 100.45, 75.25]} +d2 = {("Jim", "Nasium", "Mr."): [150.00, 10.00]} +d3 = {("Bill", "Fold", "Mr."): [45.00]} +d4 = {("Alice", "Wonder", "Mrs."): [10.00, 10.00, 25.00]} +d5 = {("Chuck", "Wheels", "Mr."): [25.00, 25,25 ]} +d6 = {("no", "one", "yet"): [] } +dictnamelist = ["d1","d2","d3","d4","d5","d6"] +dictall.update(d1) +dictall.update(d2) +dictall.update(d3) +dictall.update(d4) +dictall.update(d5) +dictall.update(d6) + +print ("dictall = ",dictall) + + +# for fun, unpack the key and make a new key in a new dictionary with re-ordered values (like in a letter) +dictsalutation = {} + +def print_report(): + + srtdictall = {} + #srtdictall = sorted(dictall,key= sum(list(dictall.values()))) *** need to figure out sort by value + print("\n\t Donor's Report: \n\t _________________\n") + for tplKey, lstValue in dictall.items(): + donations = 0 + count = 0 + #print(strKey + " / " + strValue + "\t") + #print("type ofkey",type(strKey)) + firstn = tplKey[0] + lastn = tplKey[1] + saluten = tplKey[2] + nameall = saluten + " " + firstn + " " + lastn + dictsalutation[nameall] = lstValue + #print( "Dear", nameall) + #print("type of value",type(lstValue)) + donations = sum(lstValue) + count = (len(lstValue)) + try: + avg_donation = donations/count + except ZeroDivisionError: + avg_donation = 0 + + except Exception as e: + print(e) + + print("{} {} has made {:d} donation(s) for a total of ${:f}" + "which is an ave of {:f}".format(firstn,lastn,count,donations,avg_donation)) + + input("\n\ttype any key to continue") + +print(dictall) +print("*****") +print(dictsalutation) +print("***** - now sorted") +print(sorted(dictsalutation)) +print("***** - now back to unsorted - is it still there?") +print(dictsalutation) + + + +''' +def problem_user(): + print("you stink. ") + return + +#def verify(a, count = 0): + like = "no" + print("You entered: ", a) + like = input("Is this correct? Hit 'enter'' for yes or type 'no'").lower + if like == "" or like == "yes": + return a + else: + new_a = input("please input your data again: ") + count +=1 + if count == 3: + print("you seem to be having problems.") + problem_user() + verify(new_a) +''' + +def print_thanks(donors_fullname): + print("Thank you ",donors_fullname) + print("need to format a thank ou letter") + +def add_new_donor(): + donor_fname = input("What is the new donor's first name?").title + f = (donor_fname) + donor_lastn = input("What is the new donor's last name?").title + l = (donor_lastn) + donor_salutation = input("What is the donor's salutation for a letter? i.e: Mr. or Mrs?").title + mr =(donor_salutation) + key = (f , l , mr) + print("the type of key created to dictionary is: ", type(key), "is" , key) + return (key) + +def add_new_donor_to_dictionary(unposted_new_donor): + if unposted_new_donor in dictall: + print("name already in dictionary.") + return + else: + dictall[unposted_new_donor] = [] #update the dictionary with a new key with empty list value + dictsalutation[unposted_new_donor] = [] #update the salutation dictionary too (with new key with empty list value + message = "Completed set up of new donor (added to dictionary):" + print ("{} {}".format(message,unposted_new_donor)) + return unposted_new_donor + + +"""Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. +""" + +def add_new_donations(key_name): + new_donation_Q= input("Has {} provided a new donation? Type 'yes' or 'no'".format(key_name)).lower + a= verify(new_donation_Q) + if key_name in dictall: + + lstValueNew =[] + if a == "yes": + donation_amount = int(input("What is the amount of the donation?")) + try: + b = int(verify(new_donation_Q)) + except Exception as e: + print(e, "is not a valid number. value not excepted" ) + return None + lstValueNew.append(b) + + dictall[key_name] = lstValue + dictsalutation[key_name] = lstValue + print("Ive updated that: Donor {} provided {:d} in a donation").format(key_name,lstValue) + else: + print("name {} not found. Try again.". format(key_name)) + + return + +def list_donors(): + ''' screen print list of donors in a table''' + print("temp# \t donor name \t\t donation history \n " + "--------------------------------------------------------") + count = 0 + for tplkey,lstvalue in sorted(dictsalutation.items()): + print ("No: {} \t {} \t\t {}".format((count+1),tplkey,lstvalue),sep="\t\t") + count += 1 + input("\n\ttype enter to proceed") + +# create a menu +while(True): + print (""" + Menu of Options: + ----------------- + 1) Send a Thank You letter + 2) Add a new Donor + 3) Add new Donations + 4) List Donors + 5) Create a Report + 6) Exit + + """) + strChoice = str(input("Which option would you like to perform? [1 to 6]")) + + # 1 send thank you letter + + ''' + If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. +''' + if (strChoice == '1'): + full_name = input("Please enter the:" + "1)full name and title of the donor, or" + "2)'list' to see a list of donors, or" + "3)'exit' to quit ").title + if full_name == "exit": + break + elif full_name == "list": + list_donors() + continue + + elif full_name in dictsalutation: + print("found it in dictsalutation") + print_thanks(full_name) + continue + else: + #********* + print("I do not see this name in the list.") + full_name = verify(full_name) + answer = input("Would you like to try again or add {} name to the list?".format(full_name)) + if answer == "try again": + break + else: + print("Ok, We will add {} to the list. Lets collect the details one at a time.".format(full_name)) + created_new_donor_tpl = add_new_donor() + add_new_donations(created_new_donor_tpl) + print_thanks(created_new_donor_tpl) + + + + # 2 add new donor + elif(strChoice == '2'): + print("please check that the donor is not already on the list") + list_donors() + answer = input("do you still want to add the new donor? Type yes or no") + a = (answer) + if a == 'yes': + add_new_donor() + continue + + + #3 add new donation + elif(strChoice == '3'): + print("please find your donor on the list below") + list_donors() + keynametry = input("please type the donors full name") + add_new_donations(keynametry) + continue + + + #4 list donors + elif(strChoice == '4'): + print("here is a list of donors") + list_donors() + continue + + #5 create a report + elif(strChoice == '5'): + print_report() + continue + + + #6 Quit + elif(strChoice == '6'): + print("Thank you. Have a good day.") + break + + + +''' + + +print (dictall) + + + + +print (d5.keys()) +print (d4.items()) +print (d3.values()) + +for strKey, strValue in dicTable.items(): + print(strKey) + strKeyToRemove = input("Which item would you like removed?") + if(strKeyToRemove in dicTable): + del dicTable[strKeyToRemove] + else: + print("I'm sorry, but I could not find that item.") + print(dicTable) #For testing + continue + + + elif(strChoice == '6'): + objFile = open(objFileName, "w") + for strKey, strValue in dicTable.items(): + objFile.write(strKey + "," + strValue + "\n") + objFile.close() + break +''' diff --git a/students/Boundb3/Session 03/Mailroom_b3.py b/students/Boundb3/Session 03/Mailroom_b3.py new file mode 100644 index 0000000..2d1557d --- /dev/null +++ b/students/Boundb3/Session 03/Mailroom_b3.py @@ -0,0 +1,421 @@ +""" +#-------------------------------------------------# +# Title: Mailroom - Week3/4 assignment +# Dev: BBounds +# Date: February 14 2016 +#Class: Python 2016a +Instructor: Rick Riehle / TA: Summer Rae +#-------------------------------------------------# + + +Write a small command-line script called mailroom.py. This script should be executable. +The script should accomplish the following goals: + +It should have a data structure that holds a list of your donors and a history of the amounts +they have donated. This structure should be populated at first with at least five donors, with +between 1 and 3 donations each. The script should prompt the user (you) to choose from a menu of 2 actions: + Send a Thank You or Create a Report. + + +If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. + +Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. + +Finally, use string formatting to compose an email thanking the donor for their generous donation. +Print the email to the terminal and return to the original prompt. +It is fine to forget new donors once the script quits running. + +Creating a Report +If the user (you) selected "Create a Report" Print a list of your donors, sorted by total historical donation amount. +Include Donor Name, total donated, number of donations and average donation amount as values in each row. +Using string formatting, format the output rows as nicely as possible. The end result should be tabular +(values in each column should align with those above and below) +After printing this report, return to the original prompt. +At any point, the user should be able to quit their current task and return to the original prompt. ### NEED HELP HERE +From the original prompt, the user should be able to quit the script cleanly + + + +What I was not able to accomplish: + 1. to dig into the list of values and pull, say.. donation #2 of 3 from the list in the dictionary's value. + 2. I was not able to answer all my string formatting goals, but i did get pretty good results. for example, if I + start up a new print string, (continuing from a prior end="" print line, how do I create a buffer to tell the new print line where + to start printing using the format print string details. Also, how do these buffers all line up - for the title row and + detail row to fit (without trial and error) - do I count up the buffer spaces or something? + 3. was not able to get the sum of the dictionary values to fit in a report with the details of the donations in the same report in a simple way. + I had to use nested nested loops. **from dive into python3 - 2.7.3: call the key and then the item so: dict[key][value item index], but this results in a tuple index out of range - IndexError + + +""" + +# memo to run the file only if this is a main file + +if __name__ == "__main__": + print("Hi there - this is a main file and you can run this script from here.") +else: + raise Exception("This file was not created to be imported") + +# set up imaginary donor information for use in the script +# input made-up values into a dictionary - very inefficeint - better to pull from a file (but had problems) + +d1 = {("Sally Wood"): [50.00, 100.45, 75.24]} +d2 = {("Jim Nasium"): [150.00, 10.01]} +d3 = {("Bill Fold"): [45.00]} +d4 = {("Alice Wonder"): [10.00, 10.00, 25.02]} +d5 = {("Chuck Wheels"): [25.00, 25,25.14 ]} +d6 = {("No One"): [] } + +dictall ={} +dictall.update(d1) +dictall.update(d2) +dictall.update(d3) +dictall.update(d4) +dictall.update(d5) +dictall.update(d6) + +#play prints +#dictallsort_val = sorted(dictall,key=(dictall.get), reverse = True) # problem: this sorts on the first number, not the sum total + + +#user choice and menu driving functions: + +def pause_foruser(): + waitvalue = input("\nHit any key to proceed.") + +def num_Choice(question="Please input a numerical responce in the appropriate range", low=1, high=10): + """ask for a number within a range from user""" + choiceNum = None + try: + while choiceNum not in range(low, high): + choiceNum = int(input(question)) + except Exception as e: + print("Error in Choice: " + str(e)) + return str(choiceNum) + +def yornore_Choice(question= "Please input 'y' or 'n' for yes/no. "): + """ask for a yes or no answer from user""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + choiceYN = input(question) + if choiceYN == 'y' : print("\tOK - lets do that.", end=" ") + if choiceYN == 'n': print("\tOK - let's not do that. Lets go back.") + + except Exception as e: + print("Error in y/n choice: " + str(e)) + + return str(choiceYN) + +def verify_input (responce_to_check, question = "Is this '{}' correct? Please input 'y' or 'n' "): + """ask for a yes or no confirmation of the accuracy of the user's input""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + #allow user to see if there answer is typed correctly + choiceYN = input(question.format(responce_to_check)).lower() + #print("in verify input function: check to see the value of choice YN", choiceYN) + + if choiceYN == 'y' : + print("\tOK - accepted.", end=" ") + elif choiceYN == 'n': + print("\tOK - try to input that again.") + + return(choiceYN) + + except Exception as e: + print("Error in y/n choice: " + str(e)) + return None + +#core menu function: + +def menu_display(): + """Display the menu of choices""" + print (""" + Menu of Options: + ----------------- + 1) Send a Thank You letter + 2) Add a new Donor + 3) Add new Donations + 4) List Donors' Names + 5) Create a Donor Report + 6) Exit + + """) + +#data task functions: + +def get_donor_info(): + print("Lets get name data of the donor.") + fr_name = str(input("what is the first name of the donor?")).title() + la_name = str(input("what is the last name of the donor?")).title() + full_name = fr_name + " " + la_name + #print("this is the full name:", full_name) + return full_name + +def is_name_in_the_list(fullname,database = dictall): + if fullname.title() in dictall.keys(): + print("That donor is in the donor list.") + return ("yes") + else: + print("That donor is NOT currently in the donor list.") + return fullname + + +def split_fname(fullname): + fname, lname = fullname.split() + return fname + +def split_lname(fullname): + fname, lname = fullname.split() + return lname + +def add_name_to_db(fullname): + #print("in the addname to db function. this is the full name passed to this add name fucntion", fullname) + dictall[fullname] = [] #establish name with empty list for donaation + print("\tAdded {} to the donor database".format(fullname)) + return fullname + +def add_donation(fullname): + donation = None + while type(donation) != float: + try: + donation= float(input("What value of donation would you like to add for {}?".format(fullname))) + except ValueError as e: + print("wrong value type - use $$.CC format without commas") + except Exception as e: + print("please input you donation amount with $$.CC format") + print ("Adding a Donation for $: " , donation) + #print("fullname key's value before", dictall[fullname]) + dictall[fullname] = dictall[fullname] + [donation] + print("Here is a summary of {}'s donations now.".format(split_fname(fullname)), dictall[fullname]) + +def list_out_donors(): + s_dictall = sorted(dictall.items(),reverse = False) + print(""" + \t Donors: + \t--------""") + for donors, values in s_dictall: + print("\t\t",donors) + +def list_out_donors_and_donations(): + s2_dictall = sorted(dictall.items(),reverse = False) + print("{:^15}{:^45}".format("Name","Donations")) + print("-"*15, " "*15, "-"*15) + for k,v in s2_dictall: + print("{:<15} {:>30}".format(k,str(v))) + print("\n"*2) + +def print_report_sumtotal_summary(): + """Report of the total sum of donations per donor.""" + print("\n\nReport of donors by total historical contributions:") + + s2_dictall = sorted(dictall.items(),reverse = False) + + #create a new dictionary with same keyword name and value is the sum of donations + sumvalue_dict ={} + for k, tv in s2_dictall: + sumvalue_dict[k]= sum(tv) + + # now sort on the values in the new dictionary - to give a list of keys (keys only) by sum of donations + s_sumvalue_dict_list = sorted(sumvalue_dict,key=sumvalue_dict.get,reverse = True) + + #various print plays to see values + #print("this is s2 dictall: ", s2_dictall) + #print("this is the sorted value list: s sumvalue dict list ", s_sumvalue_dict_list) + #print("this is the new dictionary sumvalue dict ", sumvalue_dict) + + #begin print table + print("{:^15}{:^45}".format("Name","Donations | Details")) + print("-"*15, " "*15, "-"*20) + #print report contents for sorted donor by value of historical donations + for name in s_sumvalue_dict_list: + #print(name) + for n,v in sumvalue_dict.items(): + #print(n,v) + if name == n: + print("{:<20} {:>20.2f} ".format(name,v,),end="") + for k,l in dictall.items(): + if name == k: + #print("{:>60)}".format(str(dictall[k]))) + print(dictall[k]) + + # print("{:<15} {:>30}".format(k,str(v))) + #print("\n"*2) + + +def print_report(): + """Report of name, count, average, and sum total of donations by donor""" + print("Report of donor name, count, average, and sum total of their donations. " + "Sorted by Name - not able to determine sort by total donations!!!") + s_dictall = sorted(dictall.items(),reverse = False) #sorting list extract of dictionary items (by key alphebetized) + #print("this is s dictall before formatting: ", s_dictall) + print("{:<15}{:<8} {:^8} {:>10} ".format("Name","Count","Average","Sum Total")) + print("{:^38}".format("-"*46)) + for k,v in s_dictall: + if sum(v)>0: + print("{:<15} {:<8} ${:8.2f} ${:>10.2f}".format(k,len(v),(sum(v)/len(v)),sum(v)) ) + else: + print("{:<15} {:<8} ${:8.2f} ${:>10.2f}".format(k,len(v),0.0,sum(v)) ) + + + +def thank_you_email(fullname): + + fname = split_fname(fullname) + print(""" + Dear {}, + + It is such a pleasure to have you as a supporter. + + Your total donations of ${:.2f} have been critical to our mission. + + Regards, + + Duey How + + President """.format(fname,sum(dictall[fullname]))) + + +#start of MAIN + +# program welcome +print("\nWelcome to your Donor Management program.") + +#call the function that cooresponds to the users selection +while(True): + # call the menu screen first + print("\nAll your options operate through this main menu:") + menu_display() + + # call the choice function to get the users choice of action + #print("calling the choice function") #used for testing + strChoice = num_Choice("Please input your selection from 1-6:",1,7) + #verifiy choice selection - for routing tracking for debugging + #print("\n\tYour menu choice was: ",strChoice, "Got it.") + +#menu tasks: + + # if they choose selection 1 - send a thank you letter + if (strChoice == '1'): + print ("made it to choice {} : send a donor thank you letter".format(strChoice)) + + #provide a list for visibility + answer = input("do you want to see a list of donors to remind you of the donor's full name? Enter 'y' if you do.").lower() + if answer == 'y': + print("here is a recent list of donors.") + list_out_donors() + + #run routine to get name of the donor you would like to send a letter + fullname = get_donor_info() + + #let them know if donor is in database or not + check_name = is_name_in_the_list(fullname) + + #print out the thank you letter to screen if user in database + if check_name =="yes": + thank_you_email(fullname) + else: + print("\n {} in not in the database. Unable to write standard letter.".format(fullname)) + + pause_foruser() #pause for user to absorb message + continue + + # if they choose selection 2 - add a new donor + elif(strChoice == '2'): + print ("made it to choice {} : add a new donor".format(strChoice)) + + #start ruitine to collect the first and last name of the donor + new_donor_name = get_donor_info() + print (new_donor_name) + + # allow user to verify they typed the name correctly + happy_new_donor_name_yn = verify_input(new_donor_name) + + #if name is acceptable to user, see if it is already in the database of donors + if happy_new_donor_name_yn == "y": + dbcheck_name = is_name_in_the_list(new_donor_name,dictall) + else: #returning to main menu for re-try a name error (maybe misspelled) + print("Returning to main menu so you can try to re-enter your data.") + continue + + #add if new name is new, or return to menu if not a new name + if dbcheck_name == "yes": + print("That name, {}, is already on the list of donors.".format(dbcheck_name.title())) + continue + else: + print("Adding name to donor list.") + add_name_to_db(new_donor_name) + + + # if they choose selection 3 - add new donations for donor + elif(strChoice == '3'): + print ("made it to choice {}: add donation".format(strChoice)) + + #for user to find name + res = str(input("would you like to see a list of donors and their donations? y/n").lower()) + if res == 'y': + print("Here is list of donors with their current donations on record.") + list_out_donors_and_donations() + + #check to see if list is on the donor list + fullname = str(input("type in the full name of the donor.")) + + #reply from list + fullname_on_list = is_name_in_the_list(fullname) + + #if reply is not on list - prompt user to return to menu + if fullname_on_list == "yes": + res2 = 'n' + res2 = input("would you like to add donation for this user? y/n").lower() + while res2 == 'y': + add_donation(fullname.title()) + res2 = input("would you like to add another donation for this user? y/n").lower() + continue + + #if reply is on the list - then add donation for the user + else: + print("Name not found on donor list. Please enter donor into system first") + continue + + + # if they choose selection 4 - print list of donor names + elif(strChoice == '4'): + print ("made it to choice {} : print list of donor names".format(strChoice)) + + list_out_donors() + + pause_foruser() + continue + + # if they choose selection 5 - output donor report + elif(strChoice == '5'): + print ("You made it to choice {}: Output Donor report".format(strChoice)) + print_report() + print_report_sumtotal_summary() + + + pause_foruser() + continue + # if they choose selection 6 - exit + elif(strChoice == '6'): + print ("You made it to choice {} : exit".format(strChoice)) + choice = yornore_Choice("\tAre you sure you want to exit? ") + if choice == "y": + print("\n\tElvis has left the building. Good bye.") + break + else: + print("\nOK, Lets go back to the menu.") + continue + else: + print("You should not have made it to here. There must be a problem in the while loop.") + break + +#salutation to the user +print("\nSee you next time.") + + diff --git a/students/Boundb3/Session 03/Mailroom_newB3.py b/students/Boundb3/Session 03/Mailroom_newB3.py new file mode 100644 index 0000000..daa70b1 --- /dev/null +++ b/students/Boundb3/Session 03/Mailroom_newB3.py @@ -0,0 +1,364 @@ + +''' +this is to make a clean start on mailroom 2-13-15 +''' + + +# memo to run the file only if this is a main file + +if __name__ == "__main__": + print("hi there - this is a main file and can run this script directly") +else: + raise Exception("This file was not created to be imported") + +# set up imaginary donor information for use in the script +# input made-up values into a dictionary - very inefficeint - better to pull from a file (but had problems) + +d1 = {("Sally Wood"): [50.00, 100.45, 75.25]} +d2 = {("Jim Nasium"): [150.00, 10.00]} +d3 = {("Bill Fold"): [45.00]} +d4 = {("Alice Wonder"): [10.00, 10.00, 25.00]} +d5 = {("Chuck Wheels"): [25.00, 25,25 ]} +d6 = {("No One"): [] } +dictnamelist = [d1,d2,d3,d4,d5,d6] +dictnametuple = (d1,d2,d3,d4,d5,d6) + +dictall ={} +dictall.update(d1) +dictall.update(d2) +dictall.update(d3) +dictall.update(d4) +dictall.update(d5) +dictall.update(d6) + +dictallsort_val = sorted(dictall,key=dictall.get, reverse = True) # problem: this sorts on the first number, not the sum total + +for v in sorted (dictall,key = dictall.get, reverse = True): + print ("for v in sorted by Value:", v, dictall[v]) + tsum = ( "sum of value = ", sum(dictall[v])) + print (tsum) +#sumzip = zip (tsum,dictallsort_val) +#print(sumzip[3], sumzip[4]) + + + +dictallsort_key = sorted(dictall, reverse = False) + +for k in sorted (dictall, reverse = False): + print ("for k in sorted by Key " , k, dictall[k]) + +print ("dictall = ",dictall) +print("dictnamelist =",dictnamelist) +print("dictnametuple = ", dictnametuple) +print("sorted dictallsort_val = ",dictallsort_val ) + +''' +for x,y in d2: + d2value = d2.get(x,y) + print (x ,y) + print(d2value) + +easyvalue = d2.get("Jim", "Nasium") +print(easyvalue) +#sumd2 = sum(d2.values()) +#print(sumd2) + +k,v = dictall.keys(), dictall.values() +print("this isk:", k) +print ("this is v" , v) + + +d2a= (d2[1]) +print (d2a) +''' + +print(sum(dictall["Jim Nasium"])) +print(dictnamelist[1]) + + + +#user choice and menu driving functions: + + +def pause_foruser(): + waitvalue = input("\nHit any key to proceed.") + +def num_Choice(question="Please input a numerical responce in the appropriate range", low=1, high=10): + """ask for a number within a range from user""" + choiceNum = None + try: + while choiceNum not in range(low, high): + choiceNum = int(input(question)) + except Exception as e: + print("Error in Choice: " + str(e)) + return str(choiceNum) + +def yornore_Choice(question= "Please input 'y' or 'n' for yes/no. "): + """ask for a yes or no answer from user""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + choiceYN = input(question) + if choiceYN == 'y' : print("\tOK - lets do that.", end="") + if choiceYN == 'n': print("\tOK - let's not do that. Lets go back.") + + + except Exception as e: + print("Error in y/n choice: " + str(e)) + return str(choiceYN) + +def verify_input (responce_to_check, question = "Is this '{}' correct? Please input 'y' or 'n' "): + """ask for a yes or no confirmation of input""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + #allow user to see if there answer is good + choiceYN = input(question.format(responce_to_check)).lower() + print("check to see the value of choice YN", choiceYN) + + if choiceYN == 'y' : + print("\tOK - accepted.", end=" ") + elif choiceYN == 'n': + print("\tOK - try to input that again.") + + return(choiceYN) + + except Exception as e: + print("Error in y/n choice: " + str(e)) + return None + +#core menu function: + +def menu_display(): + """Display the menu of choices""" + print (""" + Menu of Options: + ----------------- + 1) Send a Thank You letter + 2) Add a new Donor + 3) Add new Donations + 4) List Donors' Names + 5) Create a Donor Report + 6) Exit + + """) + +#data task functions: + +def get_donor_info(): + print("Lets get name data of the donor.") + fr_name = str(input("what is the first name of the donor?")).title() + la_name = str(input("what is the last name of the donor?")).title() + full_name = fr_name + " " + la_name + #print("this is the full name:", full_name) + return full_name + +def is_name_in_the_list(fullname,database = dictall): + if fullname in dictall.keys(): + print("That donor is in the donor list.") + return fullname + else: + return None + +def split_fname(fullname): + fname, lname = fullname.split() + return fname + +def split_lname(fullname): + fname, lname = fullname.split() + return lname + +def add_name_to_db(fullname): + dictall[fullname] = [] + print("\tAdded {} to the donor database".format(fullname)) + return fullname + +def add_donation(fullname): + donation = None + while type(donation) != float: + try: + donation= float(input("What value of donation would you like to add for {}?".format(fullname))) + except ValueError as e: + print("wrong value type - use $$.CC format") + except Exception as e: + print("please input you donation amount with $$.CC format") + print ("donation is: " , donation) + print("fullname key before", dictall[fullname]) + dictall[fullname] = dictall[fullname] + [donation] + print("fullname key after", dictall[fullname]) + +def list_out_donors(): + s_dictall = sorted(dictall.items(),reverse = False) + print(""" + \t Donors: + \t--------""") + for donors, values in s_dictall: + print("\t\t",donors) + +def thank_you_email(fullname): + + fname = split_fname(fullname) + print(""" + Dear {}, + + It is such a pleasure to have you as a supporter. + + Thank you for your donations. + + Regards, + + Duey How + + President """.format(fname)) + + +#start of MAIN + +# program welcome +print("\nWelcome to your Donor Management program.") + +#call the function that cooresponds to the users selection +while(True): + # call the menu screen first + print("\nAll your list options operate through this main menu:") + menu_display() + + # call the choice function to get the users choice of action + #print("calling the choice function") #used for testing + strChoice = num_Choice("Please input your selection from 1-6:",1,7) + #verifiy choice selection - for routing tracking for debugging + print("\n\tYour menu choice was: ",strChoice) + +#menu tasks: + + # if they choose selection 1 - send a thank you letter + if (strChoice == '1'): + print ("made it to choice {} : send a donor thank you letter".format(strChoice)) + + #provide a list for visibility + answer = input("do you want to see a list of donors to remind you of the donor's full name? Enter 'y' if you do.").lower() + if answer == 'y': + print("here is a recent list of donors.") + list_out_donors() + + #run routine to get name of the donor you would like to send a letter + fullname = get_donor_info() + + #print out the thank you letter to screen + thank_you_email(fullname) + + #pause before returning user to menu + pause_foruser() + + continue + + # if they choose selection 2 - add a new donor + elif(strChoice == '2'): + print ("made it to choice {} : add a new donor".format(strChoice)) + + #start ruitine to collect the first and last name of the donor + new_donor_name = get_donor_info() + print (new_donor_name) + + # allow user to verify they typed the name correctly + happy_new_donor_name_yn = verify_input(new_donor_name) + + #if name is acceptable to user, see if it is already in the database of donors + if happy_new_donor_name_yn == "y": + dbcheck_name = is_name_in_the_list(new_donor_name,dictall) + else: #returning to main menu for re-try a name error (maybe misspelled) + print("Returning to main menu so you can try to re-enter your data.") + continue + + #add if new name is new, or return to menu if not a new name + if dbcheck_name == new_donor_name: + print("That name, {}, is already on the list of donors.".format(dbcheck_name)) + continue + else: + add_name_to_db(dbcheck_name) + + ''' + #*******check to see if they would like to add donations for this donor (new or old name) + + print("would you like to add a donation for {}".format()) + if dbcheck_name == None: + print("Name not added because already a donor. Would you like to add donations for this person? ") + yorn = yornore_Choice() + if yorn == 'y' : add_donation(new_donor_name) + else: continue + + + else: + print("dbcheck_name is", dbcheck_name) + fname, lname = dbcheck_name.split() + print("added {} to the donor database. Would you like to add {}'s first donation?".format (dbcheck_name,fname)) + yorn = yornore_Choice() + if yorn == 'y' : add_donation(dbcheck_name) + else: continue + + continue + ''' + + + # if they choose selection 3 - add new donations for donor + elif(strChoice == '3'): + print ("made it to choice {}: add donation".format(strChoice)) + + #for user to find name + res = str(input("would you like to see a list of donors and their donations? y/n").lower()) + if res == 'y': + print("here is list of donors") + list_out_donors() + + #check to see if list is on the donor list + fullname = str(input("type in the full name of the donor.")) + + #reply from list + fullname_on_list = is_name_in_the_list(fullname) + + #if reply is not on list - prompt user to return to menu + if fullname_on_list == None: + print("Name not found on donor list. Please enter donor into system first") + continue + + #if reply is on the list - then add donation for the user + else: + res = 'n' + while res == 'y': + add_donation(fullname_on_list) + res = input("would you like to add donation for this user? y/n").lower() + continue + + # if they choose selection 4 - print list of donor names + elif(strChoice == '4'): + print ("made it to choice {} : print list of donor names".format(strChoice)) + + list_out_donors() + + pause_foruser() + continue + + # if they choose selection 5 - output donor report + elif(strChoice == '5'): + print ("You made it to choice {}: Output Donor report".format(strChoice)) + + + pause_foruser() + continue + # if they choose selection 6 - exit + elif(strChoice == '6'): + print ("You made it to choice {} : exit".format(strChoice)) + choice = yornore_Choice("\tAre you sure you want to exit? ") + if choice == "y": + print("\n\tElvis has left the building. Good bye.") + break + else: + print("\nOK, Lets go back to the menu.") + continue + else: + print("You should not have made it to here. There must be a problem in the while loop.") + break + +#salutation to the user +print("\nSee you next time.") + diff --git a/students/Boundb3/Session 03/Mailroom_work.py b/students/Boundb3/Session 03/Mailroom_work.py new file mode 100644 index 0000000..d246c18 --- /dev/null +++ b/students/Boundb3/Session 03/Mailroom_work.py @@ -0,0 +1,320 @@ +""" +#-------------------------------------------------# +# Title: Mailroom - Week3/4 assignment +# Dev: BBounds +# Date: February 1 2016 +#Class: Python 2016a +Instructor: Rick Riehle / TA: Summer Rae +#-------------------------------------------------# + + +Write a small command-line script called mailroom.py. This script should be executable. +The script should accomplish the following goals: + +It should have a data structure that holds a list of your donors and a history of the amounts +they have donated. This structure should be populated at first with at least five donors, with + + +between 1 and 3 donations each +The script should prompt the user (you) to choose from a menu of 2 actions: + Send a Thank You or Create a Report. + + +If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. + +Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. + +Finally, use string formatting to compose an email thanking the donor for their generous donation. +Print the email to the terminal and return to the original prompt. +It is fine to forget new donors once the script quits running. + +Creating a Report +If the user (you) selected "Create a Report" Print a list of your donors, sorted by total historical donation amount. +Include Donor Name, total donated, number of donations and average donation amount as values in each row. +Using string formatting, format the output rows as nicely as possible. The end result should be tabular +(values in each column should align with those above and below) +After printing this report, return to the original prompt. +At any point, the user should be able to quit their current task and return to the original prompt. ### NEED HELP HERE +From the original prompt, the user should be able to quit the script cleanly + + +""" +# memo to run the file only if this is a main file + +if __name__ == "__main__": + print("hi there - this is a main file and can run this script directly") +else: + raise Exception("This file was not created to be imported") + +# set up imaginary donor information for use in the script +dictall ={} + +# input made-up values into a dictionary - very inefficeint - better to pull from a file (but had problems) + +d1 = {("Sally", "Wood", "Ms."): [50.00, 100.45, 75.25]} +d2 = {("Jim", "Nasium", "Mr."): [150.00, 10.00]} +d3 = {("Bill", "Fold", "Mr."): [45.00]} +d4 = {("Alice", "Wonder", "Mrs."): [10.00, 10.00, 25.00]} +d5 = {("Chuck", "Wheels", "Mr."): [25.00, 25,25 ]} +d6 = {("no", "one", "yet"): [] } +dictnamelist = ["d1","d2","d3","d4","d5","d6"] +dictall.update(d1) +dictall.update(d2) +dictall.update(d3) +dictall.update(d4) +dictall.update(d5) +dictall.update(d6) + +print ("Here is the printout of dictall = ",dictall) + + +# for fun, unpack the key and make a new key in a new dictionary with re-ordered values (like in a letter) +dictsalutation = {} +sdictsalutation = {} #sorted dic + +def print_report(): + + print("\n\t Donor's Report: \n\t _________________\n") + count = 0 + nameall =(), + for tplKey, lstValue in dictall.items(): # dictionary as it is first built up + #print(strKey + " / " + strValue + "\t") + #print("type ofkey",type(strKey)) + firstn = tplKey[0] + lastn = tplKey[1] + saluten = tplKey[2] + nameall = (saluten, firstn, lastn) + dictsalutation[nameall] = lstValue + count +=1 + #print("{} item(s) added to dictionary. Here is dictionary now: {}".format(count,dictsalutation)) + + for tplKey, lstValue in dictsalutation.items(): # preparing to try a sorted dictionary + + donations = sum(lstValue) + count = (len(lstValue)) + avg_donation = 0 + try: + avg_donation = donations/count + except ZeroDivisionError: + avg_donation = 0 + except Exception as e: + print(e) + + print("{} {} {} has made {:d} donation(s) for a total of ${:f}" + " (which is an ave of {:f})".format(tplKey[0],tplKey[1],tplKey[2],len(lstValue),sum(lstValue),avg_donation)) + + input("\n\ttype any key to continue") + +''' +print_report() +print("ran print report") +print("this is print of dictall", dictall) +print("*****") +print(dictsalutation) +print("***** - now sorted") +print(sorted(dictsalutation)) +print("***** - now back to unsorted - is it still there?") +print(dictsalutation) +''' + +def print_thanks(donors_fullname): + print("Thank you ",donors_fullname) + print("need to format a thank ou letter") + +def add_new_donor(): + donor_fname = input("What is the new donor's first name?").title + f = (donor_fname) + donor_lastn = input("What is the new donor's last name?").title + l = (donor_lastn) + donor_salutation = input("What is the donor's salutation for a letter? i.e: Mr. or Mrs?").title + mr =(donor_salutation) + key = (f , l , mr) + print("the type of key created to dictionary is: ", type(key), "is" , key) + print("Thank you, got the new donor. Now I will post to the dictionary.") + add_new_donor_to_dictionary(key) + +def add_new_donor_to_dictionary(unposted_new_donor): + f,l,mr = unposted_new_donor + if (f,l,mr) in dictsalutation: + print("{} already in dictionary.".format(unposted_new_donor)) + return + else: + dictall[(f,l,mr)] = [] #update the dictionary with a new key with empty list value + dictsalutation[(f,l,mr)] = [] #update the salutation dictionary too (with new key with empty list value + message = "Completed set up of new donor (added to dictionary):" + print ("{} {}".format(message,unposted_new_donor)) + return unposted_new_donor + + +"""Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. +""" + +def add_new_donations(key_name): + new_donation_Q= input("Has {} provided a new donation? Type 'yes' or 'no'".format(key_name)).lower + a= verify(new_donation_Q) + if key_name in dictall: + + lstValueNew =[] + if a == "yes": + donation_amount = int(input("What is the amount of the donation?")) + try: + b = int(verify(new_donation_Q)) + except Exception as e: + print(e, "is not a valid number. value not excepted" ) + return None + lstValueNew.append(b) + + dictall[key_name] = lstValue + dictsalutation[key_name] = lstValue + print("Ive updated that: Donor {} provided {:d} in a donation").format(key_name,lstValue) + else: + print("name {} not found. Try again.". format(key_name)) + + return + +def list_donors(): + ''' screen print list of donors in a table''' + print("temp# \t donor name \t\t donation history \n " + "--------------------------------------------------------") + count = 0 + + for tplkey, lstvalue in dictsalutation.items(): + + print ("No: {} \t {} \t\t {}".format((count+1),(tplkey[0],tplkey[1],tplkey[2]),lstvalue),sep="\t\t") + count += 1 + input("\n\ttype enter to proceed") + +# create a menu + + + +print_report() + +while(True): + print (""" + Menu of Options: + ----------------- + 1) Send a Thank You letter + 2) Add a new Donor + 3) Add new Donations + 4) List Donors + 5) Create a Report + 6) Exit + + """) + strChoice = str(input("Which option would you like to perform? [1 to 6]")) + + # 1 send thank you letter + + ''' + If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. +''' + if (strChoice == '1'): + full_name = input("Please enter the:" + "1)full name and title of the donor, or" + "2)'list' to see a list of donors, or" + "3)'exit' to quit ").title + if full_name == "exit": + break + elif full_name == "list": + list_donors() + continue + + elif full_name in dictsalutation: + print("found it in dictsalutation") + print_thanks(full_name) + continue + else: + #********* + print("I do not see this name in the list.") + full_name = verify(full_name) + answer = input("Would you like to try again or add {} name to the list?".format(full_name)) + if answer == "try again": + break + else: + print("Ok, We will add {} to the list. Lets collect the details one at a time.".format(full_name)) + created_new_donor_tpl = add_new_donor() + add_new_donations(created_new_donor_tpl) + print_thanks(created_new_donor_tpl) + + + + # 2 add new donor + elif(strChoice == '2'): + print("please check that the donor is not already on the list") + list_donors() + answer = input("do you still want to add the new donor? Type yes or no") + a = (answer) + if a == 'yes': + add_new_donor() + continue + + + #3 add new donation + elif(strChoice == '3'): + print("please find your donor on the list below") + list_donors() + keynametry = input("please type the donors full name") + add_new_donations(keynametry) + continue + + + #4 list donors + elif(strChoice == '4'): + print("Here is a list of donors:") + list_donors() + continue + + #5 create a report + elif(strChoice == '5'): + print_report() + continue + + + #6 Quit + elif(strChoice == '6'): + print("Thank you. Have a good day.") + break + + + +''' + + +print (dictall) + + + + +print (d5.keys()) +print (d4.items()) +print (d3.values()) + +for strKey, strValue in dicTable.items(): + print(strKey) + strKeyToRemove = input("Which item would you like removed?") + if(strKeyToRemove in dicTable): + del dicTable[strKeyToRemove] + else: + print("I'm sorry, but I could not find that item.") + print(dicTable) #For testing + continue + + + elif(strChoice == '6'): + objFile = open(objFileName, "w") + for strKey, strValue in dicTable.items(): + objFile.write(strKey + "," + strValue + "\n") + objFile.close() + break +''' diff --git a/students/Boundb3/Session 03/Python_the_hard_way/ex39_test_with_hash_keyfile.py b/students/Boundb3/Session 03/Python_the_hard_way/ex39_test_with_hash_keyfile.py new file mode 100644 index 0000000..4bf8fd8 --- /dev/null +++ b/students/Boundb3/Session 03/Python_the_hard_way/ex39_test_with_hash_keyfile.py @@ -0,0 +1,61 @@ +import hash_keyfile + +# create a mapping of state to abbreviation +states = hash_keyfile.new() +hash_keyfile.set(states, 'Oregon', 'OR') +hash_keyfile.set(states, 'Florida', 'FL') +hash_keyfile.set(states, 'California', 'CA') +hash_keyfile.set(states, 'New York', 'NY') +hash_keyfile.set(states, 'Michigan', 'MI') + +# create a basic set of states and some cities in them +cities = hash_keyfile.new() +hash_keyfile.set(cities, 'CA', 'San Francisco') +hash_keyfile.set(cities, 'MI', 'Detroit') +hash_keyfile.set(cities, 'FL', 'Jacksonville') + +# add some more cities +hash_keyfile.set(cities, 'NY', 'New York') +hash_keyfile.set(cities, 'OR', 'Portland') + + +# print out some cities +print ('-' * 10) +print ("NY State has: %s" % hash_keyfile.get(cities, 'NY')) +print ("OR State has: %s" % hash_keyfile.get(cities, 'OR')) + +# print some states +print ('-' * 10) +print ("Michigan's abbreviation is: %s" % hash_keyfile.get(states, 'Michigan')) +print ("Florida's abbreviation is: %s" % hash_keyfile.get(states, 'Florida')) + +# do it by using the state then cities dict +print ('-' * 10) +print ("Michigan has: %s" % hash_keyfile.get(cities, hash_keyfile.get(states, 'Michigan'))) +print ("Florida has: %s" % hash_keyfile.get(cities, hash_keyfile.get(states, 'Florida'))) + +# print every state abbreviation +print ('-' * 10) +hash_keyfile.list(states) + +# print every city in state +print ('-' * 10) +hash_keyfile.list(cities) + +print ('-' * 10) +state = hash_keyfile.get(states, 'Texas') + +if not state: + print ("Sorry, no Texas.") + +# default values using ||= with the nil result +# can you do this on one line? +city = hash_keyfile.get(cities, 'TX', 'Does Not Exist') +print ("The city for the state 'TX' is: %s" % city) + +print("states are *****:") +hash_keyfile.list(states) + +print("cities are ******") + +hash_keyfile.list(cities) \ No newline at end of file diff --git a/students/Boundb3/Session 03/Python_the_hard_way/hash_keyfile.py b/students/Boundb3/Session 03/Python_the_hard_way/hash_keyfile.py new file mode 100644 index 0000000..b82b56a --- /dev/null +++ b/students/Boundb3/Session 03/Python_the_hard_way/hash_keyfile.py @@ -0,0 +1,71 @@ +#this is an extract from python the hard way lesson 39 + +def new(num_buckets=256): + """Initializes a Map with the given number of buckets.""" + aMap = [] + for i in range(0, num_buckets): + aMap.append([]) + return aMap + +def hash_key(aMap, key): + """Given a key this will create a number and then convert it to + an index for the aMap's buckets.""" + return hash(key) % len(aMap) #this is an equation of hash key modulus length of the map dictionary + +def get_bucket(aMap, key): + """Given a key, find the bucket where it would go.""" + bucket_id = hash_key(aMap, key) + return aMap[bucket_id] + +def get_slot(aMap, key, default=None): + """ + Returns the index, key, and value of a slot found in a bucket. + Returns -1, key, and default (None if not set) when not found. + """ + bucket = get_bucket(aMap, key) + + for i, kv in enumerate(bucket): + k, v = kv + if key == k: + print(i,k,v) #i added this to see if any bucket locations were used twice. there was one instance + return i, k, v + + return -1, key, default + +def get(aMap, key, default=None): + """Gets the value in a bucket for the given key, or the default.""" + i, k, v = get_slot(aMap, key, default=default) + return v + +def set(aMap, key, value): + """Sets the key to the value, replacing any existing value.""" + bucket = get_bucket(aMap, key) + i, k, v = get_slot(aMap, key) + + if i >= 0: + # the key exists, replace it + bucket[i] = (key, value) #assigns a tuple to the bucket index of i + else: + # the key does not, append to create it + bucket.append((key, value)) + +def delete(aMap, key): + """Deletes the given key from the Map.""" + bucket = get_bucket(aMap, key) + + for i in range(len(bucket)): + k, v = bucket[i] + if key == k: + del bucket[i] + break + +def list(aMap): #this map seems to be a list of lists(buckets) inside a huge list. +# I do not see a dictionary squiggly line anywhere. and in each list it looks like a tuple + """Prints out what's in the Map.""" + for bucket in aMap: + if bucket: + for k, v in bucket: + print (bucket, k, v) + + print(aMap) + print(type(aMap)) diff --git a/students/Boundb3/Session 03/ROT13.py b/students/Boundb3/Session 03/ROT13.py new file mode 100644 index 0000000..03b683d --- /dev/null +++ b/students/Boundb3/Session 03/ROT13.py @@ -0,0 +1,54 @@ +""" +Add a python module named rot13.py to the session03 dir in your student dir. +This module should provide at least one function called rot13 that takes any +amount of text and returns that same text encrypted by ROT13. + +This function should preserve whitespace, punctuation and capitalization. + +Your module should include an if __name__ == '__main__': block with tests (asserts) + that demonstrate that your rot13 function and any helper functions you add work properly. + +As usual, add your new file to your local clone right away. +Make commits early and often and include commit messages that are descriptive and concise. When you are done, +if you want me to review it, push your changes to github and issue a pull request. + +try decrypting this:Zntargvp sebz bhgfvqr arne pbeare +""" + + + +def rot13(codestr, ENcode=False): + '''Code or decode a string based on a 13 letter shift to the right. An optional second arguement: when True + it will ENcode, when it is False it will DEcode the first alpha arguement. ''' + + intab = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # write these outside the loop so they don't have to get + outtab = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM" # recreated every time :) + assert len(intab) == len(outtab), "lengths are not the same." # why are you checking the lengths here? + if ENcode == False: + answer = (codestr.translate(str.maketrans(outtab, intab))) + else: + answer = (codestr.translate(str.maketrans(intab, outtab))) + return answer + + + + +if __name__ == "__main__": + choice = 5 + while not choice == 2 and not choice == 1: + try: + choice = int(input("Do you want to 1)make code or 2)desypher code? Type 1 for encode and 2 for desypher ")) + print ("OK, got it. Number {} was your choice.".format(choice)) + except ValueError: + print("You need to input a number. Try again") + assert choice == 1 or choice == 2 , "You did not type in a 1 or a 2- try again or you must be a spy." + + + dedecoderring= input("Type in the string you would like to send through the decoder ring.") + + if choice == 1: + print(rot13(dedecoderring, True)) + elif choice ==2: + print(rot13(dedecoderring, False)) + else: + print("I did not understand. Try again. I'm beginning to wonder if you are spy??") diff --git a/students/Boundb3/Session 03/copyROT13.py b/students/Boundb3/Session 03/copyROT13.py new file mode 100644 index 0000000..cd59118 --- /dev/null +++ b/students/Boundb3/Session 03/copyROT13.py @@ -0,0 +1,55 @@ +""" +Add a python module named rot13.py to the session03 dir in your student dir. +This module should provide at least one function called rot13 that takes any +amount of text and returns that same text encrypted by ROT13. + +This function should preserve whitespace, punctuation and capitalization. + +Your module should include an if __name__ == '__main__': block with tests (asserts) + that demonstrate that your rot13 function and any helper functions you add work properly. + +As usual, add your new file to your local clone right away. +Make commits early and often and include commit messages that are descriptive and concise. When you are done, +if you want me to review it, push your changes to github and issue a pull request. + +try decrypting this:Zntargvp sebz bhgfvqr arne pbeare +""" + + + +def rot13(codestr, ENcode=False): + '''Code or decode a string based on a 13 letter shift to the right. An optional second arguement: when True + it will ENcode, when it is False it will DEcode the first alpha arguement. ''' + + intab = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + outtab = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM" + assert len(intab) == len(outtab), "lengths are not the same." + if ENcode == False: + answer = (codestr.translate(str.maketrans(outtab, intab))) + else: + answer = (codestr.translate(str.maketrans(intab, outtab))) + return answer + + + + +if __name__ == "__main__": + choice = 5 + while not choice == 2 and not choice == 1: + try: + choice = int(input("Do you want to 1)make code or 2)desypher code? Type 1 for encode and 2 for desypher ")) + print ("OK, got it. Number {} was your choice.".format(choice)) + except ValueError: + print("You need to input a number. Try again") + assert choice == 1 or choice == 2 , "You did not type in a 1 or a 2- try again or you must be a spy." + + + dedecoderring= input("Type in the string you would like to send through the decoder ring.") + + if choice == 1: + print(rot13(dedecoderring, True)) + elif choice ==2: + print(rot13(dedecoderring, False)) + else: + print("I did not understand. Try again. I'm beginning to wonder if you are spy??") + diff --git a/students/Boundb3/Session 03/dict_play_states_lesson39.py b/students/Boundb3/Session 03/dict_play_states_lesson39.py new file mode 100644 index 0000000..199e29c --- /dev/null +++ b/students/Boundb3/Session 03/dict_play_states_lesson39.py @@ -0,0 +1,68 @@ +# create a mapping of state to abbreviation +states = { + 'Oregon': 'OR', + 'Florida': 'FL', + 'California': 'CA', + 'New York': 'NY', + 'Michigan': 'MI' +} + +# create a basic set of states and some cities in them +cities = { + 'CA': 'San Francisco', + 'MI': 'Detroit', + 'FL': 'Jacksonville' +} + +# add some more cities +cities['NY'] = 'New York' +cities['OR'] = 'Portland' + +# print out some cities +print ('-' * 10) +print ("NY State has: ", cities['NY']) +print ("OR State has: ", cities['OR']) + +# print some states +print ('-' * 15) +print ("Michigan's abbreviation is: ", states['Michigan']) +print ("Florida's abbreviation is: ", states['Florida']) + +# do it by using the state then cities dict +print ('-' * 20) +print ("Michigan has: ", cities[states['Michigan']]) +print ("Florida has: ", cities[states['Florida']]) + +# print every state abbreviation +print ('-' * 30) +for state, abbrev in states.items(): + print ("%s is abbreviated %s" % (state, abbrev)) + +# print every city in state +print ('-' * 10) +for abbrev, city in cities.items(): + print ("%s has the city %s" % (abbrev, city)) + +# now do both at the same time +print ('-' * 10) +for state, abbrev in states.items(): + print ("%s state is abbreviated %s and has city %s" % ( + state, abbrev, cities[abbrev])) + +print ('-' * 10) +# safely get a abbreviation by state that might not be there +state = states.get('Texas') + +if not state: + print ("Sorry, no Texas.") + +# get a city with a default value +city = cities.get('TX', 'Does Not Exist') +print ("The city for the state 'TX' is: %s" % city) + +z = "dasfj;ldfkjeruio" +q = hash(z) +print(q) + +print(hash("23state")) +print(hash("45sdf")) \ No newline at end of file diff --git a/students/Boundb3/Session 03/do_n_n_times.py b/students/Boundb3/Session 03/do_n_n_times.py new file mode 100644 index 0000000..0f0eab5 --- /dev/null +++ b/students/Boundb3/Session 03/do_n_n_times.py @@ -0,0 +1,25 @@ +""" + +from greantreepress chapter 5.9 - recursion + + +""" + +def func_n(f,t): + f(t) + +def func_action(t): + if t>1: + print("hi "*t) + t=t-1 + func_action(t) + else: + print("this is the end of the series") + + + +x=8 +n=func_n(func_action,x) + + + diff --git a/students/Boundb3/Session 03/file_write_test.py b/students/Boundb3/Session 03/file_write_test.py new file mode 100644 index 0000000..2665b94 --- /dev/null +++ b/students/Boundb3/Session 03/file_write_test.py @@ -0,0 +1,49 @@ +#practice writing to a file + +''' +>> with open('test.log', mode='w', encoding='utf-8') as a_file: ? +... a_file.write('test succeeded') ? +>>> with open('test.log', encoding='utf-8') as a_file: +... print(a_file.read()) +test succeeded +>>> with open('test.log', mode='a', encoding='utf-8') as a_file: ? +... a_file.write('and again') +>>> with open('test.log', encoding='utf-8') as a_file: +... print(a_file.read()) +test succeededand again +''' + + + +with open("practicetestfile", mode = "w",encoding='utf-8') as f: + print(f.tell()) + f.write("try this text\n") + print(f.tell()) + print("stop") +with open("practicetestfile", mode = "r", encoding='utf-8') as f: + print(f.tell()) + xdata = (f.read()) + print(f.tell()) + print("finishd read") + print ("length of data read in f at this time: ",len(xdata)) +with open("practicetestfile", mode = "a+",encoding='utf-8') as f: + print("open in append") + print(f.tell()) + f.write("I like to try this text again") + print(f.tell()) + print(f.tell()) + print(f.write("\tThis is last write for the day")) + print(f.tell()) + f.seek(0) + print(f.read()) +with open("practicetestfile", mode = "r", encoding='utf-8') as f: + print(f.readline()) + print("hi") + print(f.readline()) + +from os.path import exists + +print (len("practicetestfile")) +print("does it exist? true or false \n it is: {} ".format(exists("practicetestfile"))) + + diff --git a/students/Boundb3/Session 03/list_lab.py b/students/Boundb3/Session 03/list_lab.py new file mode 100644 index 0000000..d0fd3c3 --- /dev/null +++ b/students/Boundb3/Session 03/list_lab.py @@ -0,0 +1,132 @@ +""" this is the list lab + +***key questions on shallow copy - row 100 fixed in routine below it - buthow should we DEEP copy a list +*** the boolean AND on row: 80 AND + + + +""" + +#create and print a list +fruitStr = "apples,pears,oranges,peaches" +fruitLst = fruitStr.split(",") +print(fruitLst) + +# ask and add a new fruit to the back of the list +newfruit = input("what new fruit would you like to add?") +fruitLst.append(newfruit) + +# get a number from the user and show the number and fruit from the list +#starting with 1 + +request = int(input("pick a number between 1 and {}".format(len(fruitLst)))) +print ("your list: ", fruitLst) +print("{} was the number for {}. I will delete it.".format(request,fruitLst[request-1])) +del fruitLst[request-1] +print ("your updated list" , fruitLst) + +#add another fruit to the beginning of the list using + +anotherfruit = [input("what other fruit would you like to add to the front of the list?")] # now it is a list item input +fruitLst = anotherfruit + fruitLst +print ("your list with {} looks like this:\n\t{}".format(anotherfruit[0],fruitLst)) + +#add another fruit to the beginning of the list using insert +anotherfruit2 = input("what second fruit would you like to add to the front of the list?") #now it is a string input +fruitLst.insert(0,anotherfruit2) +print ("here is the list with your second fruit {} added too:\n\t{}".format(anotherfruit2,fruitLst)) + +#display fruits beginning with letter P +print("\n\n Lets find the fruit that start with the letter 'P'") +pList = [] +for i in fruitLst: + if "P" == i[0].upper(): + pList.append(i) +print("\n\nHere is the full list of P fruits:", pList) + + +#starting again a new set of tasks +copyfruitLst = fruitLst[:] # preserve a copy of the list + +print("\n\nOK - here is the current list of all the fruits, not just P",fruitLst) +x= fruitLst.pop(-1) +print("now here is your list without the last item: {} ".format(x), end ="") +print("\t{}".format(fruitLst)) +for indx,item in enumerate(fruitLst): + print("\t{} ) {}".format((indx+1),item.strip()))#********* +dislike = int(input("select an item number to be deleted:")) +dislikefruit = fruitLst[dislike-1] +fruitLst.pop((dislike-1)) + +print("So, you don't like {}. Here is the remaining list:{}".format(dislikefruit, fruitLst)) + +#start for bonus - multiply list and delete all instances of disliked fruit +oldfruitLst = copyfruitLst[:] +print("\nOK - lets go back to the old list you had:",oldfruitLst) +oldfruitLst = oldfruitLst + oldfruitLst *2 +for x in oldfruitLst: + if x == dislikefruit: + oldfruitLst.remove(x) +print("whoops we multiplied your list{}, but we lost all the {}! where did it go?".format(oldfruitLst,dislikefruit)) + + +#new questions - loop through list to ask yes or no if they like. delete all occurances + +fruitset = set(copyfruitLst) # drop any duplicates by turning list into a set +fruitLst = list(fruitset) #return it back into a list +fruitLstlwr = [] #prep for a new list to be built in all lower case +for item in fruitset: + item= item.lower() + fruitLstlwr.append(item) + reply = None + while reply != "yes" and reply != "no": + reply = input("do you like {}? Input yes or no. ".format(item)).lower() + if reply == "yes": + print("great, we will keep {}".format(item)) + elif reply == "no": + fruitLstlwr.remove(item) + print("OK - say goodby to {}".format(item)) + else: + print("you must enter yes or no") +print("this is your new list of favorites",fruitLstlwr) + +# one more exercise to reverse the list + +## HOW do I not effect the original and the adapted one -- how to avoid a shallow copy!!!!!!!!!!! +rvrscopy_fruitLst = fruitLst[:] +print("fruitlist:" , fruitLst) +print("rvrscopy_fruitLst is", rvrscopy_fruitLst) +for item in fruitLst: #iterate on one list + print ("item",item) + if len(item)>1: + first = item[0] + last = item[-1] + newitem = last + item[1:-1] + first + else: newitem = item + print("newitem is",newitem) + rvrscopy_fruitLst.append(newitem)#update and make changes to the other list + rvrscopy_fruitLst.remove(item) +print("original list is: ", fruitLst) #yea it works now - iterate on one list, and make changes to the other copy of the list +print("new rvrsed list is: ",rvrscopy_fruitLst) #yea it works now !!! +print("now we can get rid of the last entry in our fruit salad: lets nix {}".format(fruitLst.pop()),fruitLst) + + +# start with a list and a list copy +# this time change all the letters to go backward, not just switch first and last letter + +print("\n\n\n duplicate of last excercise is below - for grins - now that it works") +fruitLst = list(fruitset) +rvrscopy_fruitLst = fruitLst[:] #this is creating the shallow copy - so how do we NOT do this??? +print("fruitlist:" , fruitLst) +print("rvrscopy_fruitLst is", rvrscopy_fruitLst) +brandnew_list = [] +for item in rvrscopy_fruitLst: + print ("item is: ",item) + if len(item)>1: #if each word in the list is longer than one letter, then swap first and last letter + newitem = item[::-1] + else: newitem = item + print("newitem is: ",newitem) + brandnew_list.append(newitem) + +print("original list is: ", fruitLst) +print("new rvrsed brand new list is: ",brandnew_list) +print("now we can get rid of the last entry in our fruit salad: lets nix {}".format(fruitLst.pop()),fruitLst) diff --git a/students/Boundb3/Session 03/play 2.py b/students/Boundb3/Session 03/play 2.py new file mode 100644 index 0000000..af497f6 --- /dev/null +++ b/students/Boundb3/Session 03/play 2.py @@ -0,0 +1,71 @@ +''' + +play 2 - to find how to get first letter print() + +''' + +''' + +#display fruits beginning with letter P +print("lets find the fruit that start with the letter 'P'") +fruitLst = ["Pinanpple", "rose", "tea", "peach", "orange", " apple"] +for i in fruitLst: + print ("i is", i) + print ("i is first place=" ,i[0]) + print(i[0], i[0].upper()) + + if "P" == i[0].upper: + print(i) +''' +''' +fruitLst = ["Pinanpple", "rose", "tea", "peach", "orange", " apple"] +fruitLst = fruitLst + fruitLst +print(fruitLst) +fruitLst = fruitLst *2 +print(fruitLst) +''' +''' + +copyfruitLst = ["Pinanpple", "rose", "teA", "Peach", "ORANGE", " apple"] +copyfruitLst = copyfruitLst *3 +print(copyfruitLst) +#new questions +fruitset = set(copyfruitLst) +print ("now it is a set?",type(fruitset)) +print(fruitset) +fruitLst = list(fruitset) +print("now it is a list?",type(fruitLst)) +print(fruitLst) +fruitLstlwr = [] +for item in fruitset: + item= item.lower() + fruitLstlwr.append(item) + reply = None + while reply != "yes" and reply != "no": + reply = input("do you like {}? Input yes or no. ".format(item)).lower() + if reply == "yes": + print("great, we will keep {}".format(item)) + elif reply == "no": + fruitLstlwr.remove(item) + print("OK - say goodby to {}".format(item)) + else: + print("you must enter yes or no") +print("this is your new list of favorites",fruitLstlwr) +''' + +rvrscopy_fruitLst = ["Pinanpple", "rose", "teA", "Peach", "ORANGE", " apple","hi", "i"] +for item in rvrscopy_fruitLst: + if len(item)>1: + print (item) + first = item[0] + last = item[-1] + item = last + item[1:-1] + first + print(item) + + + + + + + + diff --git a/students/Boundb3/Session 03/play.py b/students/Boundb3/Session 03/play.py new file mode 100644 index 0000000..75ac412 --- /dev/null +++ b/students/Boundb3/Session 03/play.py @@ -0,0 +1,34 @@ +def do_twice(func, arg): + """Runs a function twice. + + func: function object + arg: argument passed to the function + """ + func(arg) + func(arg) + + +def print_twice(arg): + """Prints the argument twice. + + arg: anything printable + """ + print(arg) + print(arg) + + +def do_four(func, arg): + """Runs a function four times. + + func: function object + arg: argument passed to the function + """ + do_twice(func, arg) + do_twice(func, arg) + + +do_twice(print_twice, 'spam') +print('') + +do_four(print_twice, 'spam') + diff --git a/students/Boundb3/Session 03/practicetestfile b/students/Boundb3/Session 03/practicetestfile new file mode 100644 index 0000000..f299898 --- /dev/null +++ b/students/Boundb3/Session 03/practicetestfile @@ -0,0 +1,2 @@ +try this text +I like to try this text again This is last write for the day \ No newline at end of file diff --git a/students/Boundb3/Session 03/read_student.py b/students/Boundb3/Session 03/read_student.py new file mode 100644 index 0000000..7103f68 --- /dev/null +++ b/students/Boundb3/Session 03/read_student.py @@ -0,0 +1,36 @@ +''' +create a file that opens and reads the student language file. + 1. create a list of all the languages that have been used + 2. if possible,can keep track of how many languages the students have each + + +''' + +import os + + + +# f = open("C:\Python_100a\IntroPython2016a\students\Boundb3\Textfiles\students.txt", "r"): + + +language_set = set () + +with open('C:\Python_100a\IntroPython2016a\students\Boundb3\Textfiles\students.txt', 'r') as f: + for line in f: + student_lang = line.rsplit(':')[1] + language_list = student_lang.split(",") + for language in language_list: + language = language.strip("\n") + language_set.add(language) + +print(language_set) +print(len(language_set)) + +''' +# we can take out zero length lengths, +''' + + + + + diff --git a/students/Boundb3/Session 03/series.py b/students/Boundb3/Session 03/series.py new file mode 100644 index 0000000..5f807de --- /dev/null +++ b/students/Boundb3/Session 03/series.py @@ -0,0 +1,70 @@ + +''' + +Brennen Bounds +Python 100a + +Create a new module series.py in the session02 folder in your student folder. +In it, add a function called "fibonacci". + +The function should have one parameter n. +The function should return the nth value in the fibonacci series. + +add a new function "lucas" that returns the nth value in the lucas numbers series. + +then add a third function called sum_series with one required parameter and two optional parameters. +The required parameter will determine which element in the series to print. +The two optional parameters will have default values of 0 and 1 and will determine +the first two values for the series to be produced. + +Calling this function with no optional parameters will produce numbers from the fibonacci series. +Calling it with the optional arguments 2 and 1 will produce values from the lucas numbers. +Other values for the optional parameters will produce other series. + +Ensure that your function has a well-formed docstring + +''' + +def fibinacci_n(n): + """Return the nth value in a fibinacci series.""" + a,b =0,1 + #print (a) + for i in range(n-1): + a,b = b, a+b + #print (a) + return a + + +def lucas_n(n): + """Return the nth value in a Lucas series.""" + a,b =2,1 + #print (a) + for i in range(n-1): + a,b = b, a+b + #print (a) + return a + + +def sum_series(n, startnum1=0,startnum2=1): + """Return the nth value in a additive summation series given the two starting numbers. + The default series is the fibinacci series.""" + startnum1, startnum2 = startnum1, startnum2 + #print (a) + for i in range(n-1): + startnum1,startnum2 = startnum2, startnum1+startnum2 + #print (a) + return startnum1 + + +n = int(input("Type in the number in the sequence you want.")) +startnum1 = int(input("Type in the starting number.")) +startnum2 = int(input("Type in the second starting number.")) + +print("\n",fibinacci_n.__doc__, ":") +print ("\tThe", n, "'th number in the fibinacci sequence is: ", fibinacci_n(n)) +print("\n",lucas_n.__doc__, ":") +print ("\tThe", n, "'th number in the lucas sequence is: ",lucas_n(n)) +print("\n",sum_series.__doc__) +print ("\tThe", n, "'th number in a made up series is:",sum_series(n,startnum1,startnum2), "(for starting numbers:)",startnum1,startnum2) + + diff --git a/students/Boundb3/Session 03/slicinglab.py b/students/Boundb3/Session 03/slicinglab.py new file mode 100644 index 0000000..00fe0c4 --- /dev/null +++ b/students/Boundb3/Session 03/slicinglab.py @@ -0,0 +1,31 @@ +# this is a re-do of the slicing lab to make sure I did it + +''' + +return a sequence with the first and last items exchanged. +return a sequence with every other item removed +return a sequence with the first and last 4 items removed, and every other item in between +return a sequence reversed (just with slicing) +return a sequence with the middle third, then last third, then the first third in the new order +''' + +x = ("1234567890 I went to the store only Monday abcdefghijklmnopqrstuvwxyz12") +print(x) + +x_switchfirstnlast = x[-1:]+x[1:-2]+x[0:1] +print(x_switchfirstnlast) + +x_every_other_removed = x[::2] +print(x_every_other_removed) + +x_mid_with_missing_mid = x[4:-4:2] +print(x_mid_with_missing_mid) + +x_reversed = x[::-1] +print(x_reversed) + +thirds = (len(x)//3) +leftover = (len(x)%3) +print(thirds,"\n",leftover) +x_mid_last_first_thirds = x[(thirds):(-thirds)]+ " *|* " + x[(-thirds):] + " *|* " + x[:(thirds)] +print(x_mid_last_first_thirds) diff --git a/students/Boundb3/Session 03/string_format_lab.py b/students/Boundb3/Session 03/string_format_lab.py new file mode 100644 index 0000000..35a091d --- /dev/null +++ b/students/Boundb3/Session 03/string_format_lab.py @@ -0,0 +1,45 @@ +''' +TO DO : this is the string formating lab assignment + +A couple Exercises +Write a format string that will take: + +( 2, 123.4567, 10000) + +and produce: + +'file_002 : 123.46, 1e+04' +Rewrite: "the first 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3) to take an arbitrary number of values +Trick: You can pass in a tuple of values to a function with a *: + +for an arbitrary number of numbers...(from chapter 4 from class slides + + +''' + +#for the lab + +def defined_string(z): + print("file_{:03d} \t {:.2f} \t {:.0e} ".format(*z)) + +z = ( 2, 123.4567, 10000) +defined_string(z) #format specfic to the lab exercise + + +#for fun +def string_for(a): + for i in range(0,2): + print("first is: {:d} next is {:d} and third is: {:d}".format(*a)) + +a = (3,4,5,6,7,8) +y = string_for(a) #simple plain format + +# a comma separater format +print("this is comma separted number format: {:,}".format(12346.34)) + +import datetime +d= datetime.datetime(2016, 2, 22,17,49,00) +print("this is the time: {:%Y-%m-%d %H:%M:%S}".format(d)) + +# for details: +# https://docs.python.org/3/library/string.html#string-formatting \ No newline at end of file diff --git a/students/Boundb3/Session 03/structshape.py b/students/Boundb3/Session 03/structshape.py new file mode 100644 index 0000000..66e9758 --- /dev/null +++ b/students/Boundb3/Session 03/structshape.py @@ -0,0 +1,139 @@ +"""This module contains a code example related to + +Think Python, 2nd Edition +by Allen Downey +http://thinkpython2.com + +Copyright 2015 Allen Downey + +License: http://creativecommons.org/licenses/by/4.0/ +""" + +from __future__ import print_function, division + +""" +This module provides one function, structshape(), which takes +an object of any type and returns a string that summarizes the +"shape" of the data structure; that is, the type, size and +composition. +""" + +def structshape(ds): + """Returns a string that describes the shape of a data structure. + + ds: any Python object + + Returns: string + """ + typename = type(ds).__name__ + + # handle sequences + sequence = (list, tuple, set, type(iter(''))) + if isinstance(ds, sequence): + t = [] + for i, x in enumerate(ds): + t.append(structshape(x)) + rep = '%s of %s' % (typename, listrep(t)) + return rep + + # handle dictionaries + elif isinstance(ds, dict): + keys = set() + vals = set() + for k, v in ds.items(): + keys.add(structshape(k)) + vals.add(structshape(v)) + rep = '%s of %d %s->%s' % (typename, len(ds), + setrep(keys), setrep(vals)) + return rep + + # handle other types + else: + if hasattr(ds, '__class__'): + return ds.__class__.__name__ + else: + return typename + + +def listrep(t): + """Returns a string representation of a list of type strings. + + t: list of strings + + Returns: string + """ + current = t[0] + count = 0 + res = [] + for x in t: + if x == current: + count += 1 + else: + append(res, current, count) + current = x + count = 1 + append(res, current, count) + return setrep(res) + + +def setrep(s): + """Returns a string representation of a set of type strings. + + s: set of strings + + Returns: string + """ + rep = ', '.join(s) + if len(s) == 1: + return rep + else: + return '(' + rep + ')' + return + + +def append(res, typestr, count): + """Adds a new element to a list of type strings. + + Modifies res. + + res: list of type strings + typestr: the new type string + count: how many of the new type there are + + Returns: None + """ + if count == 1: + rep = typestr + else: + rep = '%d %s' % (count, typestr) + res.append(rep) + + +if __name__ == '__main__': + + t = [1, 2, 3] + print(structshape(t)) + + t2 = [[1, 2], [3, 4], [5, 6]] + print(structshape(t2)) + + t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9] + print(structshape(t3)) + + class Point: + """trivial object type""" + + t4 = [Point(), Point()] + print(structshape(t4)) + + s = set('abc') + print(structshape(s)) + + lt = zip(t, s) + print(structshape(lt)) + + d = dict(lt) + print(structshape(d)) + + it = iter('abc') + print(structshape(it)) diff --git a/students/Boundb3/Session 03/test.py b/students/Boundb3/Session 03/test.py new file mode 100644 index 0000000..b627034 --- /dev/null +++ b/students/Boundb3/Session 03/test.py @@ -0,0 +1,38 @@ +''' + +from __future__ import print_function, division + + +def invert_dict(d): + """Inverts a dictionary, returning a map from val to a list of keys. + + If the mapping key->val appears in d, then in the new dictionary + val maps to a list that includes key. + + d: dict + + Returns: dict + """ + inverse = {} + for key in d: + val = d[key] + inverse.setdefault(val, []).append(key) + return inverse + + +if __name__ == '__main__': + d = dict(a=1, b=2, c=3, z=1) + inverse = invert_dict(d) + for val in inverse: + keys = inverse[val] + print(val, keys) + +''' + +def sumall(*args ): + t = sum(args) + #print (t) + return t + +x = sumall(3,4,5,6,7) +print (x) diff --git a/students/Boundb3/Session 03/test2.py b/students/Boundb3/Session 03/test2.py new file mode 100644 index 0000000..79de72b --- /dev/null +++ b/students/Boundb3/Session 03/test2.py @@ -0,0 +1,413 @@ +""" +#-------------------------------------------------# +# Title: Mailroom - Week3/4 assignment +# Dev: BBounds +# Date: February 1 2016 +#Class: Python 2016a +Instructor: Rick Riehle / TA: Summer Rae +#-------------------------------------------------# + + +Write a small command-line script called mailroom.py. This script should be executable. +The script should accomplish the following goals: + +It should have a data structure that holds a list of your donors and a history of the amounts +they have donated. This structure should be populated at first with at least five donors, with + + +between 1 and 3 donations each +The script should prompt the user (you) to choose from a menu of 2 actions: + Send a Thank You or Create a Report. + + +If the user (you) selects "Send a Thank You", prompt for a Full Name. +If the user types "list", show them a list of the donor names and re-prompt +If the user types a name not in the list, add that name to the data structure and use it. +If the user types a name in the list, use it. + +Once a name has been selected, prompt for a donation amount. +Verify that the amount is in fact a number, and re-prompt if it isnt. +Once an amount has been given, add that amount to the donation history of the selected user. + +Finally, use string formatting to compose an email thanking the donor for their generous donation. +Print the email to the terminal and return to the original prompt. +It is fine to forget new donors once the script quits running. + +Creating a Report +If the user (you) selected "Create a Report" Print a list of your donors, sorted by total historical donation amount. +Include Donor Name, total donated, number of donations and average donation amount as values in each row. +Using string formatting, format the output rows as nicely as possible. The end result should be tabular +(values in each column should align with those above and below) +After printing this report, return to the original prompt. +At any point, the user should be able to quit their current task and return to the original prompt. ### NEED HELP HERE +From the original prompt, the user should be able to quit the script cleanly + +""" + +# memo to run the file only if this is a main file + +if __name__ == "__main__": + print("Hi there - this is a main file and you can run this script from here.") +else: + raise Exception("This file was not created to be imported") + +# set up imaginary donor information for use in the script +# input made-up values into a dictionary - very inefficeint - better to pull from a file (but had problems) + +d1 = {("Sally Wood"): [50.00, 100.45, 75.24]} +d2 = {("Jim Nasium"): [150.00, 10.01]} +d3 = {("Bill Fold"): [45.00]} +d4 = {("Alice Wonder"): [10.00, 10.00, 25.02]} +d5 = {("Chuck Wheels"): [25.00, 25,25.14 ]} +d6 = {("No One"): [] } + +dictall ={} +dictall.update(d1) +dictall.update(d2) +dictall.update(d3) +dictall.update(d4) +dictall.update(d5) +dictall.update(d6) + +#play prints +#dictallsort_val = sorted(dictall,key=(dictall.get), reverse = True) # problem: this sorts on the first number, not the sum total + + +#user choice and menu driving functions: + +def pause_foruser(): + waitvalue = input("\nHit any key to proceed.") + +def num_Choice(question="Please input a numerical responce in the appropriate range", low=1, high=10): + """ask for a number within a range from user""" + choiceNum = None + try: + while choiceNum not in range(low, high): + choiceNum = int(input(question)) + except Exception as e: + print("Error in Choice: " + str(e)) + return str(choiceNum) + +def yornore_Choice(question= "Please input 'y' or 'n' for yes/no. "): + """ask for a yes or no answer from user""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + choiceYN = input(question) + if choiceYN == 'y' : print("\tOK - lets do that.", end=" ") + if choiceYN == 'n': print("\tOK - let's not do that. Lets go back.") + + except Exception as e: + print("Error in y/n choice: " + str(e)) + + return str(choiceYN) + +def verify_input (responce_to_check, question = "Is this '{}' correct? Please input 'y' or 'n' "): + """ask for a yes or no confirmation of the accuracy of the user's input""" + choiceYN = None + try: + while choiceYN not in ('y', 'n'): + #allow user to see if there answer is typed correctly + choiceYN = input(question.format(responce_to_check)).lower() + #print("in verify input function: check to see the value of choice YN", choiceYN) + + if choiceYN == 'y' : + print("\tOK - accepted.", end=" ") + elif choiceYN == 'n': + print("\tOK - try to input that again.") + + return(choiceYN) + + except Exception as e: + print("Error in y/n choice: " + str(e)) + return None + +#core menu function: + +def menu_display(): + """Display the menu of choices""" + print (""" + Menu of Options: + ----------------- + 1) Send a Thank You letter + 2) Add a new Donor + 3) Add new Donations + 4) List Donors' Names + 5) Create a Donor Report + 6) Exit + + """) + +#data task functions: + +def get_donor_info(): + print("Lets get name data of the donor.") + fr_name = str(input("what is the first name of the donor?")).title() + la_name = str(input("what is the last name of the donor?")).title() + full_name = fr_name + " " + la_name + #print("this is the full name:", full_name) + return full_name + +def is_name_in_the_list(fullname,database = dictall): + if fullname.title() in dictall.keys(): + print("That donor is in the donor list.") + return ("yes") + else: + print("That donor is NOT currently in the donor list.") + return fullname + + +def split_fname(fullname): + fname, lname = fullname.split() + return fname + +def split_lname(fullname): + fname, lname = fullname.split() + return lname + +def add_name_to_db(fullname): + #print("in the addname to db function. this is the full name passed to this add name fucntion", fullname) + dictall[fullname] = [] #establish name with empty list for donaation + print("\tAdded {} to the donor database".format(fullname)) + return fullname + +def add_donation(fullname): + donation = None + while type(donation) != float: + try: + donation= float(input("What value of donation would you like to add for {}?".format(fullname))) + except ValueError as e: + print("wrong value type - use $$.CC format without commas") + except Exception as e: + print("please input you donation amount with $$.CC format") + print ("Adding a Donation for $: " , donation) + #print("fullname key's value before", dictall[fullname]) + dictall[fullname] = dictall[fullname] + [donation] + print("Here is a summary of {}'s donations now.".format(split_fname(fullname)), dictall[fullname]) + +def list_out_donors(): + s_dictall = sorted(dictall.items(),reverse = False) + print(""" + \t Donors: + \t--------""") + for donors, values in s_dictall: + print("\t\t",donors) + +def list_out_donors_and_donations(): + s2_dictall = sorted(dictall.items(),reverse = False) + print("{:^15}{:^45}".format("Name","Donations")) + print("-"*15, " "*15, "-"*15) + for k,v in s2_dictall: + print("{:<15} {:>30}".format(k,str(v))) + print("\n"*2) + +def print_report_sumtotal_summary(): + """Report of the total sum of donations per donor.""" + print("\n\nReport of donors by total historical contributions:") + + s2_dictall = sorted(dictall.items(),reverse = False) + + #create a new dictionary with same keyword name and value is the sum of donations + sumvalue_dict ={} + for k, tv in s2_dictall: + sumvalue_dict[k]= sum(tv) + + # now sort on the values in the new dictionary - to give a list of keys (keys only) by sum of donations + s_sumvalue_dict_list = sorted(sumvalue_dict,key=sumvalue_dict.get,reverse = True) + + #various print plays to see values + #print("this is s2 dictall: ", s2_dictall) + #print("this is the sorted value list: s sumvalue dict list ", s_sumvalue_dict_list) + #print("this is the new dictionary sumvalue dict ", sumvalue_dict) + + #begin print table + print("{:^15}{:^45}".format("Name","Donations | Details")) + print("-"*15, " "*15, "-"*20) + #print report contents for sorted donor by value of historical donations + for name in s_sumvalue_dict_list: + #print(name) + for n,v in sumvalue_dict.items(): + #print(n,v) + if name == n: + print("{:<20} {:>20.2f} ".format(name,v,),end="") + for k,l in dictall.items(): + if name == k: + #print("{:>60)}".format(str(dictall[k]))) + print(dictall[k]) + + # print("{:<15} {:>30}".format(k,str(v))) + #print("\n"*2) + + +def print_report(): + """Report of name, count, average, and sum total of donations by donor""" + print("Report of donor name, count, average, and sum total of their donations. " + "Sorted by Name - not able to determine sort by total donations!!!") + s_dictall = sorted(dictall.items(),reverse = False) #sorting list extract of dictionary items (by key alphebetized) + #print("this is s dictall before formatting: ", s_dictall) + print("{:<15}{:<8} {:^8} {:>10} ".format("Name","Count","Average","Sum Total")) + print("{:^38}".format("-"*46)) + for k,v in s_dictall: + if sum(v)>0: + print("{:<15} {:<8} ${:8.2f} ${:>10.2f}".format(k,len(v),(sum(v)/len(v)),sum(v)) ) + else: + print("{:<15} {:<8} ${:8.2f} ${:>10.2f}".format(k,len(v),0.0,sum(v)) ) + + + +def thank_you_email(fullname): + + fname = split_fname(fullname) + print(""" + Dear {}, + + It is such a pleasure to have you as a supporter. + + Your total donations of ${:.2f} have been critical to our mission. + + Regards, + + Duey How + + President """.format(fname,sum(dictall[fullname]))) + + +#start of MAIN + +# program welcome +print("\nWelcome to your Donor Management program.") + +#call the function that cooresponds to the users selection +while(True): + # call the menu screen first + print("\nAll your options operate through this main menu:") + menu_display() + + # call the choice function to get the users choice of action + #print("calling the choice function") #used for testing + strChoice = num_Choice("Please input your selection from 1-6:",1,7) + #verifiy choice selection - for routing tracking for debugging + #print("\n\tYour menu choice was: ",strChoice, "Got it.") + +#menu tasks: + + # if they choose selection 1 - send a thank you letter + if (strChoice == '1'): + print ("made it to choice {} : send a donor thank you letter".format(strChoice)) + + #provide a list for visibility + answer = input("do you want to see a list of donors to remind you of the donor's full name? Enter 'y' if you do.").lower() + if answer == 'y': + print("here is a recent list of donors.") + list_out_donors() + + #run routine to get name of the donor you would like to send a letter + fullname = get_donor_info() + + #let them know if donor is in database or not + check_name = is_name_in_the_list(fullname) + + #print out the thank you letter to screen if user in database + if check_name =="yes": + thank_you_email(fullname) + else: + print("\n {} in not in the database. Unable to write standard letter.".format(fullname)) + + pause_foruser() #pause for user to absorb message + continue + + # if they choose selection 2 - add a new donor + elif(strChoice == '2'): + print ("made it to choice {} : add a new donor".format(strChoice)) + + #start ruitine to collect the first and last name of the donor + new_donor_name = get_donor_info() + print (new_donor_name) + + # allow user to verify they typed the name correctly + happy_new_donor_name_yn = verify_input(new_donor_name) + + #if name is acceptable to user, see if it is already in the database of donors + if happy_new_donor_name_yn == "y": + dbcheck_name = is_name_in_the_list(new_donor_name,dictall) + else: #returning to main menu for re-try a name error (maybe misspelled) + print("Returning to main menu so you can try to re-enter your data.") + continue + + #add if new name is new, or return to menu if not a new name + if dbcheck_name == "yes": + print("That name, {}, is already on the list of donors.".format(dbcheck_name.title())) + continue + else: + print("Adding name to donor list.") + add_name_to_db(new_donor_name) + + + # if they choose selection 3 - add new donations for donor + elif(strChoice == '3'): + print ("made it to choice {}: add donation".format(strChoice)) + + #for user to find name + res = str(input("would you like to see a list of donors and their donations? y/n").lower()) + if res == 'y': + print("Here is list of donors with their current donations on record.") + list_out_donors_and_donations() + + #check to see if list is on the donor list + fullname = str(input("type in the full name of the donor.")) + + #reply from list + fullname_on_list = is_name_in_the_list(fullname) + + #if reply is not on list - prompt user to return to menu + if fullname_on_list == "yes": + res2 = 'n' + res2 = input("would you like to add donation for this user? y/n").lower() + while res2 == 'y': + add_donation(fullname.title()) + res2 = input("would you like to add another donation for this user? y/n").lower() + continue + + #if reply is on the list - then add donation for the user + else: + print("Name not found on donor list. Please enter donor into system first") + continue + + + # if they choose selection 4 - print list of donor names + elif(strChoice == '4'): + print ("made it to choice {} : print list of donor names".format(strChoice)) + + list_out_donors() + + pause_foruser() + continue + + # if they choose selection 5 - output donor report + elif(strChoice == '5'): + print ("You made it to choice {}: Output Donor report".format(strChoice)) + print_report() + print_report_sumtotal_summary() + + + pause_foruser() + continue + # if they choose selection 6 - exit + elif(strChoice == '6'): + print ("You made it to choice {} : exit".format(strChoice)) + choice = yornore_Choice("\tAre you sure you want to exit? ") + if choice == "y": + print("\n\tElvis has left the building. Good bye.") + break + else: + print("\nOK, Lets go back to the menu.") + continue + else: + print("You should not have made it to here. There must be a problem in the while loop.") + break + +#salutation to the user +print("\nSee you next time.") + + + diff --git a/students/Boundb3/Session 04/Sherlock_Trigrams_kata14.py b/students/Boundb3/Session 04/Sherlock_Trigrams_kata14.py new file mode 100644 index 0000000..6d4590a --- /dev/null +++ b/students/Boundb3/Session 04/Sherlock_Trigrams_kata14.py @@ -0,0 +1,151 @@ +#"assignment from session 4 - create a trigram from kata 14:by tom swift +#use text file from sherlock from gutenberg" + +#open and count data lines +l=[] +with open("sherlock.txt",mode = "r", encoding= "utf-8") as f: + lines = sum(1 for _ in f) + print ("count of lines in the text file is: ", lines) + +#clean the data and read into a list (one line at a time) + +with open("sherlock.txt",mode = "r", encoding= "utf-8") as f: + for count in range(1,int(lines/10)): #just took a tenth of the whole thing after running the sherlock_short.txt + read_data = f.readline().strip() + read_data = read_data.replace("--"," ") + read_data = read_data.replace("(","") + read_data = read_data.replace(")","") + read_data = read_data.replace(","," ") #changing a comma into a space - to separate when it is split + #read_data = read_data.replace(".","") + read_data = read_data.replace("'","") + read_data = read_data.replace('"',"") + read_data = read_data.lower() + #print(read_data) # i dont need this for the big file + word_list= read_data.split() + l.extend(word_list) + print("l is:", l) + +# top popular words +popular_word_dict = {} +for item in l: + if item not in popular_word_dict: + popular_word_dict[item] = 1 + else: + popular_word_dict[item] += 1 +print ("pop dict is: " ,popular_word_dict) + +# print out word and count pairs: +for i in sorted(popular_word_dict): + print (i, popular_word_dict[i], end=" | ") #but I would like this to be sorted by the value, not key - see below +print("\n***completedsort by key\n") + +#sort on values to find the most popular 20 words +popular_words = sorted(popular_word_dict,key=popular_word_dict.get,reverse=True) #the keys sorted by value +for i in range (1,20): + print("top 20 words completed sort by value::", popular_words[i], end = " | ")## i lost the word's count so I could see how many counts each of these top words got + +print("\n\nsorted pop words", popular_words) + +#"THIS IS VERY COOL" +#trying chapter 11 dictionaries page 130 Think Python - create an inverse dictionary (to have a count in the key) +inverse = {} +for k in popular_word_dict: + + val = popular_word_dict[k] #this grabs the value of K (so the count in this case) + if val not in inverse: #if this is a new count number + inverse[val] = [k] #input the count number as the key, and assign the value of k (the word) to it + else: + inverse[val].append(k) # if the count already has a word, add another word to the count key +print ("*** this is the inverse dict of the popular word dict**** \n",inverse) + +#sort on the keys to know the range of counts in the file (if you wanted) +s_inverse = sorted(inverse, reverse = True) # this just gives me the keys again, at least we know the values +print ("***sorted inverse dict on keys to know the range of popularity counts***", s_inverse) + +#***now we can print the words in the counts for the counts which we want to see (by count) +for k,v in inverse.items(): + if k >= 4: # look at words that occure more than 4 times + print ("count= ", k, "value (the appended words) = ", v, "\n") + + + +#convert the list reference items into a dictionary key and value pair for the Triagrams +list_len= len(l) +d={} +for count in range (1,(list_len-2)): #length minus two to accomodate n+2 in the formula + k = (l[count]+ " " + l[count+1]) + if k not in d: # a new key entry + d[k] = l[(count+2)] + else: + d[k] = (d[k] + " | " + l[(count+2)]) # for a repeated key, so add the new value item to the key's value + +print("d is:",d) + +#size check + +print(list_len) +dict_len = len(d) +print(dict_len) + +#try to print a trigram + +def start_first_two_words(word1="of", word2="the"): #prime the script with the two most popular words from the popular words found above + start_words = word1 + " " + word2 + print("starting 2 words are: ", start_words) + return start_words + +def split_two_words(first_two_words): + w1,w2 = first_two_words.split() + new_w1 = w2 + return new_w1 + +def get_w3(two_word_key): + + possible_w3_values = [] #start a list for enumerate + #print("****the two word key to get values on is:", two_word_key) + values = d[two_word_key] #get all the values for the key and put it in a variable + values = values.strip().split("|") # split up the contents of the variable by the pipe i inserted into the dict + if len(values) == 1: + return values[0] + elif len(values) == 0: + return "game over; no value found for these last two words" + else: # if the contents are greater than one element, then we need to pick one + for element in values: + possible_w3_values.append(element) # load the elements into a list - for picking + #for i,v in enumerate(possible_w3_values): # this was for a manual choice of the word + # print (i,v) + #choice = None + max = int(len(possible_w3_values)) # learn the length of the list of values for this key pair + choice = random.randint(0,max-1)# make a choice from the list (starting with zero to the end of the list) + #choice = int(input("chose which value above to be the next word")) + w3 = possible_w3_values[choice] # pick the list place holder = to the choice + w3 = w3.strip() #clean the word to fit the syntex for when it is used as the two word key + + return w3 + +#main menu + +import random +print("lets start") +input("hit any key to start") + +#get first two words +start_words = start_first_two_words() #can use default or add the two words here (could do a random on the full list) +print("\n Here are the starting words for the story to come:") + +#try for a few rounds - say 1000 words +for i in range (1,1000): + count += 1 + new_w1 = split_two_words(start_words) + w3 = get_w3(start_words) + print(w3, " " , end= "") + #print("to here") + next_two_words = new_w1 +" "+ w3 + #print("got these two words donw", next_two_words) + start_words = next_two_words + if count % 20 == 0: print("\n") # make a new line after twenty words to see easy on screen with a line wrap(at 20) + +print("over; ran out of words or hit 1000 words") + + + diff --git a/students/Boundb3/Session 04/dict_lab.py b/students/Boundb3/Session 04/dict_lab.py new file mode 100644 index 0000000..a3c2ce7 --- /dev/null +++ b/students/Boundb3/Session 04/dict_lab.py @@ -0,0 +1,129 @@ +#This is from session 4 of python 100a +#instructinos for a dict and set lab + +''' +Learning about dictionaries and sets +Goal: +Learn the basic ins and outs of Python dictionaries and sets. + +Procedure +In your student dir in the IntroPython2015 repo, create a session04 dir and put in a new dict_lab.py file. + +The file should be an executable python script. That is to say that one should be able to run the script directly like so: + +Add the file to your clone of the repository and commit changes frequently while working on the following tasks. When you are done, push your changes to GitHub and issue a pull request. +''' + +#create a dictionary +# be lazy and start with a list +d={} +print(type(d)) + +# be lazy and start with a list +l=["city:Seattle", "name:Chris", "cake:chocolate"] +for x in l: + print (x) + k,v = x.split(":") + d[k]=v +#confirm in dictionary format +print(d) + +#delete cake +del d['cake'] +print(d) + +#add entry for fruit with mango +d['fruit'] = "mango" +print(d) + +#display the keys +print(d.keys()) + +#display the values +print(d.values()) + +#confirm booleon for cake in dictionary +res = "cake" in d # this could be like this: just: "in d", or like thins :'in d.keys() +print (res) + +#confirm booleon for mango in dictionary +res2 = "mango" in d.values() +print(res2) + +#using dictionary from before, +d2 = {} +l=["city:Seattle", "name:Chris", "cake:chocolate"] +for x in l: + print (x) + k,v = x.split(":") + d2[k]=v +print("d2 = ", d2) # to confirm + +#make a new dictionary using same keys but with the number of t's in each as its value' +for k,value in d2.items(): + count = 0 + for letter in value: + if letter.lower() == "t": + count +=1 + d2[k] = (count) +print (d2) + +#SETS + +#create sets +s2 = set() +#confirm type +print(type(s2)) +#create more sets: +s3 = set() +s4 = set() + +# sets divisible by some # + +def set_division(top,modulus,set): + for num in range(top): + s = num+1 + if s % modulus == 0: + set.add(s) + return set + +#create set modulus 2 fro range 1-20 +s2 = set_division(20,2,s2) +print ("s2 is" , s2) +print(type(s2)) + +#create set modulus 3 fro range 1-20 +s3 = set_division(20,3,s3) +print ("s3 is" , s3) + +#create set modulus 4 fro range 1-20 +s4 = set_division(20,4,s4) +print ("s4 is" , s4) + +#is set s3 subset of set2 +res3 = s3.issubset(s2) +print (res3) + +#is set s4 subset of set2 +res4 = s4.issubset(s2) +print (res4) + +#create a set with python +s_p = set("Python") +print("s_p is:", s_p) + +#add an i to it +s_p.add("i") +print(s_p) + +#frozen set marathon +s_m = set("marathon") +fs_m = frozenset(s_m) +print(fs_m) + +#union of python (with i) and marathon sets +print("union of python and marathon" ,s_p.union(fs_m)) + + +#intersection of pyton(with i) and marathon +print("intersection of python and marathon" ,s_p.intersection(fs_m)) \ No newline at end of file diff --git a/students/Boundb3/Session 04/sherlock.txt b/students/Boundb3/Session 04/sherlock.txt new file mode 100644 index 0000000..99d5cda --- /dev/null +++ b/students/Boundb3/Session 04/sherlock.txt @@ -0,0 +1,13052 @@ +Project Gutenberg's The Adventures of Sherlock Holmes, by Arthur Conan Doyle + +This eBook is for the use of anyone anywhere at no cost and with +almost no restrictions whatsoever. You may copy it, give it away or +re-use it under the terms of the Project Gutenberg License included +with this eBook or online at www.gutenberg.net + + +Title: The Adventures of Sherlock Holmes + +Author: Arthur Conan Doyle + +Posting Date: April 18, 2011 [EBook #1661] +First Posted: November 29, 2002 + +Language: English + + +*** START OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES *** + + + + +Produced by an anonymous Project Gutenberg volunteer and Jose Menendez + + + + + + + + + +THE ADVENTURES OF SHERLOCK HOLMES + +by + +SIR ARTHUR CONAN DOYLE + + + + I. A Scandal in Bohemia + II. The Red-headed League + III. A Case of Identity + IV. The Boscombe Valley Mystery + V. The Five Orange Pips + VI. The Man with the Twisted Lip + VII. The Adventure of the Blue Carbuncle +VIII. The Adventure of the Speckled Band + IX. The Adventure of the Engineer's Thumb + X. The Adventure of the Noble Bachelor + XI. The Adventure of the Beryl Coronet + XII. The Adventure of the Copper Beeches + + + + +ADVENTURE I. A SCANDAL IN BOHEMIA + +I. + +To Sherlock Holmes she is always THE woman. I have seldom heard +him mention her under any other name. In his eyes she eclipses +and predominates the whole of her sex. It was not that he felt +any emotion akin to love for Irene Adler. All emotions, and that +one particularly, were abhorrent to his cold, precise but +admirably balanced mind. He was, I take it, the most perfect +reasoning and observing machine that the world has seen, but as a +lover he would have placed himself in a false position. He never +spoke of the softer passions, save with a gibe and a sneer. They +were admirable things for the observer--excellent for drawing the +veil from men's motives and actions. But for the trained reasoner +to admit such intrusions into his own delicate and finely +adjusted temperament was to introduce a distracting factor which +might throw a doubt upon all his mental results. Grit in a +sensitive instrument, or a crack in one of his own high-power +lenses, would not be more disturbing than a strong emotion in a +nature such as his. And yet there was but one woman to him, and +that woman was the late Irene Adler, of dubious and questionable +memory. + +I had seen little of Holmes lately. My marriage had drifted us +away from each other. My own complete happiness, and the +home-centred interests which rise up around the man who first +finds himself master of his own establishment, were sufficient to +absorb all my attention, while Holmes, who loathed every form of +society with his whole Bohemian soul, remained in our lodgings in +Baker Street, buried among his old books, and alternating from +week to week between cocaine and ambition, the drowsiness of the +drug, and the fierce energy of his own keen nature. He was still, +as ever, deeply attracted by the study of crime, and occupied his +immense faculties and extraordinary powers of observation in +following out those clues, and clearing up those mysteries which +had been abandoned as hopeless by the official police. From time +to time I heard some vague account of his doings: of his summons +to Odessa in the case of the Trepoff murder, of his clearing up +of the singular tragedy of the Atkinson brothers at Trincomalee, +and finally of the mission which he had accomplished so +delicately and successfully for the reigning family of Holland. +Beyond these signs of his activity, however, which I merely +shared with all the readers of the daily press, I knew little of +my former friend and companion. + +One night--it was on the twentieth of March, 1888--I was +returning from a journey to a patient (for I had now returned to +civil practice), when my way led me through Baker Street. As I +passed the well-remembered door, which must always be associated +in my mind with my wooing, and with the dark incidents of the +Study in Scarlet, I was seized with a keen desire to see Holmes +again, and to know how he was employing his extraordinary powers. +His rooms were brilliantly lit, and, even as I looked up, I saw +his tall, spare figure pass twice in a dark silhouette against +the blind. He was pacing the room swiftly, eagerly, with his head +sunk upon his chest and his hands clasped behind him. To me, who +knew his every mood and habit, his attitude and manner told their +own story. He was at work again. He had risen out of his +drug-created dreams and was hot upon the scent of some new +problem. I rang the bell and was shown up to the chamber which +had formerly been in part my own. + +His manner was not effusive. It seldom was; but he was glad, I +think, to see me. With hardly a word spoken, but with a kindly +eye, he waved me to an armchair, threw across his case of cigars, +and indicated a spirit case and a gasogene in the corner. Then he +stood before the fire and looked me over in his singular +introspective fashion. + +"Wedlock suits you," he remarked. "I think, Watson, that you have +put on seven and a half pounds since I saw you." + +"Seven!" I answered. + +"Indeed, I should have thought a little more. Just a trifle more, +I fancy, Watson. And in practice again, I observe. You did not +tell me that you intended to go into harness." + +"Then, how do you know?" + +"I see it, I deduce it. How do I know that you have been getting +yourself very wet lately, and that you have a most clumsy and +careless servant girl?" + +"My dear Holmes," said I, "this is too much. You would certainly +have been burned, had you lived a few centuries ago. It is true +that I had a country walk on Thursday and came home in a dreadful +mess, but as I have changed my clothes I can't imagine how you +deduce it. As to Mary Jane, she is incorrigible, and my wife has +given her notice, but there, again, I fail to see how you work it +out." + +He chuckled to himself and rubbed his long, nervous hands +together. + +"It is simplicity itself," said he; "my eyes tell me that on the +inside of your left shoe, just where the firelight strikes it, +the leather is scored by six almost parallel cuts. Obviously they +have been caused by someone who has very carelessly scraped round +the edges of the sole in order to remove crusted mud from it. +Hence, you see, my double deduction that you had been out in vile +weather, and that you had a particularly malignant boot-slitting +specimen of the London slavey. As to your practice, if a +gentleman walks into my rooms smelling of iodoform, with a black +mark of nitrate of silver upon his right forefinger, and a bulge +on the right side of his top-hat to show where he has secreted +his stethoscope, I must be dull, indeed, if I do not pronounce +him to be an active member of the medical profession." + +I could not help laughing at the ease with which he explained his +process of deduction. "When I hear you give your reasons," I +remarked, "the thing always appears to me to be so ridiculously +simple that I could easily do it myself, though at each +successive instance of your reasoning I am baffled until you +explain your process. And yet I believe that my eyes are as good +as yours." + +"Quite so," he answered, lighting a cigarette, and throwing +himself down into an armchair. "You see, but you do not observe. +The distinction is clear. For example, you have frequently seen +the steps which lead up from the hall to this room." + +"Frequently." + +"How often?" + +"Well, some hundreds of times." + +"Then how many are there?" + +"How many? I don't know." + +"Quite so! You have not observed. And yet you have seen. That is +just my point. Now, I know that there are seventeen steps, +because I have both seen and observed. By-the-way, since you are +interested in these little problems, and since you are good +enough to chronicle one or two of my trifling experiences, you +may be interested in this." He threw over a sheet of thick, +pink-tinted note-paper which had been lying open upon the table. +"It came by the last post," said he. "Read it aloud." + +The note was undated, and without either signature or address. + +"There will call upon you to-night, at a quarter to eight +o'clock," it said, "a gentleman who desires to consult you upon a +matter of the very deepest moment. Your recent services to one of +the royal houses of Europe have shown that you are one who may +safely be trusted with matters which are of an importance which +can hardly be exaggerated. This account of you we have from all +quarters received. Be in your chamber then at that hour, and do +not take it amiss if your visitor wear a mask." + +"This is indeed a mystery," I remarked. "What do you imagine that +it means?" + +"I have no data yet. It is a capital mistake to theorize before +one has data. Insensibly one begins to twist facts to suit +theories, instead of theories to suit facts. But the note itself. +What do you deduce from it?" + +I carefully examined the writing, and the paper upon which it was +written. + +"The man who wrote it was presumably well to do," I remarked, +endeavouring to imitate my companion's processes. "Such paper +could not be bought under half a crown a packet. It is peculiarly +strong and stiff." + +"Peculiar--that is the very word," said Holmes. "It is not an +English paper at all. Hold it up to the light." + +I did so, and saw a large "E" with a small "g," a "P," and a +large "G" with a small "t" woven into the texture of the paper. + +"What do you make of that?" asked Holmes. + +"The name of the maker, no doubt; or his monogram, rather." + +"Not at all. The 'G' with the small 't' stands for +'Gesellschaft,' which is the German for 'Company.' It is a +customary contraction like our 'Co.' 'P,' of course, stands for +'Papier.' Now for the 'Eg.' Let us glance at our Continental +Gazetteer." He took down a heavy brown volume from his shelves. +"Eglow, Eglonitz--here we are, Egria. It is in a German-speaking +country--in Bohemia, not far from Carlsbad. 'Remarkable as being +the scene of the death of Wallenstein, and for its numerous +glass-factories and paper-mills.' Ha, ha, my boy, what do you +make of that?" His eyes sparkled, and he sent up a great blue +triumphant cloud from his cigarette. + +"The paper was made in Bohemia," I said. + +"Precisely. And the man who wrote the note is a German. Do you +note the peculiar construction of the sentence--'This account of +you we have from all quarters received.' A Frenchman or Russian +could not have written that. It is the German who is so +uncourteous to his verbs. It only remains, therefore, to discover +what is wanted by this German who writes upon Bohemian paper and +prefers wearing a mask to showing his face. And here he comes, if +I am not mistaken, to resolve all our doubts." + +As he spoke there was the sharp sound of horses' hoofs and +grating wheels against the curb, followed by a sharp pull at the +bell. Holmes whistled. + +"A pair, by the sound," said he. "Yes," he continued, glancing +out of the window. "A nice little brougham and a pair of +beauties. A hundred and fifty guineas apiece. There's money in +this case, Watson, if there is nothing else." + +"I think that I had better go, Holmes." + +"Not a bit, Doctor. Stay where you are. I am lost without my +Boswell. And this promises to be interesting. It would be a pity +to miss it." + +"But your client--" + +"Never mind him. I may want your help, and so may he. Here he +comes. Sit down in that armchair, Doctor, and give us your best +attention." + +A slow and heavy step, which had been heard upon the stairs and +in the passage, paused immediately outside the door. Then there +was a loud and authoritative tap. + +"Come in!" said Holmes. + +A man entered who could hardly have been less than six feet six +inches in height, with the chest and limbs of a Hercules. His +dress was rich with a richness which would, in England, be looked +upon as akin to bad taste. Heavy bands of astrakhan were slashed +across the sleeves and fronts of his double-breasted coat, while +the deep blue cloak which was thrown over his shoulders was lined +with flame-coloured silk and secured at the neck with a brooch +which consisted of a single flaming beryl. Boots which extended +halfway up his calves, and which were trimmed at the tops with +rich brown fur, completed the impression of barbaric opulence +which was suggested by his whole appearance. He carried a +broad-brimmed hat in his hand, while he wore across the upper +part of his face, extending down past the cheekbones, a black +vizard mask, which he had apparently adjusted that very moment, +for his hand was still raised to it as he entered. From the lower +part of the face he appeared to be a man of strong character, +with a thick, hanging lip, and a long, straight chin suggestive +of resolution pushed to the length of obstinacy. + +"You had my note?" he asked with a deep harsh voice and a +strongly marked German accent. "I told you that I would call." He +looked from one to the other of us, as if uncertain which to +address. + +"Pray take a seat," said Holmes. "This is my friend and +colleague, Dr. Watson, who is occasionally good enough to help me +in my cases. Whom have I the honour to address?" + +"You may address me as the Count Von Kramm, a Bohemian nobleman. +I understand that this gentleman, your friend, is a man of honour +and discretion, whom I may trust with a matter of the most +extreme importance. If not, I should much prefer to communicate +with you alone." + +I rose to go, but Holmes caught me by the wrist and pushed me +back into my chair. "It is both, or none," said he. "You may say +before this gentleman anything which you may say to me." + +The Count shrugged his broad shoulders. "Then I must begin," said +he, "by binding you both to absolute secrecy for two years; at +the end of that time the matter will be of no importance. At +present it is not too much to say that it is of such weight it +may have an influence upon European history." + +"I promise," said Holmes. + +"And I." + +"You will excuse this mask," continued our strange visitor. "The +august person who employs me wishes his agent to be unknown to +you, and I may confess at once that the title by which I have +just called myself is not exactly my own." + +"I was aware of it," said Holmes dryly. + +"The circumstances are of great delicacy, and every precaution +has to be taken to quench what might grow to be an immense +scandal and seriously compromise one of the reigning families of +Europe. To speak plainly, the matter implicates the great House +of Ormstein, hereditary kings of Bohemia." + +"I was also aware of that," murmured Holmes, settling himself +down in his armchair and closing his eyes. + +Our visitor glanced with some apparent surprise at the languid, +lounging figure of the man who had been no doubt depicted to him +as the most incisive reasoner and most energetic agent in Europe. +Holmes slowly reopened his eyes and looked impatiently at his +gigantic client. + +"If your Majesty would condescend to state your case," he +remarked, "I should be better able to advise you." + +The man sprang from his chair and paced up and down the room in +uncontrollable agitation. Then, with a gesture of desperation, he +tore the mask from his face and hurled it upon the ground. "You +are right," he cried; "I am the King. Why should I attempt to +conceal it?" + +"Why, indeed?" murmured Holmes. "Your Majesty had not spoken +before I was aware that I was addressing Wilhelm Gottsreich +Sigismond von Ormstein, Grand Duke of Cassel-Felstein, and +hereditary King of Bohemia." + +"But you can understand," said our strange visitor, sitting down +once more and passing his hand over his high white forehead, "you +can understand that I am not accustomed to doing such business in +my own person. Yet the matter was so delicate that I could not +confide it to an agent without putting myself in his power. I +have come incognito from Prague for the purpose of consulting +you." + +"Then, pray consult," said Holmes, shutting his eyes once more. + +"The facts are briefly these: Some five years ago, during a +lengthy visit to Warsaw, I made the acquaintance of the well-known +adventuress, Irene Adler. The name is no doubt familiar to you." + +"Kindly look her up in my index, Doctor," murmured Holmes without +opening his eyes. For many years he had adopted a system of +docketing all paragraphs concerning men and things, so that it +was difficult to name a subject or a person on which he could not +at once furnish information. In this case I found her biography +sandwiched in between that of a Hebrew rabbi and that of a +staff-commander who had written a monograph upon the deep-sea +fishes. + +"Let me see!" said Holmes. "Hum! Born in New Jersey in the year +1858. Contralto--hum! La Scala, hum! Prima donna Imperial Opera +of Warsaw--yes! Retired from operatic stage--ha! Living in +London--quite so! Your Majesty, as I understand, became entangled +with this young person, wrote her some compromising letters, and +is now desirous of getting those letters back." + +"Precisely so. But how--" + +"Was there a secret marriage?" + +"None." + +"No legal papers or certificates?" + +"None." + +"Then I fail to follow your Majesty. If this young person should +produce her letters for blackmailing or other purposes, how is +she to prove their authenticity?" + +"There is the writing." + +"Pooh, pooh! Forgery." + +"My private note-paper." + +"Stolen." + +"My own seal." + +"Imitated." + +"My photograph." + +"Bought." + +"We were both in the photograph." + +"Oh, dear! That is very bad! Your Majesty has indeed committed an +indiscretion." + +"I was mad--insane." + +"You have compromised yourself seriously." + +"I was only Crown Prince then. I was young. I am but thirty now." + +"It must be recovered." + +"We have tried and failed." + +"Your Majesty must pay. It must be bought." + +"She will not sell." + +"Stolen, then." + +"Five attempts have been made. Twice burglars in my pay ransacked +her house. Once we diverted her luggage when she travelled. Twice +she has been waylaid. There has been no result." + +"No sign of it?" + +"Absolutely none." + +Holmes laughed. "It is quite a pretty little problem," said he. + +"But a very serious one to me," returned the King reproachfully. + +"Very, indeed. And what does she propose to do with the +photograph?" + +"To ruin me." + +"But how?" + +"I am about to be married." + +"So I have heard." + +"To Clotilde Lothman von Saxe-Meningen, second daughter of the +King of Scandinavia. You may know the strict principles of her +family. She is herself the very soul of delicacy. A shadow of a +doubt as to my conduct would bring the matter to an end." + +"And Irene Adler?" + +"Threatens to send them the photograph. And she will do it. I +know that she will do it. You do not know her, but she has a soul +of steel. She has the face of the most beautiful of women, and +the mind of the most resolute of men. Rather than I should marry +another woman, there are no lengths to which she would not +go--none." + +"You are sure that she has not sent it yet?" + +"I am sure." + +"And why?" + +"Because she has said that she would send it on the day when the +betrothal was publicly proclaimed. That will be next Monday." + +"Oh, then we have three days yet," said Holmes with a yawn. "That +is very fortunate, as I have one or two matters of importance to +look into just at present. Your Majesty will, of course, stay in +London for the present?" + +"Certainly. You will find me at the Langham under the name of the +Count Von Kramm." + +"Then I shall drop you a line to let you know how we progress." + +"Pray do so. I shall be all anxiety." + +"Then, as to money?" + +"You have carte blanche." + +"Absolutely?" + +"I tell you that I would give one of the provinces of my kingdom +to have that photograph." + +"And for present expenses?" + +The King took a heavy chamois leather bag from under his cloak +and laid it on the table. + +"There are three hundred pounds in gold and seven hundred in +notes," he said. + +Holmes scribbled a receipt upon a sheet of his note-book and +handed it to him. + +"And Mademoiselle's address?" he asked. + +"Is Briony Lodge, Serpentine Avenue, St. John's Wood." + +Holmes took a note of it. "One other question," said he. "Was the +photograph a cabinet?" + +"It was." + +"Then, good-night, your Majesty, and I trust that we shall soon +have some good news for you. And good-night, Watson," he added, +as the wheels of the royal brougham rolled down the street. "If +you will be good enough to call to-morrow afternoon at three +o'clock I should like to chat this little matter over with you." + + +II. + +At three o'clock precisely I was at Baker Street, but Holmes had +not yet returned. The landlady informed me that he had left the +house shortly after eight o'clock in the morning. I sat down +beside the fire, however, with the intention of awaiting him, +however long he might be. I was already deeply interested in his +inquiry, for, though it was surrounded by none of the grim and +strange features which were associated with the two crimes which +I have already recorded, still, the nature of the case and the +exalted station of his client gave it a character of its own. +Indeed, apart from the nature of the investigation which my +friend had on hand, there was something in his masterly grasp of +a situation, and his keen, incisive reasoning, which made it a +pleasure to me to study his system of work, and to follow the +quick, subtle methods by which he disentangled the most +inextricable mysteries. So accustomed was I to his invariable +success that the very possibility of his failing had ceased to +enter into my head. + +It was close upon four before the door opened, and a +drunken-looking groom, ill-kempt and side-whiskered, with an +inflamed face and disreputable clothes, walked into the room. +Accustomed as I was to my friend's amazing powers in the use of +disguises, I had to look three times before I was certain that it +was indeed he. With a nod he vanished into the bedroom, whence he +emerged in five minutes tweed-suited and respectable, as of old. +Putting his hands into his pockets, he stretched out his legs in +front of the fire and laughed heartily for some minutes. + +"Well, really!" he cried, and then he choked and laughed again +until he was obliged to lie back, limp and helpless, in the +chair. + +"What is it?" + +"It's quite too funny. I am sure you could never guess how I +employed my morning, or what I ended by doing." + +"I can't imagine. I suppose that you have been watching the +habits, and perhaps the house, of Miss Irene Adler." + +"Quite so; but the sequel was rather unusual. I will tell you, +however. I left the house a little after eight o'clock this +morning in the character of a groom out of work. There is a +wonderful sympathy and freemasonry among horsey men. Be one of +them, and you will know all that there is to know. I soon found +Briony Lodge. It is a bijou villa, with a garden at the back, but +built out in front right up to the road, two stories. Chubb lock +to the door. Large sitting-room on the right side, well +furnished, with long windows almost to the floor, and those +preposterous English window fasteners which a child could open. +Behind there was nothing remarkable, save that the passage window +could be reached from the top of the coach-house. I walked round +it and examined it closely from every point of view, but without +noting anything else of interest. + +"I then lounged down the street and found, as I expected, that +there was a mews in a lane which runs down by one wall of the +garden. I lent the ostlers a hand in rubbing down their horses, +and received in exchange twopence, a glass of half and half, two +fills of shag tobacco, and as much information as I could desire +about Miss Adler, to say nothing of half a dozen other people in +the neighbourhood in whom I was not in the least interested, but +whose biographies I was compelled to listen to." + +"And what of Irene Adler?" I asked. + +"Oh, she has turned all the men's heads down in that part. She is +the daintiest thing under a bonnet on this planet. So say the +Serpentine-mews, to a man. She lives quietly, sings at concerts, +drives out at five every day, and returns at seven sharp for +dinner. Seldom goes out at other times, except when she sings. +Has only one male visitor, but a good deal of him. He is dark, +handsome, and dashing, never calls less than once a day, and +often twice. He is a Mr. Godfrey Norton, of the Inner Temple. See +the advantages of a cabman as a confidant. They had driven him +home a dozen times from Serpentine-mews, and knew all about him. +When I had listened to all they had to tell, I began to walk up +and down near Briony Lodge once more, and to think over my plan +of campaign. + +"This Godfrey Norton was evidently an important factor in the +matter. He was a lawyer. That sounded ominous. What was the +relation between them, and what the object of his repeated +visits? Was she his client, his friend, or his mistress? If the +former, she had probably transferred the photograph to his +keeping. If the latter, it was less likely. On the issue of this +question depended whether I should continue my work at Briony +Lodge, or turn my attention to the gentleman's chambers in the +Temple. It was a delicate point, and it widened the field of my +inquiry. I fear that I bore you with these details, but I have to +let you see my little difficulties, if you are to understand the +situation." + +"I am following you closely," I answered. + +"I was still balancing the matter in my mind when a hansom cab +drove up to Briony Lodge, and a gentleman sprang out. He was a +remarkably handsome man, dark, aquiline, and moustached--evidently +the man of whom I had heard. He appeared to be in a +great hurry, shouted to the cabman to wait, and brushed past the +maid who opened the door with the air of a man who was thoroughly +at home. + +"He was in the house about half an hour, and I could catch +glimpses of him in the windows of the sitting-room, pacing up and +down, talking excitedly, and waving his arms. Of her I could see +nothing. Presently he emerged, looking even more flurried than +before. As he stepped up to the cab, he pulled a gold watch from +his pocket and looked at it earnestly, 'Drive like the devil,' he +shouted, 'first to Gross & Hankey's in Regent Street, and then to +the Church of St. Monica in the Edgeware Road. Half a guinea if +you do it in twenty minutes!' + +"Away they went, and I was just wondering whether I should not do +well to follow them when up the lane came a neat little landau, +the coachman with his coat only half-buttoned, and his tie under +his ear, while all the tags of his harness were sticking out of +the buckles. It hadn't pulled up before she shot out of the hall +door and into it. I only caught a glimpse of her at the moment, +but she was a lovely woman, with a face that a man might die for. + +"'The Church of St. Monica, John,' she cried, 'and half a +sovereign if you reach it in twenty minutes.' + +"This was quite too good to lose, Watson. I was just balancing +whether I should run for it, or whether I should perch behind her +landau when a cab came through the street. The driver looked +twice at such a shabby fare, but I jumped in before he could +object. 'The Church of St. Monica,' said I, 'and half a sovereign +if you reach it in twenty minutes.' It was twenty-five minutes to +twelve, and of course it was clear enough what was in the wind. + +"My cabby drove fast. I don't think I ever drove faster, but the +others were there before us. The cab and the landau with their +steaming horses were in front of the door when I arrived. I paid +the man and hurried into the church. There was not a soul there +save the two whom I had followed and a surpliced clergyman, who +seemed to be expostulating with them. They were all three +standing in a knot in front of the altar. I lounged up the side +aisle like any other idler who has dropped into a church. +Suddenly, to my surprise, the three at the altar faced round to +me, and Godfrey Norton came running as hard as he could towards +me. + +"'Thank God,' he cried. 'You'll do. Come! Come!' + +"'What then?' I asked. + +"'Come, man, come, only three minutes, or it won't be legal.' + +"I was half-dragged up to the altar, and before I knew where I was +I found myself mumbling responses which were whispered in my ear, +and vouching for things of which I knew nothing, and generally +assisting in the secure tying up of Irene Adler, spinster, to +Godfrey Norton, bachelor. It was all done in an instant, and +there was the gentleman thanking me on the one side and the lady +on the other, while the clergyman beamed on me in front. It was +the most preposterous position in which I ever found myself in my +life, and it was the thought of it that started me laughing just +now. It seems that there had been some informality about their +license, that the clergyman absolutely refused to marry them +without a witness of some sort, and that my lucky appearance +saved the bridegroom from having to sally out into the streets in +search of a best man. The bride gave me a sovereign, and I mean +to wear it on my watch-chain in memory of the occasion." + +"This is a very unexpected turn of affairs," said I; "and what +then?" + +"Well, I found my plans very seriously menaced. It looked as if +the pair might take an immediate departure, and so necessitate +very prompt and energetic measures on my part. At the church +door, however, they separated, he driving back to the Temple, and +she to her own house. 'I shall drive out in the park at five as +usual,' she said as she left him. I heard no more. They drove +away in different directions, and I went off to make my own +arrangements." + +"Which are?" + +"Some cold beef and a glass of beer," he answered, ringing the +bell. "I have been too busy to think of food, and I am likely to +be busier still this evening. By the way, Doctor, I shall want +your co-operation." + +"I shall be delighted." + +"You don't mind breaking the law?" + +"Not in the least." + +"Nor running a chance of arrest?" + +"Not in a good cause." + +"Oh, the cause is excellent!" + +"Then I am your man." + +"I was sure that I might rely on you." + +"But what is it you wish?" + +"When Mrs. Turner has brought in the tray I will make it clear to +you. Now," he said as he turned hungrily on the simple fare that +our landlady had provided, "I must discuss it while I eat, for I +have not much time. It is nearly five now. In two hours we must +be on the scene of action. Miss Irene, or Madame, rather, returns +from her drive at seven. We must be at Briony Lodge to meet her." + +"And what then?" + +"You must leave that to me. I have already arranged what is to +occur. There is only one point on which I must insist. You must +not interfere, come what may. You understand?" + +"I am to be neutral?" + +"To do nothing whatever. There will probably be some small +unpleasantness. Do not join in it. It will end in my being +conveyed into the house. Four or five minutes afterwards the +sitting-room window will open. You are to station yourself close +to that open window." + +"Yes." + +"You are to watch me, for I will be visible to you." + +"Yes." + +"And when I raise my hand--so--you will throw into the room what +I give you to throw, and will, at the same time, raise the cry of +fire. You quite follow me?" + +"Entirely." + +"It is nothing very formidable," he said, taking a long cigar-shaped +roll from his pocket. "It is an ordinary plumber's smoke-rocket, +fitted with a cap at either end to make it self-lighting. +Your task is confined to that. When you raise your cry of fire, +it will be taken up by quite a number of people. You may then +walk to the end of the street, and I will rejoin you in ten +minutes. I hope that I have made myself clear?" + +"I am to remain neutral, to get near the window, to watch you, +and at the signal to throw in this object, then to raise the cry +of fire, and to wait you at the corner of the street." + +"Precisely." + +"Then you may entirely rely on me." + +"That is excellent. I think, perhaps, it is almost time that I +prepare for the new role I have to play." + +He disappeared into his bedroom and returned in a few minutes in +the character of an amiable and simple-minded Nonconformist +clergyman. His broad black hat, his baggy trousers, his white +tie, his sympathetic smile, and general look of peering and +benevolent curiosity were such as Mr. John Hare alone could have +equalled. It was not merely that Holmes changed his costume. His +expression, his manner, his very soul seemed to vary with every +fresh part that he assumed. The stage lost a fine actor, even as +science lost an acute reasoner, when he became a specialist in +crime. + +It was a quarter past six when we left Baker Street, and it still +wanted ten minutes to the hour when we found ourselves in +Serpentine Avenue. It was already dusk, and the lamps were just +being lighted as we paced up and down in front of Briony Lodge, +waiting for the coming of its occupant. The house was just such +as I had pictured it from Sherlock Holmes' succinct description, +but the locality appeared to be less private than I expected. On +the contrary, for a small street in a quiet neighbourhood, it was +remarkably animated. There was a group of shabbily dressed men +smoking and laughing in a corner, a scissors-grinder with his +wheel, two guardsmen who were flirting with a nurse-girl, and +several well-dressed young men who were lounging up and down with +cigars in their mouths. + +"You see," remarked Holmes, as we paced to and fro in front of +the house, "this marriage rather simplifies matters. The +photograph becomes a double-edged weapon now. The chances are +that she would be as averse to its being seen by Mr. Godfrey +Norton, as our client is to its coming to the eyes of his +princess. Now the question is, Where are we to find the +photograph?" + +"Where, indeed?" + +"It is most unlikely that she carries it about with her. It is +cabinet size. Too large for easy concealment about a woman's +dress. She knows that the King is capable of having her waylaid +and searched. Two attempts of the sort have already been made. We +may take it, then, that she does not carry it about with her." + +"Where, then?" + +"Her banker or her lawyer. There is that double possibility. But +I am inclined to think neither. Women are naturally secretive, +and they like to do their own secreting. Why should she hand it +over to anyone else? She could trust her own guardianship, but +she could not tell what indirect or political influence might be +brought to bear upon a business man. Besides, remember that she +had resolved to use it within a few days. It must be where she +can lay her hands upon it. It must be in her own house." + +"But it has twice been burgled." + +"Pshaw! They did not know how to look." + +"But how will you look?" + +"I will not look." + +"What then?" + +"I will get her to show me." + +"But she will refuse." + +"She will not be able to. But I hear the rumble of wheels. It is +her carriage. Now carry out my orders to the letter." + +As he spoke the gleam of the side-lights of a carriage came round +the curve of the avenue. It was a smart little landau which +rattled up to the door of Briony Lodge. As it pulled up, one of +the loafing men at the corner dashed forward to open the door in +the hope of earning a copper, but was elbowed away by another +loafer, who had rushed up with the same intention. A fierce +quarrel broke out, which was increased by the two guardsmen, who +took sides with one of the loungers, and by the scissors-grinder, +who was equally hot upon the other side. A blow was struck, and +in an instant the lady, who had stepped from her carriage, was +the centre of a little knot of flushed and struggling men, who +struck savagely at each other with their fists and sticks. Holmes +dashed into the crowd to protect the lady; but just as he reached +her he gave a cry and dropped to the ground, with the blood +running freely down his face. At his fall the guardsmen took to +their heels in one direction and the loungers in the other, while +a number of better-dressed people, who had watched the scuffle +without taking part in it, crowded in to help the lady and to +attend to the injured man. Irene Adler, as I will still call her, +had hurried up the steps; but she stood at the top with her +superb figure outlined against the lights of the hall, looking +back into the street. + +"Is the poor gentleman much hurt?" she asked. + +"He is dead," cried several voices. + +"No, no, there's life in him!" shouted another. "But he'll be +gone before you can get him to hospital." + +"He's a brave fellow," said a woman. "They would have had the +lady's purse and watch if it hadn't been for him. They were a +gang, and a rough one, too. Ah, he's breathing now." + +"He can't lie in the street. May we bring him in, marm?" + +"Surely. Bring him into the sitting-room. There is a comfortable +sofa. This way, please!" + +Slowly and solemnly he was borne into Briony Lodge and laid out +in the principal room, while I still observed the proceedings +from my post by the window. The lamps had been lit, but the +blinds had not been drawn, so that I could see Holmes as he lay +upon the couch. I do not know whether he was seized with +compunction at that moment for the part he was playing, but I +know that I never felt more heartily ashamed of myself in my life +than when I saw the beautiful creature against whom I was +conspiring, or the grace and kindliness with which she waited +upon the injured man. And yet it would be the blackest treachery +to Holmes to draw back now from the part which he had intrusted +to me. I hardened my heart, and took the smoke-rocket from under +my ulster. After all, I thought, we are not injuring her. We are +but preventing her from injuring another. + +Holmes had sat up upon the couch, and I saw him motion like a man +who is in need of air. A maid rushed across and threw open the +window. At the same instant I saw him raise his hand and at the +signal I tossed my rocket into the room with a cry of "Fire!" The +word was no sooner out of my mouth than the whole crowd of +spectators, well dressed and ill--gentlemen, ostlers, and +servant-maids--joined in a general shriek of "Fire!" Thick clouds +of smoke curled through the room and out at the open window. I +caught a glimpse of rushing figures, and a moment later the voice +of Holmes from within assuring them that it was a false alarm. +Slipping through the shouting crowd I made my way to the corner +of the street, and in ten minutes was rejoiced to find my +friend's arm in mine, and to get away from the scene of uproar. +He walked swiftly and in silence for some few minutes until we +had turned down one of the quiet streets which lead towards the +Edgeware Road. + +"You did it very nicely, Doctor," he remarked. "Nothing could +have been better. It is all right." + +"You have the photograph?" + +"I know where it is." + +"And how did you find out?" + +"She showed me, as I told you she would." + +"I am still in the dark." + +"I do not wish to make a mystery," said he, laughing. "The matter +was perfectly simple. You, of course, saw that everyone in the +street was an accomplice. They were all engaged for the evening." + +"I guessed as much." + +"Then, when the row broke out, I had a little moist red paint in +the palm of my hand. I rushed forward, fell down, clapped my hand +to my face, and became a piteous spectacle. It is an old trick." + +"That also I could fathom." + +"Then they carried me in. She was bound to have me in. What else +could she do? And into her sitting-room, which was the very room +which I suspected. It lay between that and her bedroom, and I was +determined to see which. They laid me on a couch, I motioned for +air, they were compelled to open the window, and you had your +chance." + +"How did that help you?" + +"It was all-important. When a woman thinks that her house is on +fire, her instinct is at once to rush to the thing which she +values most. It is a perfectly overpowering impulse, and I have +more than once taken advantage of it. In the case of the +Darlington substitution scandal it was of use to me, and also in +the Arnsworth Castle business. A married woman grabs at her baby; +an unmarried one reaches for her jewel-box. Now it was clear to +me that our lady of to-day had nothing in the house more precious +to her than what we are in quest of. She would rush to secure it. +The alarm of fire was admirably done. The smoke and shouting were +enough to shake nerves of steel. She responded beautifully. The +photograph is in a recess behind a sliding panel just above the +right bell-pull. She was there in an instant, and I caught a +glimpse of it as she half-drew it out. When I cried out that it +was a false alarm, she replaced it, glanced at the rocket, rushed +from the room, and I have not seen her since. I rose, and, making +my excuses, escaped from the house. I hesitated whether to +attempt to secure the photograph at once; but the coachman had +come in, and as he was watching me narrowly it seemed safer to +wait. A little over-precipitance may ruin all." + +"And now?" I asked. + +"Our quest is practically finished. I shall call with the King +to-morrow, and with you, if you care to come with us. We will be +shown into the sitting-room to wait for the lady, but it is +probable that when she comes she may find neither us nor the +photograph. It might be a satisfaction to his Majesty to regain +it with his own hands." + +"And when will you call?" + +"At eight in the morning. She will not be up, so that we shall +have a clear field. Besides, we must be prompt, for this marriage +may mean a complete change in her life and habits. I must wire to +the King without delay." + +We had reached Baker Street and had stopped at the door. He was +searching his pockets for the key when someone passing said: + +"Good-night, Mister Sherlock Holmes." + +There were several people on the pavement at the time, but the +greeting appeared to come from a slim youth in an ulster who had +hurried by. + +"I've heard that voice before," said Holmes, staring down the +dimly lit street. "Now, I wonder who the deuce that could have +been." + + +III. + +I slept at Baker Street that night, and we were engaged upon our +toast and coffee in the morning when the King of Bohemia rushed +into the room. + +"You have really got it!" he cried, grasping Sherlock Holmes by +either shoulder and looking eagerly into his face. + +"Not yet." + +"But you have hopes?" + +"I have hopes." + +"Then, come. I am all impatience to be gone." + +"We must have a cab." + +"No, my brougham is waiting." + +"Then that will simplify matters." We descended and started off +once more for Briony Lodge. + +"Irene Adler is married," remarked Holmes. + +"Married! When?" + +"Yesterday." + +"But to whom?" + +"To an English lawyer named Norton." + +"But she could not love him." + +"I am in hopes that she does." + +"And why in hopes?" + +"Because it would spare your Majesty all fear of future +annoyance. If the lady loves her husband, she does not love your +Majesty. If she does not love your Majesty, there is no reason +why she should interfere with your Majesty's plan." + +"It is true. And yet--Well! I wish she had been of my own +station! What a queen she would have made!" He relapsed into a +moody silence, which was not broken until we drew up in +Serpentine Avenue. + +The door of Briony Lodge was open, and an elderly woman stood +upon the steps. She watched us with a sardonic eye as we stepped +from the brougham. + +"Mr. Sherlock Holmes, I believe?" said she. + +"I am Mr. Holmes," answered my companion, looking at her with a +questioning and rather startled gaze. + +"Indeed! My mistress told me that you were likely to call. She +left this morning with her husband by the 5:15 train from Charing +Cross for the Continent." + +"What!" Sherlock Holmes staggered back, white with chagrin and +surprise. "Do you mean that she has left England?" + +"Never to return." + +"And the papers?" asked the King hoarsely. "All is lost." + +"We shall see." He pushed past the servant and rushed into the +drawing-room, followed by the King and myself. The furniture was +scattered about in every direction, with dismantled shelves and +open drawers, as if the lady had hurriedly ransacked them before +her flight. Holmes rushed at the bell-pull, tore back a small +sliding shutter, and, plunging in his hand, pulled out a +photograph and a letter. The photograph was of Irene Adler +herself in evening dress, the letter was superscribed to +"Sherlock Holmes, Esq. To be left till called for." My friend +tore it open and we all three read it together. It was dated at +midnight of the preceding night and ran in this way: + +"MY DEAR MR. SHERLOCK HOLMES,--You really did it very well. You +took me in completely. Until after the alarm of fire, I had not a +suspicion. But then, when I found how I had betrayed myself, I +began to think. I had been warned against you months ago. I had +been told that if the King employed an agent it would certainly +be you. And your address had been given me. Yet, with all this, +you made me reveal what you wanted to know. Even after I became +suspicious, I found it hard to think evil of such a dear, kind +old clergyman. But, you know, I have been trained as an actress +myself. Male costume is nothing new to me. I often take advantage +of the freedom which it gives. I sent John, the coachman, to +watch you, ran up stairs, got into my walking-clothes, as I call +them, and came down just as you departed. + +"Well, I followed you to your door, and so made sure that I was +really an object of interest to the celebrated Mr. Sherlock +Holmes. Then I, rather imprudently, wished you good-night, and +started for the Temple to see my husband. + +"We both thought the best resource was flight, when pursued by +so formidable an antagonist; so you will find the nest empty when +you call to-morrow. As to the photograph, your client may rest in +peace. I love and am loved by a better man than he. The King may +do what he will without hindrance from one whom he has cruelly +wronged. I keep it only to safeguard myself, and to preserve a +weapon which will always secure me from any steps which he might +take in the future. I leave a photograph which he might care to +possess; and I remain, dear Mr. Sherlock Holmes, + + "Very truly yours, + "IRENE NORTON, ne ADLER." + +"What a woman--oh, what a woman!" cried the King of Bohemia, when +we had all three read this epistle. "Did I not tell you how quick +and resolute she was? Would she not have made an admirable queen? +Is it not a pity that she was not on my level?" + +"From what I have seen of the lady she seems indeed to be on a +very different level to your Majesty," said Holmes coldly. "I am +sorry that I have not been able to bring your Majesty's business +to a more successful conclusion." + +"On the contrary, my dear sir," cried the King; "nothing could be +more successful. I know that her word is inviolate. The +photograph is now as safe as if it were in the fire." + +"I am glad to hear your Majesty say so." + +"I am immensely indebted to you. Pray tell me in what way I can +reward you. This ring--" He slipped an emerald snake ring from +his finger and held it out upon the palm of his hand. + +"Your Majesty has something which I should value even more +highly," said Holmes. + +"You have but to name it." + +"This photograph!" + +The King stared at him in amazement. + +"Irene's photograph!" he cried. "Certainly, if you wish it." + +"I thank your Majesty. Then there is no more to be done in the +matter. I have the honour to wish you a very good-morning." He +bowed, and, turning away without observing the hand which the +King had stretched out to him, he set off in my company for his +chambers. + +And that was how a great scandal threatened to affect the kingdom +of Bohemia, and how the best plans of Mr. Sherlock Holmes were +beaten by a woman's wit. He used to make merry over the +cleverness of women, but I have not heard him do it of late. And +when he speaks of Irene Adler, or when he refers to her +photograph, it is always under the honourable title of the woman. + + + +ADVENTURE II. THE RED-HEADED LEAGUE + +I had called upon my friend, Mr. Sherlock Holmes, one day in the +autumn of last year and found him in deep conversation with a +very stout, florid-faced, elderly gentleman with fiery red hair. +With an apology for my intrusion, I was about to withdraw when +Holmes pulled me abruptly into the room and closed the door +behind me. + +"You could not possibly have come at a better time, my dear +Watson," he said cordially. + +"I was afraid that you were engaged." + +"So I am. Very much so." + +"Then I can wait in the next room." + +"Not at all. This gentleman, Mr. Wilson, has been my partner and +helper in many of my most successful cases, and I have no +doubt that he will be of the utmost use to me in yours also." + +The stout gentleman half rose from his chair and gave a bob of +greeting, with a quick little questioning glance from his small +fat-encircled eyes. + +"Try the settee," said Holmes, relapsing into his armchair and +putting his fingertips together, as was his custom when in +judicial moods. "I know, my dear Watson, that you share my love +of all that is bizarre and outside the conventions and humdrum +routine of everyday life. You have shown your relish for it by +the enthusiasm which has prompted you to chronicle, and, if you +will excuse my saying so, somewhat to embellish so many of my own +little adventures." + +"Your cases have indeed been of the greatest interest to me," I +observed. + +"You will remember that I remarked the other day, just before we +went into the very simple problem presented by Miss Mary +Sutherland, that for strange effects and extraordinary +combinations we must go to life itself, which is always far more +daring than any effort of the imagination." + +"A proposition which I took the liberty of doubting." + +"You did, Doctor, but none the less you must come round to my +view, for otherwise I shall keep on piling fact upon fact on you +until your reason breaks down under them and acknowledges me to +be right. Now, Mr. Jabez Wilson here has been good enough to call +upon me this morning, and to begin a narrative which promises to +be one of the most singular which I have listened to for some +time. You have heard me remark that the strangest and most unique +things are very often connected not with the larger but with the +smaller crimes, and occasionally, indeed, where there is room for +doubt whether any positive crime has been committed. As far as I +have heard it is impossible for me to say whether the present +case is an instance of crime or not, but the course of events is +certainly among the most singular that I have ever listened to. +Perhaps, Mr. Wilson, you would have the great kindness to +recommence your narrative. I ask you not merely because my friend +Dr. Watson has not heard the opening part but also because the +peculiar nature of the story makes me anxious to have every +possible detail from your lips. As a rule, when I have heard some +slight indication of the course of events, I am able to guide +myself by the thousands of other similar cases which occur to my +memory. In the present instance I am forced to admit that the +facts are, to the best of my belief, unique." + +The portly client puffed out his chest with an appearance of some +little pride and pulled a dirty and wrinkled newspaper from the +inside pocket of his greatcoat. As he glanced down the +advertisement column, with his head thrust forward and the paper +flattened out upon his knee, I took a good look at the man and +endeavoured, after the fashion of my companion, to read the +indications which might be presented by his dress or appearance. + +I did not gain very much, however, by my inspection. Our visitor +bore every mark of being an average commonplace British +tradesman, obese, pompous, and slow. He wore rather baggy grey +shepherd's check trousers, a not over-clean black frock-coat, +unbuttoned in the front, and a drab waistcoat with a heavy brassy +Albert chain, and a square pierced bit of metal dangling down as +an ornament. A frayed top-hat and a faded brown overcoat with a +wrinkled velvet collar lay upon a chair beside him. Altogether, +look as I would, there was nothing remarkable about the man save +his blazing red head, and the expression of extreme chagrin and +discontent upon his features. + +Sherlock Holmes' quick eye took in my occupation, and he shook +his head with a smile as he noticed my questioning glances. +"Beyond the obvious facts that he has at some time done manual +labour, that he takes snuff, that he is a Freemason, that he has +been in China, and that he has done a considerable amount of +writing lately, I can deduce nothing else." + +Mr. Jabez Wilson started up in his chair, with his forefinger +upon the paper, but his eyes upon my companion. + +"How, in the name of good-fortune, did you know all that, Mr. +Holmes?" he asked. "How did you know, for example, that I did +manual labour. It's as true as gospel, for I began as a ship's +carpenter." + +"Your hands, my dear sir. Your right hand is quite a size larger +than your left. You have worked with it, and the muscles are more +developed." + +"Well, the snuff, then, and the Freemasonry?" + +"I won't insult your intelligence by telling you how I read that, +especially as, rather against the strict rules of your order, you +use an arc-and-compass breastpin." + +"Ah, of course, I forgot that. But the writing?" + +"What else can be indicated by that right cuff so very shiny for +five inches, and the left one with the smooth patch near the +elbow where you rest it upon the desk?" + +"Well, but China?" + +"The fish that you have tattooed immediately above your right +wrist could only have been done in China. I have made a small +study of tattoo marks and have even contributed to the literature +of the subject. That trick of staining the fishes' scales of a +delicate pink is quite peculiar to China. When, in addition, I +see a Chinese coin hanging from your watch-chain, the matter +becomes even more simple." + +Mr. Jabez Wilson laughed heavily. "Well, I never!" said he. "I +thought at first that you had done something clever, but I see +that there was nothing in it, after all." + +"I begin to think, Watson," said Holmes, "that I make a mistake +in explaining. 'Omne ignotum pro magnifico,' you know, and my +poor little reputation, such as it is, will suffer shipwreck if I +am so candid. Can you not find the advertisement, Mr. Wilson?" + +"Yes, I have got it now," he answered with his thick red finger +planted halfway down the column. "Here it is. This is what began +it all. You just read it for yourself, sir." + +I took the paper from him and read as follows: + +"TO THE RED-HEADED LEAGUE: On account of the bequest of the late +Ezekiah Hopkins, of Lebanon, Pennsylvania, U. S. A., there is now +another vacancy open which entitles a member of the League to a +salary of 4 pounds a week for purely nominal services. All +red-headed men who are sound in body and mind and above the age +of twenty-one years, are eligible. Apply in person on Monday, at +eleven o'clock, to Duncan Ross, at the offices of the League, 7 +Pope's Court, Fleet Street." + +"What on earth does this mean?" I ejaculated after I had twice +read over the extraordinary announcement. + +Holmes chuckled and wriggled in his chair, as was his habit when +in high spirits. "It is a little off the beaten track, isn't it?" +said he. "And now, Mr. Wilson, off you go at scratch and tell us +all about yourself, your household, and the effect which this +advertisement had upon your fortunes. You will first make a note, +Doctor, of the paper and the date." + +"It is The Morning Chronicle of April 27, 1890. Just two months +ago." + +"Very good. Now, Mr. Wilson?" + +"Well, it is just as I have been telling you, Mr. Sherlock +Holmes," said Jabez Wilson, mopping his forehead; "I have a small +pawnbroker's business at Coburg Square, near the City. It's not a +very large affair, and of late years it has not done more than +just give me a living. I used to be able to keep two assistants, +but now I only keep one; and I would have a job to pay him but +that he is willing to come for half wages so as to learn the +business." + +"What is the name of this obliging youth?" asked Sherlock Holmes. + +"His name is Vincent Spaulding, and he's not such a youth, +either. It's hard to say his age. I should not wish a smarter +assistant, Mr. Holmes; and I know very well that he could better +himself and earn twice what I am able to give him. But, after +all, if he is satisfied, why should I put ideas in his head?" + +"Why, indeed? You seem most fortunate in having an employ who +comes under the full market price. It is not a common experience +among employers in this age. I don't know that your assistant is +not as remarkable as your advertisement." + +"Oh, he has his faults, too," said Mr. Wilson. "Never was such a +fellow for photography. Snapping away with a camera when he ought +to be improving his mind, and then diving down into the cellar +like a rabbit into its hole to develop his pictures. That is his +main fault, but on the whole he's a good worker. There's no vice +in him." + +"He is still with you, I presume?" + +"Yes, sir. He and a girl of fourteen, who does a bit of simple +cooking and keeps the place clean--that's all I have in the +house, for I am a widower and never had any family. We live very +quietly, sir, the three of us; and we keep a roof over our heads +and pay our debts, if we do nothing more. + +"The first thing that put us out was that advertisement. +Spaulding, he came down into the office just this day eight +weeks, with this very paper in his hand, and he says: + +"'I wish to the Lord, Mr. Wilson, that I was a red-headed man.' + +"'Why that?' I asks. + +"'Why,' says he, 'here's another vacancy on the League of the +Red-headed Men. It's worth quite a little fortune to any man who +gets it, and I understand that there are more vacancies than +there are men, so that the trustees are at their wits' end what +to do with the money. If my hair would only change colour, here's +a nice little crib all ready for me to step into.' + +"'Why, what is it, then?' I asked. You see, Mr. Holmes, I am a +very stay-at-home man, and as my business came to me instead of +my having to go to it, I was often weeks on end without putting +my foot over the door-mat. In that way I didn't know much of what +was going on outside, and I was always glad of a bit of news. + +"'Have you never heard of the League of the Red-headed Men?' he +asked with his eyes open. + +"'Never.' + +"'Why, I wonder at that, for you are eligible yourself for one +of the vacancies.' + +"'And what are they worth?' I asked. + +"'Oh, merely a couple of hundred a year, but the work is slight, +and it need not interfere very much with one's other +occupations.' + +"Well, you can easily think that that made me prick up my ears, +for the business has not been over-good for some years, and an +extra couple of hundred would have been very handy. + +"'Tell me all about it,' said I. + +"'Well,' said he, showing me the advertisement, 'you can see for +yourself that the League has a vacancy, and there is the address +where you should apply for particulars. As far as I can make out, +the League was founded by an American millionaire, Ezekiah +Hopkins, who was very peculiar in his ways. He was himself +red-headed, and he had a great sympathy for all red-headed men; +so when he died it was found that he had left his enormous +fortune in the hands of trustees, with instructions to apply the +interest to the providing of easy berths to men whose hair is of +that colour. From all I hear it is splendid pay and very little to +do.' + +"'But,' said I, 'there would be millions of red-headed men who +would apply.' + +"'Not so many as you might think,' he answered. 'You see it is +really confined to Londoners, and to grown men. This American had +started from London when he was young, and he wanted to do the +old town a good turn. Then, again, I have heard it is no use your +applying if your hair is light red, or dark red, or anything but +real bright, blazing, fiery red. Now, if you cared to apply, Mr. +Wilson, you would just walk in; but perhaps it would hardly be +worth your while to put yourself out of the way for the sake of a +few hundred pounds.' + +"Now, it is a fact, gentlemen, as you may see for yourselves, +that my hair is of a very full and rich tint, so that it seemed +to me that if there was to be any competition in the matter I +stood as good a chance as any man that I had ever met. Vincent +Spaulding seemed to know so much about it that I thought he might +prove useful, so I just ordered him to put up the shutters for +the day and to come right away with me. He was very willing to +have a holiday, so we shut the business up and started off for +the address that was given us in the advertisement. + +"I never hope to see such a sight as that again, Mr. Holmes. From +north, south, east, and west every man who had a shade of red in +his hair had tramped into the city to answer the advertisement. +Fleet Street was choked with red-headed folk, and Pope's Court +looked like a coster's orange barrow. I should not have thought +there were so many in the whole country as were brought together +by that single advertisement. Every shade of colour they +were--straw, lemon, orange, brick, Irish-setter, liver, clay; +but, as Spaulding said, there were not many who had the real +vivid flame-coloured tint. When I saw how many were waiting, I +would have given it up in despair; but Spaulding would not hear +of it. How he did it I could not imagine, but he pushed and +pulled and butted until he got me through the crowd, and right up +to the steps which led to the office. There was a double stream +upon the stair, some going up in hope, and some coming back +dejected; but we wedged in as well as we could and soon found +ourselves in the office." + +"Your experience has been a most entertaining one," remarked +Holmes as his client paused and refreshed his memory with a huge +pinch of snuff. "Pray continue your very interesting statement." + +"There was nothing in the office but a couple of wooden chairs +and a deal table, behind which sat a small man with a head that +was even redder than mine. He said a few words to each candidate +as he came up, and then he always managed to find some fault in +them which would disqualify them. Getting a vacancy did not seem +to be such a very easy matter, after all. However, when our turn +came the little man was much more favourable to me than to any of +the others, and he closed the door as we entered, so that he +might have a private word with us. + +"'This is Mr. Jabez Wilson,' said my assistant, 'and he is +willing to fill a vacancy in the League.' + +"'And he is admirably suited for it,' the other answered. 'He has +every requirement. I cannot recall when I have seen anything so +fine.' He took a step backward, cocked his head on one side, and +gazed at my hair until I felt quite bashful. Then suddenly he +plunged forward, wrung my hand, and congratulated me warmly on my +success. + +"'It would be injustice to hesitate,' said he. 'You will, +however, I am sure, excuse me for taking an obvious precaution.' +With that he seized my hair in both his hands, and tugged until I +yelled with the pain. 'There is water in your eyes,' said he as +he released me. 'I perceive that all is as it should be. But we +have to be careful, for we have twice been deceived by wigs and +once by paint. I could tell you tales of cobbler's wax which +would disgust you with human nature.' He stepped over to the +window and shouted through it at the top of his voice that the +vacancy was filled. A groan of disappointment came up from below, +and the folk all trooped away in different directions until there +was not a red-head to be seen except my own and that of the +manager. + +"'My name,' said he, 'is Mr. Duncan Ross, and I am myself one of +the pensioners upon the fund left by our noble benefactor. Are +you a married man, Mr. Wilson? Have you a family?' + +"I answered that I had not. + +"His face fell immediately. + +"'Dear me!' he said gravely, 'that is very serious indeed! I am +sorry to hear you say that. The fund was, of course, for the +propagation and spread of the red-heads as well as for their +maintenance. It is exceedingly unfortunate that you should be a +bachelor.' + +"My face lengthened at this, Mr. Holmes, for I thought that I was +not to have the vacancy after all; but after thinking it over for +a few minutes he said that it would be all right. + +"'In the case of another,' said he, 'the objection might be +fatal, but we must stretch a point in favour of a man with such a +head of hair as yours. When shall you be able to enter upon your +new duties?' + +"'Well, it is a little awkward, for I have a business already,' +said I. + +"'Oh, never mind about that, Mr. Wilson!' said Vincent Spaulding. +'I should be able to look after that for you.' + +"'What would be the hours?' I asked. + +"'Ten to two.' + +"Now a pawnbroker's business is mostly done of an evening, Mr. +Holmes, especially Thursday and Friday evening, which is just +before pay-day; so it would suit me very well to earn a little in +the mornings. Besides, I knew that my assistant was a good man, +and that he would see to anything that turned up. + +"'That would suit me very well,' said I. 'And the pay?' + +"'Is 4 pounds a week.' + +"'And the work?' + +"'Is purely nominal.' + +"'What do you call purely nominal?' + +"'Well, you have to be in the office, or at least in the +building, the whole time. If you leave, you forfeit your whole +position forever. The will is very clear upon that point. You +don't comply with the conditions if you budge from the office +during that time.' + +"'It's only four hours a day, and I should not think of leaving,' +said I. + +"'No excuse will avail,' said Mr. Duncan Ross; 'neither sickness +nor business nor anything else. There you must stay, or you lose +your billet.' + +"'And the work?' + +"'Is to copy out the "Encyclopaedia Britannica." There is the first +volume of it in that press. You must find your own ink, pens, and +blotting-paper, but we provide this table and chair. Will you be +ready to-morrow?' + +"'Certainly,' I answered. + +"'Then, good-bye, Mr. Jabez Wilson, and let me congratulate you +once more on the important position which you have been fortunate +enough to gain.' He bowed me out of the room and I went home with +my assistant, hardly knowing what to say or do, I was so pleased +at my own good fortune. + +"Well, I thought over the matter all day, and by evening I was in +low spirits again; for I had quite persuaded myself that the +whole affair must be some great hoax or fraud, though what its +object might be I could not imagine. It seemed altogether past +belief that anyone could make such a will, or that they would pay +such a sum for doing anything so simple as copying out the +'Encyclopaedia Britannica.' Vincent Spaulding did what he could to +cheer me up, but by bedtime I had reasoned myself out of the +whole thing. However, in the morning I determined to have a look +at it anyhow, so I bought a penny bottle of ink, and with a +quill-pen, and seven sheets of foolscap paper, I started off for +Pope's Court. + +"Well, to my surprise and delight, everything was as right as +possible. The table was set out ready for me, and Mr. Duncan Ross +was there to see that I got fairly to work. He started me off +upon the letter A, and then he left me; but he would drop in from +time to time to see that all was right with me. At two o'clock he +bade me good-day, complimented me upon the amount that I had +written, and locked the door of the office after me. + +"This went on day after day, Mr. Holmes, and on Saturday the +manager came in and planked down four golden sovereigns for my +week's work. It was the same next week, and the same the week +after. Every morning I was there at ten, and every afternoon I +left at two. By degrees Mr. Duncan Ross took to coming in only +once of a morning, and then, after a time, he did not come in at +all. Still, of course, I never dared to leave the room for an +instant, for I was not sure when he might come, and the billet +was such a good one, and suited me so well, that I would not risk +the loss of it. + +"Eight weeks passed away like this, and I had written about +Abbots and Archery and Armour and Architecture and Attica, and +hoped with diligence that I might get on to the B's before very +long. It cost me something in foolscap, and I had pretty nearly +filled a shelf with my writings. And then suddenly the whole +business came to an end." + +"To an end?" + +"Yes, sir. And no later than this morning. I went to my work as +usual at ten o'clock, but the door was shut and locked, with a +little square of cardboard hammered on to the middle of the +panel with a tack. Here it is, and you can read for yourself." + +He held up a piece of white cardboard about the size of a sheet +of note-paper. It read in this fashion: + + THE RED-HEADED LEAGUE + + IS + + DISSOLVED. + + October 9, 1890. + +Sherlock Holmes and I surveyed this curt announcement and the +rueful face behind it, until the comical side of the affair so +completely overtopped every other consideration that we both +burst out into a roar of laughter. + +"I cannot see that there is anything very funny," cried our +client, flushing up to the roots of his flaming head. "If you can +do nothing better than laugh at me, I can go elsewhere." + +"No, no," cried Holmes, shoving him back into the chair from +which he had half risen. "I really wouldn't miss your case for +the world. It is most refreshingly unusual. But there is, if you +will excuse my saying so, something just a little funny about it. +Pray what steps did you take when you found the card upon the +door?" + +"I was staggered, sir. I did not know what to do. Then I called +at the offices round, but none of them seemed to know anything +about it. Finally, I went to the landlord, who is an accountant +living on the ground-floor, and I asked him if he could tell me +what had become of the Red-headed League. He said that he had +never heard of any such body. Then I asked him who Mr. Duncan +Ross was. He answered that the name was new to him. + +"'Well,' said I, 'the gentleman at No. 4.' + +"'What, the red-headed man?' + +"'Yes.' + +"'Oh,' said he, 'his name was William Morris. He was a solicitor +and was using my room as a temporary convenience until his new +premises were ready. He moved out yesterday.' + +"'Where could I find him?' + +"'Oh, at his new offices. He did tell me the address. Yes, 17 +King Edward Street, near St. Paul's.' + +"I started off, Mr. Holmes, but when I got to that address it was +a manufactory of artificial knee-caps, and no one in it had ever +heard of either Mr. William Morris or Mr. Duncan Ross." + +"And what did you do then?" asked Holmes. + +"I went home to Saxe-Coburg Square, and I took the advice of my +assistant. But he could not help me in any way. He could only say +that if I waited I should hear by post. But that was not quite +good enough, Mr. Holmes. I did not wish to lose such a place +without a struggle, so, as I had heard that you were good enough +to give advice to poor folk who were in need of it, I came right +away to you." + +"And you did very wisely," said Holmes. "Your case is an +exceedingly remarkable one, and I shall be happy to look into it. +From what you have told me I think that it is possible that +graver issues hang from it than might at first sight appear." + +"Grave enough!" said Mr. Jabez Wilson. "Why, I have lost four +pound a week." + +"As far as you are personally concerned," remarked Holmes, "I do +not see that you have any grievance against this extraordinary +league. On the contrary, you are, as I understand, richer by some +30 pounds, to say nothing of the minute knowledge which you have +gained on every subject which comes under the letter A. You have +lost nothing by them." + +"No, sir. But I want to find out about them, and who they are, +and what their object was in playing this prank--if it was a +prank--upon me. It was a pretty expensive joke for them, for it +cost them two and thirty pounds." + +"We shall endeavour to clear up these points for you. And, first, +one or two questions, Mr. Wilson. This assistant of yours who +first called your attention to the advertisement--how long had he +been with you?" + +"About a month then." + +"How did he come?" + +"In answer to an advertisement." + +"Was he the only applicant?" + +"No, I had a dozen." + +"Why did you pick him?" + +"Because he was handy and would come cheap." + +"At half-wages, in fact." + +"Yes." + +"What is he like, this Vincent Spaulding?" + +"Small, stout-built, very quick in his ways, no hair on his face, +though he's not short of thirty. Has a white splash of acid upon +his forehead." + +Holmes sat up in his chair in considerable excitement. "I thought +as much," said he. "Have you ever observed that his ears are +pierced for earrings?" + +"Yes, sir. He told me that a gipsy had done it for him when he +was a lad." + +"Hum!" said Holmes, sinking back in deep thought. "He is still +with you?" + +"Oh, yes, sir; I have only just left him." + +"And has your business been attended to in your absence?" + +"Nothing to complain of, sir. There's never very much to do of a +morning." + +"That will do, Mr. Wilson. I shall be happy to give you an +opinion upon the subject in the course of a day or two. To-day is +Saturday, and I hope that by Monday we may come to a conclusion." + +"Well, Watson," said Holmes when our visitor had left us, "what +do you make of it all?" + +"I make nothing of it," I answered frankly. "It is a most +mysterious business." + +"As a rule," said Holmes, "the more bizarre a thing is the less +mysterious it proves to be. It is your commonplace, featureless +crimes which are really puzzling, just as a commonplace face is +the most difficult to identify. But I must be prompt over this +matter." + +"What are you going to do, then?" I asked. + +"To smoke," he answered. "It is quite a three pipe problem, and I +beg that you won't speak to me for fifty minutes." He curled +himself up in his chair, with his thin knees drawn up to his +hawk-like nose, and there he sat with his eyes closed and his +black clay pipe thrusting out like the bill of some strange bird. +I had come to the conclusion that he had dropped asleep, and +indeed was nodding myself, when he suddenly sprang out of his +chair with the gesture of a man who has made up his mind and put +his pipe down upon the mantelpiece. + +"Sarasate plays at the St. James's Hall this afternoon," he +remarked. "What do you think, Watson? Could your patients spare +you for a few hours?" + +"I have nothing to do to-day. My practice is never very +absorbing." + +"Then put on your hat and come. I am going through the City +first, and we can have some lunch on the way. I observe that +there is a good deal of German music on the programme, which is +rather more to my taste than Italian or French. It is +introspective, and I want to introspect. Come along!" + +We travelled by the Underground as far as Aldersgate; and a short +walk took us to Saxe-Coburg Square, the scene of the singular +story which we had listened to in the morning. It was a poky, +little, shabby-genteel place, where four lines of dingy +two-storied brick houses looked out into a small railed-in +enclosure, where a lawn of weedy grass and a few clumps of faded +laurel-bushes made a hard fight against a smoke-laden and +uncongenial atmosphere. Three gilt balls and a brown board with +"JABEZ WILSON" in white letters, upon a corner house, announced +the place where our red-headed client carried on his business. +Sherlock Holmes stopped in front of it with his head on one side +and looked it all over, with his eyes shining brightly between +puckered lids. Then he walked slowly up the street, and then down +again to the corner, still looking keenly at the houses. Finally +he returned to the pawnbroker's, and, having thumped vigorously +upon the pavement with his stick two or three times, he went up +to the door and knocked. It was instantly opened by a +bright-looking, clean-shaven young fellow, who asked him to step +in. + +"Thank you," said Holmes, "I only wished to ask you how you would +go from here to the Strand." + +"Third right, fourth left," answered the assistant promptly, +closing the door. + +"Smart fellow, that," observed Holmes as we walked away. "He is, +in my judgment, the fourth smartest man in London, and for daring +I am not sure that he has not a claim to be third. I have known +something of him before." + +"Evidently," said I, "Mr. Wilson's assistant counts for a good +deal in this mystery of the Red-headed League. I am sure that you +inquired your way merely in order that you might see him." + +"Not him." + +"What then?" + +"The knees of his trousers." + +"And what did you see?" + +"What I expected to see." + +"Why did you beat the pavement?" + +"My dear doctor, this is a time for observation, not for talk. We +are spies in an enemy's country. We know something of Saxe-Coburg +Square. Let us now explore the parts which lie behind it." + +The road in which we found ourselves as we turned round the +corner from the retired Saxe-Coburg Square presented as great a +contrast to it as the front of a picture does to the back. It was +one of the main arteries which conveyed the traffic of the City +to the north and west. The roadway was blocked with the immense +stream of commerce flowing in a double tide inward and outward, +while the footpaths were black with the hurrying swarm of +pedestrians. It was difficult to realise as we looked at the line +of fine shops and stately business premises that they really +abutted on the other side upon the faded and stagnant square +which we had just quitted. + +"Let me see," said Holmes, standing at the corner and glancing +along the line, "I should like just to remember the order of the +houses here. It is a hobby of mine to have an exact knowledge of +London. There is Mortimer's, the tobacconist, the little +newspaper shop, the Coburg branch of the City and Suburban Bank, +the Vegetarian Restaurant, and McFarlane's carriage-building +depot. That carries us right on to the other block. And now, +Doctor, we've done our work, so it's time we had some play. A +sandwich and a cup of coffee, and then off to violin-land, where +all is sweetness and delicacy and harmony, and there are no +red-headed clients to vex us with their conundrums." + +My friend was an enthusiastic musician, being himself not only a +very capable performer but a composer of no ordinary merit. All +the afternoon he sat in the stalls wrapped in the most perfect +happiness, gently waving his long, thin fingers in time to the +music, while his gently smiling face and his languid, dreamy eyes +were as unlike those of Holmes the sleuth-hound, Holmes the +relentless, keen-witted, ready-handed criminal agent, as it was +possible to conceive. In his singular character the dual nature +alternately asserted itself, and his extreme exactness and +astuteness represented, as I have often thought, the reaction +against the poetic and contemplative mood which occasionally +predominated in him. The swing of his nature took him from +extreme languor to devouring energy; and, as I knew well, he was +never so truly formidable as when, for days on end, he had been +lounging in his armchair amid his improvisations and his +black-letter editions. Then it was that the lust of the chase +would suddenly come upon him, and that his brilliant reasoning +power would rise to the level of intuition, until those who were +unacquainted with his methods would look askance at him as on a +man whose knowledge was not that of other mortals. When I saw him +that afternoon so enwrapped in the music at St. James's Hall I +felt that an evil time might be coming upon those whom he had set +himself to hunt down. + +"You want to go home, no doubt, Doctor," he remarked as we +emerged. + +"Yes, it would be as well." + +"And I have some business to do which will take some hours. This +business at Coburg Square is serious." + +"Why serious?" + +"A considerable crime is in contemplation. I have every reason to +believe that we shall be in time to stop it. But to-day being +Saturday rather complicates matters. I shall want your help +to-night." + +"At what time?" + +"Ten will be early enough." + +"I shall be at Baker Street at ten." + +"Very well. And, I say, Doctor, there may be some little danger, +so kindly put your army revolver in your pocket." He waved his +hand, turned on his heel, and disappeared in an instant among the +crowd. + +I trust that I am not more dense than my neighbours, but I was +always oppressed with a sense of my own stupidity in my dealings +with Sherlock Holmes. Here I had heard what he had heard, I had +seen what he had seen, and yet from his words it was evident that +he saw clearly not only what had happened but what was about to +happen, while to me the whole business was still confused and +grotesque. As I drove home to my house in Kensington I thought +over it all, from the extraordinary story of the red-headed +copier of the "Encyclopaedia" down to the visit to Saxe-Coburg +Square, and the ominous words with which he had parted from me. +What was this nocturnal expedition, and why should I go armed? +Where were we going, and what were we to do? I had the hint from +Holmes that this smooth-faced pawnbroker's assistant was a +formidable man--a man who might play a deep game. I tried to +puzzle it out, but gave it up in despair and set the matter aside +until night should bring an explanation. + +It was a quarter-past nine when I started from home and made my +way across the Park, and so through Oxford Street to Baker +Street. Two hansoms were standing at the door, and as I entered +the passage I heard the sound of voices from above. On entering +his room I found Holmes in animated conversation with two men, +one of whom I recognised as Peter Jones, the official police +agent, while the other was a long, thin, sad-faced man, with a +very shiny hat and oppressively respectable frock-coat. + +"Ha! Our party is complete," said Holmes, buttoning up his +pea-jacket and taking his heavy hunting crop from the rack. +"Watson, I think you know Mr. Jones, of Scotland Yard? Let me +introduce you to Mr. Merryweather, who is to be our companion in +to-night's adventure." + +"We're hunting in couples again, Doctor, you see," said Jones in +his consequential way. "Our friend here is a wonderful man for +starting a chase. All he wants is an old dog to help him to do +the running down." + +"I hope a wild goose may not prove to be the end of our chase," +observed Mr. Merryweather gloomily. + +"You may place considerable confidence in Mr. Holmes, sir," said +the police agent loftily. "He has his own little methods, which +are, if he won't mind my saying so, just a little too theoretical +and fantastic, but he has the makings of a detective in him. It +is not too much to say that once or twice, as in that business of +the Sholto murder and the Agra treasure, he has been more nearly +correct than the official force." + +"Oh, if you say so, Mr. Jones, it is all right," said the +stranger with deference. "Still, I confess that I miss my rubber. +It is the first Saturday night for seven-and-twenty years that I +have not had my rubber." + +"I think you will find," said Sherlock Holmes, "that you will +play for a higher stake to-night than you have ever done yet, and +that the play will be more exciting. For you, Mr. Merryweather, +the stake will be some 30,000 pounds; and for you, Jones, it will +be the man upon whom you wish to lay your hands." + +"John Clay, the murderer, thief, smasher, and forger. He's a +young man, Mr. Merryweather, but he is at the head of his +profession, and I would rather have my bracelets on him than on +any criminal in London. He's a remarkable man, is young John +Clay. His grandfather was a royal duke, and he himself has been +to Eton and Oxford. His brain is as cunning as his fingers, and +though we meet signs of him at every turn, we never know where to +find the man himself. He'll crack a crib in Scotland one week, +and be raising money to build an orphanage in Cornwall the next. +I've been on his track for years and have never set eyes on him +yet." + +"I hope that I may have the pleasure of introducing you to-night. +I've had one or two little turns also with Mr. John Clay, and I +agree with you that he is at the head of his profession. It is +past ten, however, and quite time that we started. If you two +will take the first hansom, Watson and I will follow in the +second." + +Sherlock Holmes was not very communicative during the long drive +and lay back in the cab humming the tunes which he had heard in +the afternoon. We rattled through an endless labyrinth of gas-lit +streets until we emerged into Farrington Street. + +"We are close there now," my friend remarked. "This fellow +Merryweather is a bank director, and personally interested in the +matter. I thought it as well to have Jones with us also. He is +not a bad fellow, though an absolute imbecile in his profession. +He has one positive virtue. He is as brave as a bulldog and as +tenacious as a lobster if he gets his claws upon anyone. Here we +are, and they are waiting for us." + +We had reached the same crowded thoroughfare in which we had +found ourselves in the morning. Our cabs were dismissed, and, +following the guidance of Mr. Merryweather, we passed down a +narrow passage and through a side door, which he opened for us. +Within there was a small corridor, which ended in a very massive +iron gate. This also was opened, and led down a flight of winding +stone steps, which terminated at another formidable gate. Mr. +Merryweather stopped to light a lantern, and then conducted us +down a dark, earth-smelling passage, and so, after opening a +third door, into a huge vault or cellar, which was piled all +round with crates and massive boxes. + +"You are not very vulnerable from above," Holmes remarked as he +held up the lantern and gazed about him. + +"Nor from below," said Mr. Merryweather, striking his stick upon +the flags which lined the floor. "Why, dear me, it sounds quite +hollow!" he remarked, looking up in surprise. + +"I must really ask you to be a little more quiet!" said Holmes +severely. "You have already imperilled the whole success of our +expedition. Might I beg that you would have the goodness to sit +down upon one of those boxes, and not to interfere?" + +The solemn Mr. Merryweather perched himself upon a crate, with a +very injured expression upon his face, while Holmes fell upon his +knees upon the floor and, with the lantern and a magnifying lens, +began to examine minutely the cracks between the stones. A few +seconds sufficed to satisfy him, for he sprang to his feet again +and put his glass in his pocket. + +"We have at least an hour before us," he remarked, "for they can +hardly take any steps until the good pawnbroker is safely in bed. +Then they will not lose a minute, for the sooner they do their +work the longer time they will have for their escape. We are at +present, Doctor--as no doubt you have divined--in the cellar of +the City branch of one of the principal London banks. Mr. +Merryweather is the chairman of directors, and he will explain to +you that there are reasons why the more daring criminals of +London should take a considerable interest in this cellar at +present." + +"It is our French gold," whispered the director. "We have had +several warnings that an attempt might be made upon it." + +"Your French gold?" + +"Yes. We had occasion some months ago to strengthen our resources +and borrowed for that purpose 30,000 napoleons from the Bank of +France. It has become known that we have never had occasion to +unpack the money, and that it is still lying in our cellar. The +crate upon which I sit contains 2,000 napoleons packed between +layers of lead foil. Our reserve of bullion is much larger at +present than is usually kept in a single branch office, and the +directors have had misgivings upon the subject." + +"Which were very well justified," observed Holmes. "And now it is +time that we arranged our little plans. I expect that within an +hour matters will come to a head. In the meantime Mr. +Merryweather, we must put the screen over that dark lantern." + +"And sit in the dark?" + +"I am afraid so. I had brought a pack of cards in my pocket, and +I thought that, as we were a partie carre, you might have your +rubber after all. But I see that the enemy's preparations have +gone so far that we cannot risk the presence of a light. And, +first of all, we must choose our positions. These are daring men, +and though we shall take them at a disadvantage, they may do us +some harm unless we are careful. I shall stand behind this crate, +and do you conceal yourselves behind those. Then, when I flash a +light upon them, close in swiftly. If they fire, Watson, have no +compunction about shooting them down." + +I placed my revolver, cocked, upon the top of the wooden case +behind which I crouched. Holmes shot the slide across the front +of his lantern and left us in pitch darkness--such an absolute +darkness as I have never before experienced. The smell of hot +metal remained to assure us that the light was still there, ready +to flash out at a moment's notice. To me, with my nerves worked +up to a pitch of expectancy, there was something depressing and +subduing in the sudden gloom, and in the cold dank air of the +vault. + +"They have but one retreat," whispered Holmes. "That is back +through the house into Saxe-Coburg Square. I hope that you have +done what I asked you, Jones?" + +"I have an inspector and two officers waiting at the front door." + +"Then we have stopped all the holes. And now we must be silent +and wait." + +What a time it seemed! From comparing notes afterwards it was but +an hour and a quarter, yet it appeared to me that the night must +have almost gone and the dawn be breaking above us. My limbs +were weary and stiff, for I feared to change my position; yet my +nerves were worked up to the highest pitch of tension, and my +hearing was so acute that I could not only hear the gentle +breathing of my companions, but I could distinguish the deeper, +heavier in-breath of the bulky Jones from the thin, sighing note +of the bank director. From my position I could look over the case +in the direction of the floor. Suddenly my eyes caught the glint +of a light. + +At first it was but a lurid spark upon the stone pavement. Then +it lengthened out until it became a yellow line, and then, +without any warning or sound, a gash seemed to open and a hand +appeared, a white, almost womanly hand, which felt about in the +centre of the little area of light. For a minute or more the +hand, with its writhing fingers, protruded out of the floor. Then +it was withdrawn as suddenly as it appeared, and all was dark +again save the single lurid spark which marked a chink between +the stones. + +Its disappearance, however, was but momentary. With a rending, +tearing sound, one of the broad, white stones turned over upon +its side and left a square, gaping hole, through which streamed +the light of a lantern. Over the edge there peeped a clean-cut, +boyish face, which looked keenly about it, and then, with a hand +on either side of the aperture, drew itself shoulder-high and +waist-high, until one knee rested upon the edge. In another +instant he stood at the side of the hole and was hauling after +him a companion, lithe and small like himself, with a pale face +and a shock of very red hair. + +"It's all clear," he whispered. "Have you the chisel and the +bags? Great Scott! Jump, Archie, jump, and I'll swing for it!" + +Sherlock Holmes had sprung out and seized the intruder by the +collar. The other dived down the hole, and I heard the sound of +rending cloth as Jones clutched at his skirts. The light flashed +upon the barrel of a revolver, but Holmes' hunting crop came +down on the man's wrist, and the pistol clinked upon the stone +floor. + +"It's no use, John Clay," said Holmes blandly. "You have no +chance at all." + +"So I see," the other answered with the utmost coolness. "I fancy +that my pal is all right, though I see you have got his +coat-tails." + +"There are three men waiting for him at the door," said Holmes. + +"Oh, indeed! You seem to have done the thing very completely. I +must compliment you." + +"And I you," Holmes answered. "Your red-headed idea was very new +and effective." + +"You'll see your pal again presently," said Jones. "He's quicker +at climbing down holes than I am. Just hold out while I fix the +derbies." + +"I beg that you will not touch me with your filthy hands," +remarked our prisoner as the handcuffs clattered upon his wrists. +"You may not be aware that I have royal blood in my veins. Have +the goodness, also, when you address me always to say 'sir' and +'please.'" + +"All right," said Jones with a stare and a snigger. "Well, would +you please, sir, march upstairs, where we can get a cab to carry +your Highness to the police-station?" + +"That is better," said John Clay serenely. He made a sweeping bow +to the three of us and walked quietly off in the custody of the +detective. + +"Really, Mr. Holmes," said Mr. Merryweather as we followed them +from the cellar, "I do not know how the bank can thank you or +repay you. There is no doubt that you have detected and defeated +in the most complete manner one of the most determined attempts +at bank robbery that have ever come within my experience." + +"I have had one or two little scores of my own to settle with Mr. +John Clay," said Holmes. "I have been at some small expense over +this matter, which I shall expect the bank to refund, but beyond +that I am amply repaid by having had an experience which is in +many ways unique, and by hearing the very remarkable narrative of +the Red-headed League." + + +"You see, Watson," he explained in the early hours of the morning +as we sat over a glass of whisky and soda in Baker Street, "it +was perfectly obvious from the first that the only possible +object of this rather fantastic business of the advertisement of +the League, and the copying of the 'Encyclopaedia,' must be to get +this not over-bright pawnbroker out of the way for a number of +hours every day. It was a curious way of managing it, but, +really, it would be difficult to suggest a better. The method was +no doubt suggested to Clay's ingenious mind by the colour of his +accomplice's hair. The 4 pounds a week was a lure which must draw +him, and what was it to them, who were playing for thousands? +They put in the advertisement, one rogue has the temporary +office, the other rogue incites the man to apply for it, and +together they manage to secure his absence every morning in the +week. From the time that I heard of the assistant having come for +half wages, it was obvious to me that he had some strong motive +for securing the situation." + +"But how could you guess what the motive was?" + +"Had there been women in the house, I should have suspected a +mere vulgar intrigue. That, however, was out of the question. The +man's business was a small one, and there was nothing in his +house which could account for such elaborate preparations, and +such an expenditure as they were at. It must, then, be something +out of the house. What could it be? I thought of the assistant's +fondness for photography, and his trick of vanishing into the +cellar. The cellar! There was the end of this tangled clue. Then +I made inquiries as to this mysterious assistant and found that I +had to deal with one of the coolest and most daring criminals in +London. He was doing something in the cellar--something which +took many hours a day for months on end. What could it be, once +more? I could think of nothing save that he was running a tunnel +to some other building. + +"So far I had got when we went to visit the scene of action. I +surprised you by beating upon the pavement with my stick. I was +ascertaining whether the cellar stretched out in front or behind. +It was not in front. Then I rang the bell, and, as I hoped, the +assistant answered it. We have had some skirmishes, but we had +never set eyes upon each other before. I hardly looked at his +face. His knees were what I wished to see. You must yourself have +remarked how worn, wrinkled, and stained they were. They spoke of +those hours of burrowing. The only remaining point was what they +were burrowing for. I walked round the corner, saw the City and +Suburban Bank abutted on our friend's premises, and felt that I +had solved my problem. When you drove home after the concert I +called upon Scotland Yard and upon the chairman of the bank +directors, with the result that you have seen." + +"And how could you tell that they would make their attempt +to-night?" I asked. + +"Well, when they closed their League offices that was a sign that +they cared no longer about Mr. Jabez Wilson's presence--in other +words, that they had completed their tunnel. But it was essential +that they should use it soon, as it might be discovered, or the +bullion might be removed. Saturday would suit them better than +any other day, as it would give them two days for their escape. +For all these reasons I expected them to come to-night." + +"You reasoned it out beautifully," I exclaimed in unfeigned +admiration. "It is so long a chain, and yet every link rings +true." + +"It saved me from ennui," he answered, yawning. "Alas! I already +feel it closing in upon me. My life is spent in one long effort +to escape from the commonplaces of existence. These little +problems help me to do so." + +"And you are a benefactor of the race," said I. + +He shrugged his shoulders. "Well, perhaps, after all, it is of +some little use," he remarked. "'L'homme c'est rien--l'oeuvre +c'est tout,' as Gustave Flaubert wrote to George Sand." + + + +ADVENTURE III. A CASE OF IDENTITY + +"My dear fellow," said Sherlock Holmes as we sat on either side +of the fire in his lodgings at Baker Street, "life is infinitely +stranger than anything which the mind of man could invent. We +would not dare to conceive the things which are really mere +commonplaces of existence. If we could fly out of that window +hand in hand, hover over this great city, gently remove the +roofs, and peep in at the queer things which are going on, the +strange coincidences, the plannings, the cross-purposes, the +wonderful chains of events, working through generations, and +leading to the most outr results, it would make all fiction with +its conventionalities and foreseen conclusions most stale and +unprofitable." + +"And yet I am not convinced of it," I answered. "The cases which +come to light in the papers are, as a rule, bald enough, and +vulgar enough. We have in our police reports realism pushed to +its extreme limits, and yet the result is, it must be confessed, +neither fascinating nor artistic." + +"A certain selection and discretion must be used in producing a +realistic effect," remarked Holmes. "This is wanting in the +police report, where more stress is laid, perhaps, upon the +platitudes of the magistrate than upon the details, which to an +observer contain the vital essence of the whole matter. Depend +upon it, there is nothing so unnatural as the commonplace." + +I smiled and shook my head. "I can quite understand your thinking +so," I said. "Of course, in your position of unofficial adviser +and helper to everybody who is absolutely puzzled, throughout +three continents, you are brought in contact with all that is +strange and bizarre. But here"--I picked up the morning paper +from the ground--"let us put it to a practical test. Here is the +first heading upon which I come. 'A husband's cruelty to his +wife.' There is half a column of print, but I know without +reading it that it is all perfectly familiar to me. There is, of +course, the other woman, the drink, the push, the blow, the +bruise, the sympathetic sister or landlady. The crudest of +writers could invent nothing more crude." + +"Indeed, your example is an unfortunate one for your argument," +said Holmes, taking the paper and glancing his eye down it. "This +is the Dundas separation case, and, as it happens, I was engaged +in clearing up some small points in connection with it. The +husband was a teetotaler, there was no other woman, and the +conduct complained of was that he had drifted into the habit of +winding up every meal by taking out his false teeth and hurling +them at his wife, which, you will allow, is not an action likely +to occur to the imagination of the average story-teller. Take a +pinch of snuff, Doctor, and acknowledge that I have scored over +you in your example." + +He held out his snuffbox of old gold, with a great amethyst in +the centre of the lid. Its splendour was in such contrast to his +homely ways and simple life that I could not help commenting upon +it. + +"Ah," said he, "I forgot that I had not seen you for some weeks. +It is a little souvenir from the King of Bohemia in return for my +assistance in the case of the Irene Adler papers." + +"And the ring?" I asked, glancing at a remarkable brilliant which +sparkled upon his finger. + +"It was from the reigning family of Holland, though the matter in +which I served them was of such delicacy that I cannot confide it +even to you, who have been good enough to chronicle one or two of +my little problems." + +"And have you any on hand just now?" I asked with interest. + +"Some ten or twelve, but none which present any feature of +interest. They are important, you understand, without being +interesting. Indeed, I have found that it is usually in +unimportant matters that there is a field for the observation, +and for the quick analysis of cause and effect which gives the +charm to an investigation. The larger crimes are apt to be the +simpler, for the bigger the crime the more obvious, as a rule, is +the motive. In these cases, save for one rather intricate matter +which has been referred to me from Marseilles, there is nothing +which presents any features of interest. It is possible, however, +that I may have something better before very many minutes are +over, for this is one of my clients, or I am much mistaken." + +He had risen from his chair and was standing between the parted +blinds gazing down into the dull neutral-tinted London street. +Looking over his shoulder, I saw that on the pavement opposite +there stood a large woman with a heavy fur boa round her neck, +and a large curling red feather in a broad-brimmed hat which was +tilted in a coquettish Duchess of Devonshire fashion over her +ear. From under this great panoply she peeped up in a nervous, +hesitating fashion at our windows, while her body oscillated +backward and forward, and her fingers fidgeted with her glove +buttons. Suddenly, with a plunge, as of the swimmer who leaves +the bank, she hurried across the road, and we heard the sharp +clang of the bell. + +"I have seen those symptoms before," said Holmes, throwing his +cigarette into the fire. "Oscillation upon the pavement always +means an affaire de coeur. She would like advice, but is not sure +that the matter is not too delicate for communication. And yet +even here we may discriminate. When a woman has been seriously +wronged by a man she no longer oscillates, and the usual symptom +is a broken bell wire. Here we may take it that there is a love +matter, but that the maiden is not so much angry as perplexed, or +grieved. But here she comes in person to resolve our doubts." + +As he spoke there was a tap at the door, and the boy in buttons +entered to announce Miss Mary Sutherland, while the lady herself +loomed behind his small black figure like a full-sailed +merchant-man behind a tiny pilot boat. Sherlock Holmes welcomed +her with the easy courtesy for which he was remarkable, and, +having closed the door and bowed her into an armchair, he looked +her over in the minute and yet abstracted fashion which was +peculiar to him. + +"Do you not find," he said, "that with your short sight it is a +little trying to do so much typewriting?" + +"I did at first," she answered, "but now I know where the letters +are without looking." Then, suddenly realising the full purport +of his words, she gave a violent start and looked up, with fear +and astonishment upon her broad, good-humoured face. "You've +heard about me, Mr. Holmes," she cried, "else how could you know +all that?" + +"Never mind," said Holmes, laughing; "it is my business to know +things. Perhaps I have trained myself to see what others +overlook. If not, why should you come to consult me?" + +"I came to you, sir, because I heard of you from Mrs. Etherege, +whose husband you found so easy when the police and everyone had +given him up for dead. Oh, Mr. Holmes, I wish you would do as +much for me. I'm not rich, but still I have a hundred a year in +my own right, besides the little that I make by the machine, and +I would give it all to know what has become of Mr. Hosmer Angel." + +"Why did you come away to consult me in such a hurry?" asked +Sherlock Holmes, with his finger-tips together and his eyes to +the ceiling. + +Again a startled look came over the somewhat vacuous face of Miss +Mary Sutherland. "Yes, I did bang out of the house," she said, +"for it made me angry to see the easy way in which Mr. +Windibank--that is, my father--took it all. He would not go to +the police, and he would not go to you, and so at last, as he +would do nothing and kept on saying that there was no harm done, +it made me mad, and I just on with my things and came right away +to you." + +"Your father," said Holmes, "your stepfather, surely, since the +name is different." + +"Yes, my stepfather. I call him father, though it sounds funny, +too, for he is only five years and two months older than myself." + +"And your mother is alive?" + +"Oh, yes, mother is alive and well. I wasn't best pleased, Mr. +Holmes, when she married again so soon after father's death, and +a man who was nearly fifteen years younger than herself. Father +was a plumber in the Tottenham Court Road, and he left a tidy +business behind him, which mother carried on with Mr. Hardy, the +foreman; but when Mr. Windibank came he made her sell the +business, for he was very superior, being a traveller in wines. +They got 4700 pounds for the goodwill and interest, which wasn't +near as much as father could have got if he had been alive." + +I had expected to see Sherlock Holmes impatient under this +rambling and inconsequential narrative, but, on the contrary, he +had listened with the greatest concentration of attention. + +"Your own little income," he asked, "does it come out of the +business?" + +"Oh, no, sir. It is quite separate and was left me by my uncle +Ned in Auckland. It is in New Zealand stock, paying 4 1/2 per +cent. Two thousand five hundred pounds was the amount, but I can +only touch the interest." + +"You interest me extremely," said Holmes. "And since you draw so +large a sum as a hundred a year, with what you earn into the +bargain, you no doubt travel a little and indulge yourself in +every way. I believe that a single lady can get on very nicely +upon an income of about 60 pounds." + +"I could do with much less than that, Mr. Holmes, but you +understand that as long as I live at home I don't wish to be a +burden to them, and so they have the use of the money just while +I am staying with them. Of course, that is only just for the +time. Mr. Windibank draws my interest every quarter and pays it +over to mother, and I find that I can do pretty well with what I +earn at typewriting. It brings me twopence a sheet, and I can +often do from fifteen to twenty sheets in a day." + +"You have made your position very clear to me," said Holmes. +"This is my friend, Dr. Watson, before whom you can speak as +freely as before myself. Kindly tell us now all about your +connection with Mr. Hosmer Angel." + +A flush stole over Miss Sutherland's face, and she picked +nervously at the fringe of her jacket. "I met him first at the +gasfitters' ball," she said. "They used to send father tickets +when he was alive, and then afterwards they remembered us, and +sent them to mother. Mr. Windibank did not wish us to go. He +never did wish us to go anywhere. He would get quite mad if I +wanted so much as to join a Sunday-school treat. But this time I +was set on going, and I would go; for what right had he to +prevent? He said the folk were not fit for us to know, when all +father's friends were to be there. And he said that I had nothing +fit to wear, when I had my purple plush that I had never so much +as taken out of the drawer. At last, when nothing else would do, +he went off to France upon the business of the firm, but we went, +mother and I, with Mr. Hardy, who used to be our foreman, and it +was there I met Mr. Hosmer Angel." + +"I suppose," said Holmes, "that when Mr. Windibank came back from +France he was very annoyed at your having gone to the ball." + +"Oh, well, he was very good about it. He laughed, I remember, and +shrugged his shoulders, and said there was no use denying +anything to a woman, for she would have her way." + +"I see. Then at the gasfitters' ball you met, as I understand, a +gentleman called Mr. Hosmer Angel." + +"Yes, sir. I met him that night, and he called next day to ask if +we had got home all safe, and after that we met him--that is to +say, Mr. Holmes, I met him twice for walks, but after that father +came back again, and Mr. Hosmer Angel could not come to the house +any more." + +"No?" + +"Well, you know father didn't like anything of the sort. He +wouldn't have any visitors if he could help it, and he used to +say that a woman should be happy in her own family circle. But +then, as I used to say to mother, a woman wants her own circle to +begin with, and I had not got mine yet." + +"But how about Mr. Hosmer Angel? Did he make no attempt to see +you?" + +"Well, father was going off to France again in a week, and Hosmer +wrote and said that it would be safer and better not to see each +other until he had gone. We could write in the meantime, and he +used to write every day. I took the letters in in the morning, so +there was no need for father to know." + +"Were you engaged to the gentleman at this time?" + +"Oh, yes, Mr. Holmes. We were engaged after the first walk that +we took. Hosmer--Mr. Angel--was a cashier in an office in +Leadenhall Street--and--" + +"What office?" + +"That's the worst of it, Mr. Holmes, I don't know." + +"Where did he live, then?" + +"He slept on the premises." + +"And you don't know his address?" + +"No--except that it was Leadenhall Street." + +"Where did you address your letters, then?" + +"To the Leadenhall Street Post Office, to be left till called +for. He said that if they were sent to the office he would be +chaffed by all the other clerks about having letters from a lady, +so I offered to typewrite them, like he did his, but he wouldn't +have that, for he said that when I wrote them they seemed to come +from me, but when they were typewritten he always felt that the +machine had come between us. That will just show you how fond he +was of me, Mr. Holmes, and the little things that he would think +of." + +"It was most suggestive," said Holmes. "It has long been an axiom +of mine that the little things are infinitely the most important. +Can you remember any other little things about Mr. Hosmer Angel?" + +"He was a very shy man, Mr. Holmes. He would rather walk with me +in the evening than in the daylight, for he said that he hated to +be conspicuous. Very retiring and gentlemanly he was. Even his +voice was gentle. He'd had the quinsy and swollen glands when he +was young, he told me, and it had left him with a weak throat, +and a hesitating, whispering fashion of speech. He was always +well dressed, very neat and plain, but his eyes were weak, just +as mine are, and he wore tinted glasses against the glare." + +"Well, and what happened when Mr. Windibank, your stepfather, +returned to France?" + +"Mr. Hosmer Angel came to the house again and proposed that we +should marry before father came back. He was in dreadful earnest +and made me swear, with my hands on the Testament, that whatever +happened I would always be true to him. Mother said he was quite +right to make me swear, and that it was a sign of his passion. +Mother was all in his favour from the first and was even fonder +of him than I was. Then, when they talked of marrying within the +week, I began to ask about father; but they both said never to +mind about father, but just to tell him afterwards, and mother +said she would make it all right with him. I didn't quite like +that, Mr. Holmes. It seemed funny that I should ask his leave, as +he was only a few years older than me; but I didn't want to do +anything on the sly, so I wrote to father at Bordeaux, where the +company has its French offices, but the letter came back to me on +the very morning of the wedding." + +"It missed him, then?" + +"Yes, sir; for he had started to England just before it arrived." + +"Ha! that was unfortunate. Your wedding was arranged, then, for +the Friday. Was it to be in church?" + +"Yes, sir, but very quietly. It was to be at St. Saviour's, near +King's Cross, and we were to have breakfast afterwards at the St. +Pancras Hotel. Hosmer came for us in a hansom, but as there were +two of us he put us both into it and stepped himself into a +four-wheeler, which happened to be the only other cab in the +street. We got to the church first, and when the four-wheeler +drove up we waited for him to step out, but he never did, and +when the cabman got down from the box and looked there was no one +there! The cabman said that he could not imagine what had become +of him, for he had seen him get in with his own eyes. That was +last Friday, Mr. Holmes, and I have never seen or heard anything +since then to throw any light upon what became of him." + +"It seems to me that you have been very shamefully treated," said +Holmes. + +"Oh, no, sir! He was too good and kind to leave me so. Why, all +the morning he was saying to me that, whatever happened, I was to +be true; and that even if something quite unforeseen occurred to +separate us, I was always to remember that I was pledged to him, +and that he would claim his pledge sooner or later. It seemed +strange talk for a wedding-morning, but what has happened since +gives a meaning to it." + +"Most certainly it does. Your own opinion is, then, that some +unforeseen catastrophe has occurred to him?" + +"Yes, sir. I believe that he foresaw some danger, or else he +would not have talked so. And then I think that what he foresaw +happened." + +"But you have no notion as to what it could have been?" + +"None." + +"One more question. How did your mother take the matter?" + +"She was angry, and said that I was never to speak of the matter +again." + +"And your father? Did you tell him?" + +"Yes; and he seemed to think, with me, that something had +happened, and that I should hear of Hosmer again. As he said, +what interest could anyone have in bringing me to the doors of +the church, and then leaving me? Now, if he had borrowed my +money, or if he had married me and got my money settled on him, +there might be some reason, but Hosmer was very independent about +money and never would look at a shilling of mine. And yet, what +could have happened? And why could he not write? Oh, it drives me +half-mad to think of it, and I can't sleep a wink at night." She +pulled a little handkerchief out of her muff and began to sob +heavily into it. + +"I shall glance into the case for you," said Holmes, rising, "and +I have no doubt that we shall reach some definite result. Let the +weight of the matter rest upon me now, and do not let your mind +dwell upon it further. Above all, try to let Mr. Hosmer Angel +vanish from your memory, as he has done from your life." + +"Then you don't think I'll see him again?" + +"I fear not." + +"Then what has happened to him?" + +"You will leave that question in my hands. I should like an +accurate description of him and any letters of his which you can +spare." + +"I advertised for him in last Saturday's Chronicle," said she. +"Here is the slip and here are four letters from him." + +"Thank you. And your address?" + +"No. 31 Lyon Place, Camberwell." + +"Mr. Angel's address you never had, I understand. Where is your +father's place of business?" + +"He travels for Westhouse & Marbank, the great claret importers +of Fenchurch Street." + +"Thank you. You have made your statement very clearly. You will +leave the papers here, and remember the advice which I have given +you. Let the whole incident be a sealed book, and do not allow it +to affect your life." + +"You are very kind, Mr. Holmes, but I cannot do that. I shall be +true to Hosmer. He shall find me ready when he comes back." + +For all the preposterous hat and the vacuous face, there was +something noble in the simple faith of our visitor which +compelled our respect. She laid her little bundle of papers upon +the table and went her way, with a promise to come again whenever +she might be summoned. + +Sherlock Holmes sat silent for a few minutes with his fingertips +still pressed together, his legs stretched out in front of him, +and his gaze directed upward to the ceiling. Then he took down +from the rack the old and oily clay pipe, which was to him as a +counsellor, and, having lit it, he leaned back in his chair, with +the thick blue cloud-wreaths spinning up from him, and a look of +infinite languor in his face. + +"Quite an interesting study, that maiden," he observed. "I found +her more interesting than her little problem, which, by the way, +is rather a trite one. You will find parallel cases, if you +consult my index, in Andover in '77, and there was something of +the sort at The Hague last year. Old as is the idea, however, +there were one or two details which were new to me. But the +maiden herself was most instructive." + +"You appeared to read a good deal upon her which was quite +invisible to me," I remarked. + +"Not invisible but unnoticed, Watson. You did not know where to +look, and so you missed all that was important. I can never bring +you to realise the importance of sleeves, the suggestiveness of +thumb-nails, or the great issues that may hang from a boot-lace. +Now, what did you gather from that woman's appearance? Describe +it." + +"Well, she had a slate-coloured, broad-brimmed straw hat, with a +feather of a brickish red. Her jacket was black, with black beads +sewn upon it, and a fringe of little black jet ornaments. Her +dress was brown, rather darker than coffee colour, with a little +purple plush at the neck and sleeves. Her gloves were greyish and +were worn through at the right forefinger. Her boots I didn't +observe. She had small round, hanging gold earrings, and a +general air of being fairly well-to-do in a vulgar, comfortable, +easy-going way." + +Sherlock Holmes clapped his hands softly together and chuckled. + +"'Pon my word, Watson, you are coming along wonderfully. You have +really done very well indeed. It is true that you have missed +everything of importance, but you have hit upon the method, and +you have a quick eye for colour. Never trust to general +impressions, my boy, but concentrate yourself upon details. My +first glance is always at a woman's sleeve. In a man it is +perhaps better first to take the knee of the trouser. As you +observe, this woman had plush upon her sleeves, which is a most +useful material for showing traces. The double line a little +above the wrist, where the typewritist presses against the table, +was beautifully defined. The sewing-machine, of the hand type, +leaves a similar mark, but only on the left arm, and on the side +of it farthest from the thumb, instead of being right across the +broadest part, as this was. I then glanced at her face, and, +observing the dint of a pince-nez at either side of her nose, I +ventured a remark upon short sight and typewriting, which seemed +to surprise her." + +"It surprised me." + +"But, surely, it was obvious. I was then much surprised and +interested on glancing down to observe that, though the boots +which she was wearing were not unlike each other, they were +really odd ones; the one having a slightly decorated toe-cap, and +the other a plain one. One was buttoned only in the two lower +buttons out of five, and the other at the first, third, and +fifth. Now, when you see that a young lady, otherwise neatly +dressed, has come away from home with odd boots, half-buttoned, +it is no great deduction to say that she came away in a hurry." + +"And what else?" I asked, keenly interested, as I always was, by +my friend's incisive reasoning. + +"I noted, in passing, that she had written a note before leaving +home but after being fully dressed. You observed that her right +glove was torn at the forefinger, but you did not apparently see +that both glove and finger were stained with violet ink. She had +written in a hurry and dipped her pen too deep. It must have been +this morning, or the mark would not remain clear upon the finger. +All this is amusing, though rather elementary, but I must go back +to business, Watson. Would you mind reading me the advertised +description of Mr. Hosmer Angel?" + +I held the little printed slip to the light. + +"Missing," it said, "on the morning of the fourteenth, a gentleman +named Hosmer Angel. About five ft. seven in. in height; +strongly built, sallow complexion, black hair, a little bald in +the centre, bushy, black side-whiskers and moustache; tinted +glasses, slight infirmity of speech. Was dressed, when last seen, +in black frock-coat faced with silk, black waistcoat, gold Albert +chain, and grey Harris tweed trousers, with brown gaiters over +elastic-sided boots. Known to have been employed in an office in +Leadenhall Street. Anybody bringing--" + +"That will do," said Holmes. "As to the letters," he continued, +glancing over them, "they are very commonplace. Absolutely no +clue in them to Mr. Angel, save that he quotes Balzac once. There +is one remarkable point, however, which will no doubt strike +you." + +"They are typewritten," I remarked. + +"Not only that, but the signature is typewritten. Look at the +neat little 'Hosmer Angel' at the bottom. There is a date, you +see, but no superscription except Leadenhall Street, which is +rather vague. The point about the signature is very suggestive--in +fact, we may call it conclusive." + +"Of what?" + +"My dear fellow, is it possible you do not see how strongly it +bears upon the case?" + +"I cannot say that I do unless it were that he wished to be able +to deny his signature if an action for breach of promise were +instituted." + +"No, that was not the point. However, I shall write two letters, +which should settle the matter. One is to a firm in the City, the +other is to the young lady's stepfather, Mr. Windibank, asking +him whether he could meet us here at six o'clock tomorrow +evening. It is just as well that we should do business with the +male relatives. And now, Doctor, we can do nothing until the +answers to those letters come, so we may put our little problem +upon the shelf for the interim." + +I had had so many reasons to believe in my friend's subtle powers +of reasoning and extraordinary energy in action that I felt that +he must have some solid grounds for the assured and easy +demeanour with which he treated the singular mystery which he had +been called upon to fathom. Once only had I known him to fail, in +the case of the King of Bohemia and of the Irene Adler +photograph; but when I looked back to the weird business of the +Sign of Four, and the extraordinary circumstances connected with +the Study in Scarlet, I felt that it would be a strange tangle +indeed which he could not unravel. + +I left him then, still puffing at his black clay pipe, with the +conviction that when I came again on the next evening I would +find that he held in his hands all the clues which would lead up +to the identity of the disappearing bridegroom of Miss Mary +Sutherland. + +A professional case of great gravity was engaging my own +attention at the time, and the whole of next day I was busy at +the bedside of the sufferer. It was not until close upon six +o'clock that I found myself free and was able to spring into a +hansom and drive to Baker Street, half afraid that I might be too +late to assist at the dnouement of the little mystery. I found +Sherlock Holmes alone, however, half asleep, with his long, thin +form curled up in the recesses of his armchair. A formidable +array of bottles and test-tubes, with the pungent cleanly smell +of hydrochloric acid, told me that he had spent his day in the +chemical work which was so dear to him. + +"Well, have you solved it?" I asked as I entered. + +"Yes. It was the bisulphate of baryta." + +"No, no, the mystery!" I cried. + +"Oh, that! I thought of the salt that I have been working upon. +There was never any mystery in the matter, though, as I said +yesterday, some of the details are of interest. The only drawback +is that there is no law, I fear, that can touch the scoundrel." + +"Who was he, then, and what was his object in deserting Miss +Sutherland?" + +The question was hardly out of my mouth, and Holmes had not yet +opened his lips to reply, when we heard a heavy footfall in the +passage and a tap at the door. + +"This is the girl's stepfather, Mr. James Windibank," said +Holmes. "He has written to me to say that he would be here at +six. Come in!" + +The man who entered was a sturdy, middle-sized fellow, some +thirty years of age, clean-shaven, and sallow-skinned, with a +bland, insinuating manner, and a pair of wonderfully sharp and +penetrating grey eyes. He shot a questioning glance at each of +us, placed his shiny top-hat upon the sideboard, and with a +slight bow sidled down into the nearest chair. + +"Good-evening, Mr. James Windibank," said Holmes. "I think that +this typewritten letter is from you, in which you made an +appointment with me for six o'clock?" + +"Yes, sir. I am afraid that I am a little late, but I am not +quite my own master, you know. I am sorry that Miss Sutherland +has troubled you about this little matter, for I think it is far +better not to wash linen of the sort in public. It was quite +against my wishes that she came, but she is a very excitable, +impulsive girl, as you may have noticed, and she is not easily +controlled when she has made up her mind on a point. Of course, I +did not mind you so much, as you are not connected with the +official police, but it is not pleasant to have a family +misfortune like this noised abroad. Besides, it is a useless +expense, for how could you possibly find this Hosmer Angel?" + +"On the contrary," said Holmes quietly; "I have every reason to +believe that I will succeed in discovering Mr. Hosmer Angel." + +Mr. Windibank gave a violent start and dropped his gloves. "I am +delighted to hear it," he said. + +"It is a curious thing," remarked Holmes, "that a typewriter has +really quite as much individuality as a man's handwriting. Unless +they are quite new, no two of them write exactly alike. Some +letters get more worn than others, and some wear only on one +side. Now, you remark in this note of yours, Mr. Windibank, that +in every case there is some little slurring over of the 'e,' and +a slight defect in the tail of the 'r.' There are fourteen other +characteristics, but those are the more obvious." + +"We do all our correspondence with this machine at the office, +and no doubt it is a little worn," our visitor answered, glancing +keenly at Holmes with his bright little eyes. + +"And now I will show you what is really a very interesting study, +Mr. Windibank," Holmes continued. "I think of writing another +little monograph some of these days on the typewriter and its +relation to crime. It is a subject to which I have devoted some +little attention. I have here four letters which purport to come +from the missing man. They are all typewritten. In each case, not +only are the 'e's' slurred and the 'r's' tailless, but you will +observe, if you care to use my magnifying lens, that the fourteen +other characteristics to which I have alluded are there as well." + +Mr. Windibank sprang out of his chair and picked up his hat. "I +cannot waste time over this sort of fantastic talk, Mr. Holmes," +he said. "If you can catch the man, catch him, and let me know +when you have done it." + +"Certainly," said Holmes, stepping over and turning the key in +the door. "I let you know, then, that I have caught him!" + +"What! where?" shouted Mr. Windibank, turning white to his lips +and glancing about him like a rat in a trap. + +"Oh, it won't do--really it won't," said Holmes suavely. "There +is no possible getting out of it, Mr. Windibank. It is quite too +transparent, and it was a very bad compliment when you said that +it was impossible for me to solve so simple a question. That's +right! Sit down and let us talk it over." + +Our visitor collapsed into a chair, with a ghastly face and a +glitter of moisture on his brow. "It--it's not actionable," he +stammered. + +"I am very much afraid that it is not. But between ourselves, +Windibank, it was as cruel and selfish and heartless a trick in a +petty way as ever came before me. Now, let me just run over the +course of events, and you will contradict me if I go wrong." + +The man sat huddled up in his chair, with his head sunk upon his +breast, like one who is utterly crushed. Holmes stuck his feet up +on the corner of the mantelpiece and, leaning back with his hands +in his pockets, began talking, rather to himself, as it seemed, +than to us. + +"The man married a woman very much older than himself for her +money," said he, "and he enjoyed the use of the money of the +daughter as long as she lived with them. It was a considerable +sum, for people in their position, and the loss of it would have +made a serious difference. It was worth an effort to preserve it. +The daughter was of a good, amiable disposition, but affectionate +and warm-hearted in her ways, so that it was evident that with +her fair personal advantages, and her little income, she would +not be allowed to remain single long. Now her marriage would +mean, of course, the loss of a hundred a year, so what does her +stepfather do to prevent it? He takes the obvious course of +keeping her at home and forbidding her to seek the company of +people of her own age. But soon he found that that would not +answer forever. She became restive, insisted upon her rights, and +finally announced her positive intention of going to a certain +ball. What does her clever stepfather do then? He conceives an +idea more creditable to his head than to his heart. With the +connivance and assistance of his wife he disguised himself, +covered those keen eyes with tinted glasses, masked the face with +a moustache and a pair of bushy whiskers, sunk that clear voice +into an insinuating whisper, and doubly secure on account of the +girl's short sight, he appears as Mr. Hosmer Angel, and keeps off +other lovers by making love himself." + +"It was only a joke at first," groaned our visitor. "We never +thought that she would have been so carried away." + +"Very likely not. However that may be, the young lady was very +decidedly carried away, and, having quite made up her mind that +her stepfather was in France, the suspicion of treachery never +for an instant entered her mind. She was flattered by the +gentleman's attentions, and the effect was increased by the +loudly expressed admiration of her mother. Then Mr. Angel began +to call, for it was obvious that the matter should be pushed as +far as it would go if a real effect were to be produced. There +were meetings, and an engagement, which would finally secure the +girl's affections from turning towards anyone else. But the +deception could not be kept up forever. These pretended journeys +to France were rather cumbrous. The thing to do was clearly to +bring the business to an end in such a dramatic manner that it +would leave a permanent impression upon the young lady's mind and +prevent her from looking upon any other suitor for some time to +come. Hence those vows of fidelity exacted upon a Testament, and +hence also the allusions to a possibility of something happening +on the very morning of the wedding. James Windibank wished Miss +Sutherland to be so bound to Hosmer Angel, and so uncertain as to +his fate, that for ten years to come, at any rate, she would not +listen to another man. As far as the church door he brought her, +and then, as he could go no farther, he conveniently vanished +away by the old trick of stepping in at one door of a +four-wheeler and out at the other. I think that was the chain of +events, Mr. Windibank!" + +Our visitor had recovered something of his assurance while Holmes +had been talking, and he rose from his chair now with a cold +sneer upon his pale face. + +"It may be so, or it may not, Mr. Holmes," said he, "but if you +are so very sharp you ought to be sharp enough to know that it is +you who are breaking the law now, and not me. I have done nothing +actionable from the first, but as long as you keep that door +locked you lay yourself open to an action for assault and illegal +constraint." + +"The law cannot, as you say, touch you," said Holmes, unlocking +and throwing open the door, "yet there never was a man who +deserved punishment more. If the young lady has a brother or a +friend, he ought to lay a whip across your shoulders. By Jove!" +he continued, flushing up at the sight of the bitter sneer upon +the man's face, "it is not part of my duties to my client, but +here's a hunting crop handy, and I think I shall just treat +myself to--" He took two swift steps to the whip, but before he +could grasp it there was a wild clatter of steps upon the stairs, +the heavy hall door banged, and from the window we could see Mr. +James Windibank running at the top of his speed down the road. + +"There's a cold-blooded scoundrel!" said Holmes, laughing, as he +threw himself down into his chair once more. "That fellow will +rise from crime to crime until he does something very bad, and +ends on a gallows. The case has, in some respects, been not +entirely devoid of interest." + +"I cannot now entirely see all the steps of your reasoning," I +remarked. + +"Well, of course it was obvious from the first that this Mr. +Hosmer Angel must have some strong object for his curious +conduct, and it was equally clear that the only man who really +profited by the incident, as far as we could see, was the +stepfather. Then the fact that the two men were never together, +but that the one always appeared when the other was away, was +suggestive. So were the tinted spectacles and the curious voice, +which both hinted at a disguise, as did the bushy whiskers. My +suspicions were all confirmed by his peculiar action in +typewriting his signature, which, of course, inferred that his +handwriting was so familiar to her that she would recognise even +the smallest sample of it. You see all these isolated facts, +together with many minor ones, all pointed in the same +direction." + +"And how did you verify them?" + +"Having once spotted my man, it was easy to get corroboration. I +knew the firm for which this man worked. Having taken the printed +description. I eliminated everything from it which could be the +result of a disguise--the whiskers, the glasses, the voice, and I +sent it to the firm, with a request that they would inform me +whether it answered to the description of any of their +travellers. I had already noticed the peculiarities of the +typewriter, and I wrote to the man himself at his business +address asking him if he would come here. As I expected, his +reply was typewritten and revealed the same trivial but +characteristic defects. The same post brought me a letter from +Westhouse & Marbank, of Fenchurch Street, to say that the +description tallied in every respect with that of their employ, +James Windibank. Voil tout!" + +"And Miss Sutherland?" + +"If I tell her she will not believe me. You may remember the old +Persian saying, 'There is danger for him who taketh the tiger +cub, and danger also for whoso snatches a delusion from a woman.' +There is as much sense in Hafiz as in Horace, and as much +knowledge of the world." + + + +ADVENTURE IV. THE BOSCOMBE VALLEY MYSTERY + +We were seated at breakfast one morning, my wife and I, when the +maid brought in a telegram. It was from Sherlock Holmes and ran +in this way: + +"Have you a couple of days to spare? Have just been wired for from +the west of England in connection with Boscombe Valley tragedy. +Shall be glad if you will come with me. Air and scenery perfect. +Leave Paddington by the 11:15." + +"What do you say, dear?" said my wife, looking across at me. +"Will you go?" + +"I really don't know what to say. I have a fairly long list at +present." + +"Oh, Anstruther would do your work for you. You have been looking +a little pale lately. I think that the change would do you good, +and you are always so interested in Mr. Sherlock Holmes' cases." + +"I should be ungrateful if I were not, seeing what I gained +through one of them," I answered. "But if I am to go, I must pack +at once, for I have only half an hour." + +My experience of camp life in Afghanistan had at least had the +effect of making me a prompt and ready traveller. My wants were +few and simple, so that in less than the time stated I was in a +cab with my valise, rattling away to Paddington Station. Sherlock +Holmes was pacing up and down the platform, his tall, gaunt +figure made even gaunter and taller by his long grey +travelling-cloak and close-fitting cloth cap. + +"It is really very good of you to come, Watson," said he. "It +makes a considerable difference to me, having someone with me on +whom I can thoroughly rely. Local aid is always either worthless +or else biassed. If you will keep the two corner seats I shall +get the tickets." + +We had the carriage to ourselves save for an immense litter of +papers which Holmes had brought with him. Among these he rummaged +and read, with intervals of note-taking and of meditation, until +we were past Reading. Then he suddenly rolled them all into a +gigantic ball and tossed them up onto the rack. + +"Have you heard anything of the case?" he asked. + +"Not a word. I have not seen a paper for some days." + +"The London press has not had very full accounts. I have just +been looking through all the recent papers in order to master the +particulars. It seems, from what I gather, to be one of those +simple cases which are so extremely difficult." + +"That sounds a little paradoxical." + +"But it is profoundly true. Singularity is almost invariably a +clue. The more featureless and commonplace a crime is, the more +difficult it is to bring it home. In this case, however, they +have established a very serious case against the son of the +murdered man." + +"It is a murder, then?" + +"Well, it is conjectured to be so. I shall take nothing for +granted until I have the opportunity of looking personally into +it. I will explain the state of things to you, as far as I have +been able to understand it, in a very few words. + +"Boscombe Valley is a country district not very far from Ross, in +Herefordshire. The largest landed proprietor in that part is a +Mr. John Turner, who made his money in Australia and returned +some years ago to the old country. One of the farms which he +held, that of Hatherley, was let to Mr. Charles McCarthy, who was +also an ex-Australian. The men had known each other in the +colonies, so that it was not unnatural that when they came to +settle down they should do so as near each other as possible. +Turner was apparently the richer man, so McCarthy became his +tenant but still remained, it seems, upon terms of perfect +equality, as they were frequently together. McCarthy had one son, +a lad of eighteen, and Turner had an only daughter of the same +age, but neither of them had wives living. They appear to have +avoided the society of the neighbouring English families and to +have led retired lives, though both the McCarthys were fond of +sport and were frequently seen at the race-meetings of the +neighbourhood. McCarthy kept two servants--a man and a girl. +Turner had a considerable household, some half-dozen at the +least. That is as much as I have been able to gather about the +families. Now for the facts. + +"On June 3rd, that is, on Monday last, McCarthy left his house at +Hatherley about three in the afternoon and walked down to the +Boscombe Pool, which is a small lake formed by the spreading out +of the stream which runs down the Boscombe Valley. He had been +out with his serving-man in the morning at Ross, and he had told +the man that he must hurry, as he had an appointment of +importance to keep at three. From that appointment he never came +back alive. + +"From Hatherley Farm-house to the Boscombe Pool is a quarter of a +mile, and two people saw him as he passed over this ground. One +was an old woman, whose name is not mentioned, and the other was +William Crowder, a game-keeper in the employ of Mr. Turner. Both +these witnesses depose that Mr. McCarthy was walking alone. The +game-keeper adds that within a few minutes of his seeing Mr. +McCarthy pass he had seen his son, Mr. James McCarthy, going the +same way with a gun under his arm. To the best of his belief, the +father was actually in sight at the time, and the son was +following him. He thought no more of the matter until he heard in +the evening of the tragedy that had occurred. + +"The two McCarthys were seen after the time when William Crowder, +the game-keeper, lost sight of them. The Boscombe Pool is thickly +wooded round, with just a fringe of grass and of reeds round the +edge. A girl of fourteen, Patience Moran, who is the daughter of +the lodge-keeper of the Boscombe Valley estate, was in one of the +woods picking flowers. She states that while she was there she +saw, at the border of the wood and close by the lake, Mr. +McCarthy and his son, and that they appeared to be having a +violent quarrel. She heard Mr. McCarthy the elder using very +strong language to his son, and she saw the latter raise up his +hand as if to strike his father. She was so frightened by their +violence that she ran away and told her mother when she reached +home that she had left the two McCarthys quarrelling near +Boscombe Pool, and that she was afraid that they were going to +fight. She had hardly said the words when young Mr. McCarthy came +running up to the lodge to say that he had found his father dead +in the wood, and to ask for the help of the lodge-keeper. He was +much excited, without either his gun or his hat, and his right +hand and sleeve were observed to be stained with fresh blood. On +following him they found the dead body stretched out upon the +grass beside the pool. The head had been beaten in by repeated +blows of some heavy and blunt weapon. The injuries were such as +might very well have been inflicted by the butt-end of his son's +gun, which was found lying on the grass within a few paces of the +body. Under these circumstances the young man was instantly +arrested, and a verdict of 'wilful murder' having been returned +at the inquest on Tuesday, he was on Wednesday brought before the +magistrates at Ross, who have referred the case to the next +Assizes. Those are the main facts of the case as they came out +before the coroner and the police-court." + +"I could hardly imagine a more damning case," I remarked. "If +ever circumstantial evidence pointed to a criminal it does so +here." + +"Circumstantial evidence is a very tricky thing," answered Holmes +thoughtfully. "It may seem to point very straight to one thing, +but if you shift your own point of view a little, you may find it +pointing in an equally uncompromising manner to something +entirely different. It must be confessed, however, that the case +looks exceedingly grave against the young man, and it is very +possible that he is indeed the culprit. There are several people +in the neighbourhood, however, and among them Miss Turner, the +daughter of the neighbouring landowner, who believe in his +innocence, and who have retained Lestrade, whom you may recollect +in connection with the Study in Scarlet, to work out the case in +his interest. Lestrade, being rather puzzled, has referred the +case to me, and hence it is that two middle-aged gentlemen are +flying westward at fifty miles an hour instead of quietly +digesting their breakfasts at home." + +"I am afraid," said I, "that the facts are so obvious that you +will find little credit to be gained out of this case." + +"There is nothing more deceptive than an obvious fact," he +answered, laughing. "Besides, we may chance to hit upon some +other obvious facts which may have been by no means obvious to +Mr. Lestrade. You know me too well to think that I am boasting +when I say that I shall either confirm or destroy his theory by +means which he is quite incapable of employing, or even of +understanding. To take the first example to hand, I very clearly +perceive that in your bedroom the window is upon the right-hand +side, and yet I question whether Mr. Lestrade would have noted +even so self-evident a thing as that." + +"How on earth--" + +"My dear fellow, I know you well. I know the military neatness +which characterises you. You shave every morning, and in this +season you shave by the sunlight; but since your shaving is less +and less complete as we get farther back on the left side, until +it becomes positively slovenly as we get round the angle of the +jaw, it is surely very clear that that side is less illuminated +than the other. I could not imagine a man of your habits looking +at himself in an equal light and being satisfied with such a +result. I only quote this as a trivial example of observation and +inference. Therein lies my mtier, and it is just possible that +it may be of some service in the investigation which lies before +us. There are one or two minor points which were brought out in +the inquest, and which are worth considering." + +"What are they?" + +"It appears that his arrest did not take place at once, but after +the return to Hatherley Farm. On the inspector of constabulary +informing him that he was a prisoner, he remarked that he was not +surprised to hear it, and that it was no more than his deserts. +This observation of his had the natural effect of removing any +traces of doubt which might have remained in the minds of the +coroner's jury." + +"It was a confession," I ejaculated. + +"No, for it was followed by a protestation of innocence." + +"Coming on the top of such a damning series of events, it was at +least a most suspicious remark." + +"On the contrary," said Holmes, "it is the brightest rift which I +can at present see in the clouds. However innocent he might be, +he could not be such an absolute imbecile as not to see that the +circumstances were very black against him. Had he appeared +surprised at his own arrest, or feigned indignation at it, I +should have looked upon it as highly suspicious, because such +surprise or anger would not be natural under the circumstances, +and yet might appear to be the best policy to a scheming man. His +frank acceptance of the situation marks him as either an innocent +man, or else as a man of considerable self-restraint and +firmness. As to his remark about his deserts, it was also not +unnatural if you consider that he stood beside the dead body of +his father, and that there is no doubt that he had that very day +so far forgotten his filial duty as to bandy words with him, and +even, according to the little girl whose evidence is so +important, to raise his hand as if to strike him. The +self-reproach and contrition which are displayed in his remark +appear to me to be the signs of a healthy mind rather than of a +guilty one." + +I shook my head. "Many men have been hanged on far slighter +evidence," I remarked. + +"So they have. And many men have been wrongfully hanged." + +"What is the young man's own account of the matter?" + +"It is, I am afraid, not very encouraging to his supporters, +though there are one or two points in it which are suggestive. +You will find it here, and may read it for yourself." + +He picked out from his bundle a copy of the local Herefordshire +paper, and having turned down the sheet he pointed out the +paragraph in which the unfortunate young man had given his own +statement of what had occurred. I settled myself down in the +corner of the carriage and read it very carefully. It ran in this +way: + +"Mr. James McCarthy, the only son of the deceased, was then called +and gave evidence as follows: 'I had been away from home for +three days at Bristol, and had only just returned upon the +morning of last Monday, the 3rd. My father was absent from home at +the time of my arrival, and I was informed by the maid that he +had driven over to Ross with John Cobb, the groom. Shortly after +my return I heard the wheels of his trap in the yard, and, +looking out of my window, I saw him get out and walk rapidly out +of the yard, though I was not aware in which direction he was +going. I then took my gun and strolled out in the direction of +the Boscombe Pool, with the intention of visiting the rabbit +warren which is upon the other side. On my way I saw William +Crowder, the game-keeper, as he had stated in his evidence; but +he is mistaken in thinking that I was following my father. I had +no idea that he was in front of me. When about a hundred yards +from the pool I heard a cry of "Cooee!" which was a usual signal +between my father and myself. I then hurried forward, and found +him standing by the pool. He appeared to be much surprised at +seeing me and asked me rather roughly what I was doing there. A +conversation ensued which led to high words and almost to blows, +for my father was a man of a very violent temper. Seeing that his +passion was becoming ungovernable, I left him and returned +towards Hatherley Farm. I had not gone more than 150 yards, +however, when I heard a hideous outcry behind me, which caused me +to run back again. I found my father expiring upon the ground, +with his head terribly injured. I dropped my gun and held him in +my arms, but he almost instantly expired. I knelt beside him for +some minutes, and then made my way to Mr. Turner's lodge-keeper, +his house being the nearest, to ask for assistance. I saw no one +near my father when I returned, and I have no idea how he came by +his injuries. He was not a popular man, being somewhat cold and +forbidding in his manners, but he had, as far as I know, no +active enemies. I know nothing further of the matter.' + +"The Coroner: Did your father make any statement to you before +he died? + +"Witness: He mumbled a few words, but I could only catch some +allusion to a rat. + +"The Coroner: What did you understand by that? + +"Witness: It conveyed no meaning to me. I thought that he was +delirious. + +"The Coroner: What was the point upon which you and your father +had this final quarrel? + +"Witness: I should prefer not to answer. + +"The Coroner: I am afraid that I must press it. + +"Witness: It is really impossible for me to tell you. I can +assure you that it has nothing to do with the sad tragedy which +followed. + +"The Coroner: That is for the court to decide. I need not point +out to you that your refusal to answer will prejudice your case +considerably in any future proceedings which may arise. + +"Witness: I must still refuse. + +"The Coroner: I understand that the cry of 'Cooee' was a common +signal between you and your father? + +"Witness: It was. + +"The Coroner: How was it, then, that he uttered it before he saw +you, and before he even knew that you had returned from Bristol? + +"Witness (with considerable confusion): I do not know. + +"A Juryman: Did you see nothing which aroused your suspicions +when you returned on hearing the cry and found your father +fatally injured? + +"Witness: Nothing definite. + +"The Coroner: What do you mean? + +"Witness: I was so disturbed and excited as I rushed out into +the open, that I could think of nothing except of my father. Yet +I have a vague impression that as I ran forward something lay +upon the ground to the left of me. It seemed to me to be +something grey in colour, a coat of some sort, or a plaid perhaps. +When I rose from my father I looked round for it, but it was +gone. + +"'Do you mean that it disappeared before you went for help?' + +"'Yes, it was gone.' + +"'You cannot say what it was?' + +"'No, I had a feeling something was there.' + +"'How far from the body?' + +"'A dozen yards or so.' + +"'And how far from the edge of the wood?' + +"'About the same.' + +"'Then if it was removed it was while you were within a dozen +yards of it?' + +"'Yes, but with my back towards it.' + +"This concluded the examination of the witness." + +"I see," said I as I glanced down the column, "that the coroner +in his concluding remarks was rather severe upon young McCarthy. +He calls attention, and with reason, to the discrepancy about his +father having signalled to him before seeing him, also to his +refusal to give details of his conversation with his father, and +his singular account of his father's dying words. They are all, +as he remarks, very much against the son." + +Holmes laughed softly to himself and stretched himself out upon +the cushioned seat. "Both you and the coroner have been at some +pains," said he, "to single out the very strongest points in the +young man's favour. Don't you see that you alternately give him +credit for having too much imagination and too little? Too +little, if he could not invent a cause of quarrel which would +give him the sympathy of the jury; too much, if he evolved from +his own inner consciousness anything so outr as a dying +reference to a rat, and the incident of the vanishing cloth. No, +sir, I shall approach this case from the point of view that what +this young man says is true, and we shall see whither that +hypothesis will lead us. And now here is my pocket Petrarch, and +not another word shall I say of this case until we are on the +scene of action. We lunch at Swindon, and I see that we shall be +there in twenty minutes." + +It was nearly four o'clock when we at last, after passing through +the beautiful Stroud Valley, and over the broad gleaming Severn, +found ourselves at the pretty little country-town of Ross. A +lean, ferret-like man, furtive and sly-looking, was waiting for +us upon the platform. In spite of the light brown dustcoat and +leather-leggings which he wore in deference to his rustic +surroundings, I had no difficulty in recognising Lestrade, of +Scotland Yard. With him we drove to the Hereford Arms where a +room had already been engaged for us. + +"I have ordered a carriage," said Lestrade as we sat over a cup +of tea. "I knew your energetic nature, and that you would not be +happy until you had been on the scene of the crime." + +"It was very nice and complimentary of you," Holmes answered. "It +is entirely a question of barometric pressure." + +Lestrade looked startled. "I do not quite follow," he said. + +"How is the glass? Twenty-nine, I see. No wind, and not a cloud +in the sky. I have a caseful of cigarettes here which need +smoking, and the sofa is very much superior to the usual country +hotel abomination. I do not think that it is probable that I +shall use the carriage to-night." + +Lestrade laughed indulgently. "You have, no doubt, already formed +your conclusions from the newspapers," he said. "The case is as +plain as a pikestaff, and the more one goes into it the plainer +it becomes. Still, of course, one can't refuse a lady, and such a +very positive one, too. She has heard of you, and would have your +opinion, though I repeatedly told her that there was nothing +which you could do which I had not already done. Why, bless my +soul! here is her carriage at the door." + +He had hardly spoken before there rushed into the room one of the +most lovely young women that I have ever seen in my life. Her +violet eyes shining, her lips parted, a pink flush upon her +cheeks, all thought of her natural reserve lost in her +overpowering excitement and concern. + +"Oh, Mr. Sherlock Holmes!" she cried, glancing from one to the +other of us, and finally, with a woman's quick intuition, +fastening upon my companion, "I am so glad that you have come. I +have driven down to tell you so. I know that James didn't do it. +I know it, and I want you to start upon your work knowing it, +too. Never let yourself doubt upon that point. We have known each +other since we were little children, and I know his faults as no +one else does; but he is too tender-hearted to hurt a fly. Such a +charge is absurd to anyone who really knows him." + +"I hope we may clear him, Miss Turner," said Sherlock Holmes. +"You may rely upon my doing all that I can." + +"But you have read the evidence. You have formed some conclusion? +Do you not see some loophole, some flaw? Do you not yourself +think that he is innocent?" + +"I think that it is very probable." + +"There, now!" she cried, throwing back her head and looking +defiantly at Lestrade. "You hear! He gives me hopes." + +Lestrade shrugged his shoulders. "I am afraid that my colleague +has been a little quick in forming his conclusions," he said. + +"But he is right. Oh! I know that he is right. James never did +it. And about his quarrel with his father, I am sure that the +reason why he would not speak about it to the coroner was because +I was concerned in it." + +"In what way?" asked Holmes. + +"It is no time for me to hide anything. James and his father had +many disagreements about me. Mr. McCarthy was very anxious that +there should be a marriage between us. James and I have always +loved each other as brother and sister; but of course he is young +and has seen very little of life yet, and--and--well, he +naturally did not wish to do anything like that yet. So there +were quarrels, and this, I am sure, was one of them." + +"And your father?" asked Holmes. "Was he in favour of such a +union?" + +"No, he was averse to it also. No one but Mr. McCarthy was in +favour of it." A quick blush passed over her fresh young face as +Holmes shot one of his keen, questioning glances at her. + +"Thank you for this information," said he. "May I see your father +if I call to-morrow?" + +"I am afraid the doctor won't allow it." + +"The doctor?" + +"Yes, have you not heard? Poor father has never been strong for +years back, but this has broken him down completely. He has taken +to his bed, and Dr. Willows says that he is a wreck and that his +nervous system is shattered. Mr. McCarthy was the only man alive +who had known dad in the old days in Victoria." + +"Ha! In Victoria! That is important." + +"Yes, at the mines." + +"Quite so; at the gold-mines, where, as I understand, Mr. Turner +made his money." + +"Yes, certainly." + +"Thank you, Miss Turner. You have been of material assistance to +me." + +"You will tell me if you have any news to-morrow. No doubt you +will go to the prison to see James. Oh, if you do, Mr. Holmes, do +tell him that I know him to be innocent." + +"I will, Miss Turner." + +"I must go home now, for dad is very ill, and he misses me so if +I leave him. Good-bye, and God help you in your undertaking." She +hurried from the room as impulsively as she had entered, and we +heard the wheels of her carriage rattle off down the street. + +"I am ashamed of you, Holmes," said Lestrade with dignity after a +few minutes' silence. "Why should you raise up hopes which you +are bound to disappoint? I am not over-tender of heart, but I +call it cruel." + +"I think that I see my way to clearing James McCarthy," said +Holmes. "Have you an order to see him in prison?" + +"Yes, but only for you and me." + +"Then I shall reconsider my resolution about going out. We have +still time to take a train to Hereford and see him to-night?" + +"Ample." + +"Then let us do so. Watson, I fear that you will find it very +slow, but I shall only be away a couple of hours." + +I walked down to the station with them, and then wandered through +the streets of the little town, finally returning to the hotel, +where I lay upon the sofa and tried to interest myself in a +yellow-backed novel. The puny plot of the story was so thin, +however, when compared to the deep mystery through which we were +groping, and I found my attention wander so continually from the +action to the fact, that I at last flung it across the room and +gave myself up entirely to a consideration of the events of the +day. Supposing that this unhappy young man's story were +absolutely true, then what hellish thing, what absolutely +unforeseen and extraordinary calamity could have occurred between +the time when he parted from his father, and the moment when, +drawn back by his screams, he rushed into the glade? It was +something terrible and deadly. What could it be? Might not the +nature of the injuries reveal something to my medical instincts? +I rang the bell and called for the weekly county paper, which +contained a verbatim account of the inquest. In the surgeon's +deposition it was stated that the posterior third of the left +parietal bone and the left half of the occipital bone had been +shattered by a heavy blow from a blunt weapon. I marked the spot +upon my own head. Clearly such a blow must have been struck from +behind. That was to some extent in favour of the accused, as when +seen quarrelling he was face to face with his father. Still, it +did not go for very much, for the older man might have turned his +back before the blow fell. Still, it might be worth while to call +Holmes' attention to it. Then there was the peculiar dying +reference to a rat. What could that mean? It could not be +delirium. A man dying from a sudden blow does not commonly become +delirious. No, it was more likely to be an attempt to explain how +he met his fate. But what could it indicate? I cudgelled my +brains to find some possible explanation. And then the incident +of the grey cloth seen by young McCarthy. If that were true the +murderer must have dropped some part of his dress, presumably his +overcoat, in his flight, and must have had the hardihood to +return and to carry it away at the instant when the son was +kneeling with his back turned not a dozen paces off. What a +tissue of mysteries and improbabilities the whole thing was! I +did not wonder at Lestrade's opinion, and yet I had so much faith +in Sherlock Holmes' insight that I could not lose hope as long +as every fresh fact seemed to strengthen his conviction of young +McCarthy's innocence. + +It was late before Sherlock Holmes returned. He came back alone, +for Lestrade was staying in lodgings in the town. + +"The glass still keeps very high," he remarked as he sat down. +"It is of importance that it should not rain before we are able +to go over the ground. On the other hand, a man should be at his +very best and keenest for such nice work as that, and I did not +wish to do it when fagged by a long journey. I have seen young +McCarthy." + +"And what did you learn from him?" + +"Nothing." + +"Could he throw no light?" + +"None at all. I was inclined to think at one time that he knew +who had done it and was screening him or her, but I am convinced +now that he is as puzzled as everyone else. He is not a very +quick-witted youth, though comely to look at and, I should think, +sound at heart." + +"I cannot admire his taste," I remarked, "if it is indeed a fact +that he was averse to a marriage with so charming a young lady as +this Miss Turner." + +"Ah, thereby hangs a rather painful tale. This fellow is madly, +insanely, in love with her, but some two years ago, when he was +only a lad, and before he really knew her, for she had been away +five years at a boarding-school, what does the idiot do but get +into the clutches of a barmaid in Bristol and marry her at a +registry office? No one knows a word of the matter, but you can +imagine how maddening it must be to him to be upbraided for not +doing what he would give his very eyes to do, but what he knows +to be absolutely impossible. It was sheer frenzy of this sort +which made him throw his hands up into the air when his father, +at their last interview, was goading him on to propose to Miss +Turner. On the other hand, he had no means of supporting himself, +and his father, who was by all accounts a very hard man, would +have thrown him over utterly had he known the truth. It was with +his barmaid wife that he had spent the last three days in +Bristol, and his father did not know where he was. Mark that +point. It is of importance. Good has come out of evil, however, +for the barmaid, finding from the papers that he is in serious +trouble and likely to be hanged, has thrown him over utterly and +has written to him to say that she has a husband already in the +Bermuda Dockyard, so that there is really no tie between them. I +think that that bit of news has consoled young McCarthy for all +that he has suffered." + +"But if he is innocent, who has done it?" + +"Ah! who? I would call your attention very particularly to two +points. One is that the murdered man had an appointment with +someone at the pool, and that the someone could not have been his +son, for his son was away, and he did not know when he would +return. The second is that the murdered man was heard to cry +'Cooee!' before he knew that his son had returned. Those are the +crucial points upon which the case depends. And now let us talk +about George Meredith, if you please, and we shall leave all +minor matters until to-morrow." + +There was no rain, as Holmes had foretold, and the morning broke +bright and cloudless. At nine o'clock Lestrade called for us with +the carriage, and we set off for Hatherley Farm and the Boscombe +Pool. + +"There is serious news this morning," Lestrade observed. "It is +said that Mr. Turner, of the Hall, is so ill that his life is +despaired of." + +"An elderly man, I presume?" said Holmes. + +"About sixty; but his constitution has been shattered by his life +abroad, and he has been in failing health for some time. This +business has had a very bad effect upon him. He was an old friend +of McCarthy's, and, I may add, a great benefactor to him, for I +have learned that he gave him Hatherley Farm rent free." + +"Indeed! That is interesting," said Holmes. + +"Oh, yes! In a hundred other ways he has helped him. Everybody +about here speaks of his kindness to him." + +"Really! Does it not strike you as a little singular that this +McCarthy, who appears to have had little of his own, and to have +been under such obligations to Turner, should still talk of +marrying his son to Turner's daughter, who is, presumably, +heiress to the estate, and that in such a very cocksure manner, +as if it were merely a case of a proposal and all else would +follow? It is the more strange, since we know that Turner himself +was averse to the idea. The daughter told us as much. Do you not +deduce something from that?" + +"We have got to the deductions and the inferences," said +Lestrade, winking at me. "I find it hard enough to tackle facts, +Holmes, without flying away after theories and fancies." + +"You are right," said Holmes demurely; "you do find it very hard +to tackle the facts." + +"Anyhow, I have grasped one fact which you seem to find it +difficult to get hold of," replied Lestrade with some warmth. + +"And that is--" + +"That McCarthy senior met his death from McCarthy junior and that +all theories to the contrary are the merest moonshine." + +"Well, moonshine is a brighter thing than fog," said Holmes, +laughing. "But I am very much mistaken if this is not Hatherley +Farm upon the left." + +"Yes, that is it." It was a widespread, comfortable-looking +building, two-storied, slate-roofed, with great yellow blotches +of lichen upon the grey walls. The drawn blinds and the smokeless +chimneys, however, gave it a stricken look, as though the weight +of this horror still lay heavy upon it. We called at the door, +when the maid, at Holmes' request, showed us the boots which her +master wore at the time of his death, and also a pair of the +son's, though not the pair which he had then had. Having measured +these very carefully from seven or eight different points, Holmes +desired to be led to the court-yard, from which we all followed +the winding track which led to Boscombe Pool. + +Sherlock Holmes was transformed when he was hot upon such a scent +as this. Men who had only known the quiet thinker and logician of +Baker Street would have failed to recognise him. His face flushed +and darkened. His brows were drawn into two hard black lines, +while his eyes shone out from beneath them with a steely glitter. +His face was bent downward, his shoulders bowed, his lips +compressed, and the veins stood out like whipcord in his long, +sinewy neck. His nostrils seemed to dilate with a purely animal +lust for the chase, and his mind was so absolutely concentrated +upon the matter before him that a question or remark fell +unheeded upon his ears, or, at the most, only provoked a quick, +impatient snarl in reply. Swiftly and silently he made his way +along the track which ran through the meadows, and so by way of +the woods to the Boscombe Pool. It was damp, marshy ground, as is +all that district, and there were marks of many feet, both upon +the path and amid the short grass which bounded it on either +side. Sometimes Holmes would hurry on, sometimes stop dead, and +once he made quite a little detour into the meadow. Lestrade and +I walked behind him, the detective indifferent and contemptuous, +while I watched my friend with the interest which sprang from the +conviction that every one of his actions was directed towards a +definite end. + +The Boscombe Pool, which is a little reed-girt sheet of water +some fifty yards across, is situated at the boundary between the +Hatherley Farm and the private park of the wealthy Mr. Turner. +Above the woods which lined it upon the farther side we could see +the red, jutting pinnacles which marked the site of the rich +landowner's dwelling. On the Hatherley side of the pool the woods +grew very thick, and there was a narrow belt of sodden grass +twenty paces across between the edge of the trees and the reeds +which lined the lake. Lestrade showed us the exact spot at which +the body had been found, and, indeed, so moist was the ground, +that I could plainly see the traces which had been left by the +fall of the stricken man. To Holmes, as I could see by his eager +face and peering eyes, very many other things were to be read +upon the trampled grass. He ran round, like a dog who is picking +up a scent, and then turned upon my companion. + +"What did you go into the pool for?" he asked. + +"I fished about with a rake. I thought there might be some weapon +or other trace. But how on earth--" + +"Oh, tut, tut! I have no time! That left foot of yours with its +inward twist is all over the place. A mole could trace it, and +there it vanishes among the reeds. Oh, how simple it would all +have been had I been here before they came like a herd of buffalo +and wallowed all over it. Here is where the party with the +lodge-keeper came, and they have covered all tracks for six or +eight feet round the body. But here are three separate tracks of +the same feet." He drew out a lens and lay down upon his +waterproof to have a better view, talking all the time rather to +himself than to us. "These are young McCarthy's feet. Twice he +was walking, and once he ran swiftly, so that the soles are +deeply marked and the heels hardly visible. That bears out his +story. He ran when he saw his father on the ground. Then here are +the father's feet as he paced up and down. What is this, then? It +is the butt-end of the gun as the son stood listening. And this? +Ha, ha! What have we here? Tiptoes! tiptoes! Square, too, quite +unusual boots! They come, they go, they come again--of course +that was for the cloak. Now where did they come from?" He ran up +and down, sometimes losing, sometimes finding the track until we +were well within the edge of the wood and under the shadow of a +great beech, the largest tree in the neighbourhood. Holmes traced +his way to the farther side of this and lay down once more upon +his face with a little cry of satisfaction. For a long time he +remained there, turning over the leaves and dried sticks, +gathering up what seemed to me to be dust into an envelope and +examining with his lens not only the ground but even the bark of +the tree as far as he could reach. A jagged stone was lying among +the moss, and this also he carefully examined and retained. Then +he followed a pathway through the wood until he came to the +highroad, where all traces were lost. + +"It has been a case of considerable interest," he remarked, +returning to his natural manner. "I fancy that this grey house on +the right must be the lodge. I think that I will go in and have a +word with Moran, and perhaps write a little note. Having done +that, we may drive back to our luncheon. You may walk to the cab, +and I shall be with you presently." + +It was about ten minutes before we regained our cab and drove +back into Ross, Holmes still carrying with him the stone which he +had picked up in the wood. + +"This may interest you, Lestrade," he remarked, holding it out. +"The murder was done with it." + +"I see no marks." + +"There are none." + +"How do you know, then?" + +"The grass was growing under it. It had only lain there a few +days. There was no sign of a place whence it had been taken. It +corresponds with the injuries. There is no sign of any other +weapon." + +"And the murderer?" + +"Is a tall man, left-handed, limps with the right leg, wears +thick-soled shooting-boots and a grey cloak, smokes Indian +cigars, uses a cigar-holder, and carries a blunt pen-knife in his +pocket. There are several other indications, but these may be +enough to aid us in our search." + +Lestrade laughed. "I am afraid that I am still a sceptic," he +said. "Theories are all very well, but we have to deal with a +hard-headed British jury." + +"Nous verrons," answered Holmes calmly. "You work your own +method, and I shall work mine. I shall be busy this afternoon, +and shall probably return to London by the evening train." + +"And leave your case unfinished?" + +"No, finished." + +"But the mystery?" + +"It is solved." + +"Who was the criminal, then?" + +"The gentleman I describe." + +"But who is he?" + +"Surely it would not be difficult to find out. This is not such a +populous neighbourhood." + +Lestrade shrugged his shoulders. "I am a practical man," he said, +"and I really cannot undertake to go about the country looking +for a left-handed gentleman with a game leg. I should become the +laughing-stock of Scotland Yard." + +"All right," said Holmes quietly. "I have given you the chance. +Here are your lodgings. Good-bye. I shall drop you a line before +I leave." + +Having left Lestrade at his rooms, we drove to our hotel, where +we found lunch upon the table. Holmes was silent and buried in +thought with a pained expression upon his face, as one who finds +himself in a perplexing position. + +"Look here, Watson," he said when the cloth was cleared "just sit +down in this chair and let me preach to you for a little. I don't +know quite what to do, and I should value your advice. Light a +cigar and let me expound." + + "Pray do so." + +"Well, now, in considering this case there are two points about +young McCarthy's narrative which struck us both instantly, +although they impressed me in his favour and you against him. One +was the fact that his father should, according to his account, +cry 'Cooee!' before seeing him. The other was his singular dying +reference to a rat. He mumbled several words, you understand, but +that was all that caught the son's ear. Now from this double +point our research must commence, and we will begin it by +presuming that what the lad says is absolutely true." + +"What of this 'Cooee!' then?" + +"Well, obviously it could not have been meant for the son. The +son, as far as he knew, was in Bristol. It was mere chance that +he was within earshot. The 'Cooee!' was meant to attract the +attention of whoever it was that he had the appointment with. But +'Cooee' is a distinctly Australian cry, and one which is used +between Australians. There is a strong presumption that the +person whom McCarthy expected to meet him at Boscombe Pool was +someone who had been in Australia." + +"What of the rat, then?" + +Sherlock Holmes took a folded paper from his pocket and flattened +it out on the table. "This is a map of the Colony of Victoria," +he said. "I wired to Bristol for it last night." He put his hand +over part of the map. "What do you read?" + +"ARAT," I read. + +"And now?" He raised his hand. + +"BALLARAT." + +"Quite so. That was the word the man uttered, and of which his +son only caught the last two syllables. He was trying to utter +the name of his murderer. So and so, of Ballarat." + +"It is wonderful!" I exclaimed. + +"It is obvious. And now, you see, I had narrowed the field down +considerably. The possession of a grey garment was a third point +which, granting the son's statement to be correct, was a +certainty. We have come now out of mere vagueness to the definite +conception of an Australian from Ballarat with a grey cloak." + +"Certainly." + +"And one who was at home in the district, for the pool can only +be approached by the farm or by the estate, where strangers could +hardly wander." + +"Quite so." + +"Then comes our expedition of to-day. By an examination of the +ground I gained the trifling details which I gave to that +imbecile Lestrade, as to the personality of the criminal." + +"But how did you gain them?" + +"You know my method. It is founded upon the observation of +trifles." + +"His height I know that you might roughly judge from the length +of his stride. His boots, too, might be told from their traces." + +"Yes, they were peculiar boots." + +"But his lameness?" + +"The impression of his right foot was always less distinct than +his left. He put less weight upon it. Why? Because he limped--he +was lame." + +"But his left-handedness." + +"You were yourself struck by the nature of the injury as recorded +by the surgeon at the inquest. The blow was struck from +immediately behind, and yet was upon the left side. Now, how can +that be unless it were by a left-handed man? He had stood behind +that tree during the interview between the father and son. He had +even smoked there. I found the ash of a cigar, which my special +knowledge of tobacco ashes enables me to pronounce as an Indian +cigar. I have, as you know, devoted some attention to this, and +written a little monograph on the ashes of 140 different +varieties of pipe, cigar, and cigarette tobacco. Having found the +ash, I then looked round and discovered the stump among the moss +where he had tossed it. It was an Indian cigar, of the variety +which are rolled in Rotterdam." + +"And the cigar-holder?" + +"I could see that the end had not been in his mouth. Therefore he +used a holder. The tip had been cut off, not bitten off, but the +cut was not a clean one, so I deduced a blunt pen-knife." + +"Holmes," I said, "you have drawn a net round this man from which +he cannot escape, and you have saved an innocent human life as +truly as if you had cut the cord which was hanging him. I see the +direction in which all this points. The culprit is--" + +"Mr. John Turner," cried the hotel waiter, opening the door of +our sitting-room, and ushering in a visitor. + +The man who entered was a strange and impressive figure. His +slow, limping step and bowed shoulders gave the appearance of +decrepitude, and yet his hard, deep-lined, craggy features, and +his enormous limbs showed that he was possessed of unusual +strength of body and of character. His tangled beard, grizzled +hair, and outstanding, drooping eyebrows combined to give an air +of dignity and power to his appearance, but his face was of an +ashen white, while his lips and the corners of his nostrils were +tinged with a shade of blue. It was clear to me at a glance that +he was in the grip of some deadly and chronic disease. + +"Pray sit down on the sofa," said Holmes gently. "You had my +note?" + +"Yes, the lodge-keeper brought it up. You said that you wished to +see me here to avoid scandal." + +"I thought people would talk if I went to the Hall." + +"And why did you wish to see me?" He looked across at my +companion with despair in his weary eyes, as though his question +was already answered. + +"Yes," said Holmes, answering the look rather than the words. "It +is so. I know all about McCarthy." + +The old man sank his face in his hands. "God help me!" he cried. +"But I would not have let the young man come to harm. I give you +my word that I would have spoken out if it went against him at +the Assizes." + +"I am glad to hear you say so," said Holmes gravely. + +"I would have spoken now had it not been for my dear girl. It +would break her heart--it will break her heart when she hears +that I am arrested." + +"It may not come to that," said Holmes. + +"What?" + +"I am no official agent. I understand that it was your daughter +who required my presence here, and I am acting in her interests. +Young McCarthy must be got off, however." + +"I am a dying man," said old Turner. "I have had diabetes for +years. My doctor says it is a question whether I shall live a +month. Yet I would rather die under my own roof than in a gaol." + +Holmes rose and sat down at the table with his pen in his hand +and a bundle of paper before him. "Just tell us the truth," he +said. "I shall jot down the facts. You will sign it, and Watson +here can witness it. Then I could produce your confession at the +last extremity to save young McCarthy. I promise you that I shall +not use it unless it is absolutely needed." + +"It's as well," said the old man; "it's a question whether I +shall live to the Assizes, so it matters little to me, but I +should wish to spare Alice the shock. And now I will make the +thing clear to you; it has been a long time in the acting, but +will not take me long to tell. + +"You didn't know this dead man, McCarthy. He was a devil +incarnate. I tell you that. God keep you out of the clutches of +such a man as he. His grip has been upon me these twenty years, +and he has blasted my life. I'll tell you first how I came to be +in his power. + +"It was in the early '60's at the diggings. I was a young chap +then, hot-blooded and reckless, ready to turn my hand at +anything; I got among bad companions, took to drink, had no luck +with my claim, took to the bush, and in a word became what you +would call over here a highway robber. There were six of us, and +we had a wild, free life of it, sticking up a station from time +to time, or stopping the wagons on the road to the diggings. +Black Jack of Ballarat was the name I went under, and our party +is still remembered in the colony as the Ballarat Gang. + +"One day a gold convoy came down from Ballarat to Melbourne, and +we lay in wait for it and attacked it. There were six troopers +and six of us, so it was a close thing, but we emptied four of +their saddles at the first volley. Three of our boys were killed, +however, before we got the swag. I put my pistol to the head of +the wagon-driver, who was this very man McCarthy. I wish to the +Lord that I had shot him then, but I spared him, though I saw his +wicked little eyes fixed on my face, as though to remember every +feature. We got away with the gold, became wealthy men, and made +our way over to England without being suspected. There I parted +from my old pals and determined to settle down to a quiet and +respectable life. I bought this estate, which chanced to be in +the market, and I set myself to do a little good with my money, +to make up for the way in which I had earned it. I married, too, +and though my wife died young she left me my dear little Alice. +Even when she was just a baby her wee hand seemed to lead me down +the right path as nothing else had ever done. In a word, I turned +over a new leaf and did my best to make up for the past. All was +going well when McCarthy laid his grip upon me. + +"I had gone up to town about an investment, and I met him in +Regent Street with hardly a coat to his back or a boot to his +foot. + +"'Here we are, Jack,' says he, touching me on the arm; 'we'll be +as good as a family to you. There's two of us, me and my son, and +you can have the keeping of us. If you don't--it's a fine, +law-abiding country is England, and there's always a policeman +within hail.' + +"Well, down they came to the west country, there was no shaking +them off, and there they have lived rent free on my best land +ever since. There was no rest for me, no peace, no forgetfulness; +turn where I would, there was his cunning, grinning face at my +elbow. It grew worse as Alice grew up, for he soon saw I was more +afraid of her knowing my past than of the police. Whatever he +wanted he must have, and whatever it was I gave him without +question, land, money, houses, until at last he asked a thing +which I could not give. He asked for Alice. + +"His son, you see, had grown up, and so had my girl, and as I was +known to be in weak health, it seemed a fine stroke to him that +his lad should step into the whole property. But there I was +firm. I would not have his cursed stock mixed with mine; not that +I had any dislike to the lad, but his blood was in him, and that +was enough. I stood firm. McCarthy threatened. I braved him to do +his worst. We were to meet at the pool midway between our houses +to talk it over. + +"When I went down there I found him talking with his son, so I +smoked a cigar and waited behind a tree until he should be alone. +But as I listened to his talk all that was black and bitter in +me seemed to come uppermost. He was urging his son to marry my +daughter with as little regard for what she might think as if she +were a slut from off the streets. It drove me mad to think that I +and all that I held most dear should be in the power of such a +man as this. Could I not snap the bond? I was already a dying and +a desperate man. Though clear of mind and fairly strong of limb, +I knew that my own fate was sealed. But my memory and my girl! +Both could be saved if I could but silence that foul tongue. I +did it, Mr. Holmes. I would do it again. Deeply as I have sinned, +I have led a life of martyrdom to atone for it. But that my girl +should be entangled in the same meshes which held me was more +than I could suffer. I struck him down with no more compunction +than if he had been some foul and venomous beast. His cry brought +back his son; but I had gained the cover of the wood, though I +was forced to go back to fetch the cloak which I had dropped in +my flight. That is the true story, gentlemen, of all that +occurred." + +"Well, it is not for me to judge you," said Holmes as the old man +signed the statement which had been drawn out. "I pray that we +may never be exposed to such a temptation." + +"I pray not, sir. And what do you intend to do?" + +"In view of your health, nothing. You are yourself aware that you +will soon have to answer for your deed at a higher court than the +Assizes. I will keep your confession, and if McCarthy is +condemned I shall be forced to use it. If not, it shall never be +seen by mortal eye; and your secret, whether you be alive or +dead, shall be safe with us." + +"Farewell, then," said the old man solemnly. "Your own deathbeds, +when they come, will be the easier for the thought of the peace +which you have given to mine." Tottering and shaking in all his +giant frame, he stumbled slowly from the room. + +"God help us!" said Holmes after a long silence. "Why does fate +play such tricks with poor, helpless worms? I never hear of such +a case as this that I do not think of Baxter's words, and say, +'There, but for the grace of God, goes Sherlock Holmes.'" + +James McCarthy was acquitted at the Assizes on the strength of a +number of objections which had been drawn out by Holmes and +submitted to the defending counsel. Old Turner lived for seven +months after our interview, but he is now dead; and there is +every prospect that the son and daughter may come to live happily +together in ignorance of the black cloud which rests upon their +past. + + + +ADVENTURE V. THE FIVE ORANGE PIPS + +When I glance over my notes and records of the Sherlock Holmes +cases between the years '82 and '90, I am faced by so many which +present strange and interesting features that it is no easy +matter to know which to choose and which to leave. Some, however, +have already gained publicity through the papers, and others have +not offered a field for those peculiar qualities which my friend +possessed in so high a degree, and which it is the object of +these papers to illustrate. Some, too, have baffled his +analytical skill, and would be, as narratives, beginnings without +an ending, while others have been but partially cleared up, and +have their explanations founded rather upon conjecture and +surmise than on that absolute logical proof which was so dear to +him. There is, however, one of these last which was so remarkable +in its details and so startling in its results that I am tempted +to give some account of it in spite of the fact that there are +points in connection with it which never have been, and probably +never will be, entirely cleared up. + +The year '87 furnished us with a long series of cases of greater +or less interest, of which I retain the records. Among my +headings under this one twelve months I find an account of the +adventure of the Paradol Chamber, of the Amateur Mendicant +Society, who held a luxurious club in the lower vault of a +furniture warehouse, of the facts connected with the loss of the +British barque "Sophy Anderson", of the singular adventures of the +Grice Patersons in the island of Uffa, and finally of the +Camberwell poisoning case. In the latter, as may be remembered, +Sherlock Holmes was able, by winding up the dead man's watch, to +prove that it had been wound up two hours before, and that +therefore the deceased had gone to bed within that time--a +deduction which was of the greatest importance in clearing up the +case. All these I may sketch out at some future date, but none of +them present such singular features as the strange train of +circumstances which I have now taken up my pen to describe. + +It was in the latter days of September, and the equinoctial gales +had set in with exceptional violence. All day the wind had +screamed and the rain had beaten against the windows, so that +even here in the heart of great, hand-made London we were forced +to raise our minds for the instant from the routine of life and +to recognise the presence of those great elemental forces which +shriek at mankind through the bars of his civilisation, like +untamed beasts in a cage. As evening drew in, the storm grew +higher and louder, and the wind cried and sobbed like a child in +the chimney. Sherlock Holmes sat moodily at one side of the +fireplace cross-indexing his records of crime, while I at the +other was deep in one of Clark Russell's fine sea-stories until +the howl of the gale from without seemed to blend with the text, +and the splash of the rain to lengthen out into the long swash of +the sea waves. My wife was on a visit to her mother's, and for a +few days I was a dweller once more in my old quarters at Baker +Street. + +"Why," said I, glancing up at my companion, "that was surely the +bell. Who could come to-night? Some friend of yours, perhaps?" + +"Except yourself I have none," he answered. "I do not encourage +visitors." + +"A client, then?" + +"If so, it is a serious case. Nothing less would bring a man out +on such a day and at such an hour. But I take it that it is more +likely to be some crony of the landlady's." + +Sherlock Holmes was wrong in his conjecture, however, for there +came a step in the passage and a tapping at the door. He +stretched out his long arm to turn the lamp away from himself and +towards the vacant chair upon which a newcomer must sit. + +"Come in!" said he. + +The man who entered was young, some two-and-twenty at the +outside, well-groomed and trimly clad, with something of +refinement and delicacy in his bearing. The streaming umbrella +which he held in his hand, and his long shining waterproof told +of the fierce weather through which he had come. He looked about +him anxiously in the glare of the lamp, and I could see that his +face was pale and his eyes heavy, like those of a man who is +weighed down with some great anxiety. + +"I owe you an apology," he said, raising his golden pince-nez to +his eyes. "I trust that I am not intruding. I fear that I have +brought some traces of the storm and rain into your snug +chamber." + +"Give me your coat and umbrella," said Holmes. "They may rest +here on the hook and will be dry presently. You have come up from +the south-west, I see." + +"Yes, from Horsham." + +"That clay and chalk mixture which I see upon your toe caps is +quite distinctive." + +"I have come for advice." + +"That is easily got." + +"And help." + +"That is not always so easy." + +"I have heard of you, Mr. Holmes. I heard from Major Prendergast +how you saved him in the Tankerville Club scandal." + +"Ah, of course. He was wrongfully accused of cheating at cards." + +"He said that you could solve anything." + +"He said too much." + +"That you are never beaten." + +"I have been beaten four times--three times by men, and once by a +woman." + +"But what is that compared with the number of your successes?" + +"It is true that I have been generally successful." + +"Then you may be so with me." + +"I beg that you will draw your chair up to the fire and favour me +with some details as to your case." + +"It is no ordinary one." + +"None of those which come to me are. I am the last court of +appeal." + +"And yet I question, sir, whether, in all your experience, you +have ever listened to a more mysterious and inexplicable chain of +events than those which have happened in my own family." + +"You fill me with interest," said Holmes. "Pray give us the +essential facts from the commencement, and I can afterwards +question you as to those details which seem to me to be most +important." + +The young man pulled his chair up and pushed his wet feet out +towards the blaze. + +"My name," said he, "is John Openshaw, but my own affairs have, +as far as I can understand, little to do with this awful +business. It is a hereditary matter; so in order to give you an +idea of the facts, I must go back to the commencement of the +affair. + +"You must know that my grandfather had two sons--my uncle Elias +and my father Joseph. My father had a small factory at Coventry, +which he enlarged at the time of the invention of bicycling. He +was a patentee of the Openshaw unbreakable tire, and his business +met with such success that he was able to sell it and to retire +upon a handsome competence. + +"My uncle Elias emigrated to America when he was a young man and +became a planter in Florida, where he was reported to have done +very well. At the time of the war he fought in Jackson's army, +and afterwards under Hood, where he rose to be a colonel. When +Lee laid down his arms my uncle returned to his plantation, where +he remained for three or four years. About 1869 or 1870 he came +back to Europe and took a small estate in Sussex, near Horsham. +He had made a very considerable fortune in the States, and his +reason for leaving them was his aversion to the negroes, and his +dislike of the Republican policy in extending the franchise to +them. He was a singular man, fierce and quick-tempered, very +foul-mouthed when he was angry, and of a most retiring +disposition. During all the years that he lived at Horsham, I +doubt if ever he set foot in the town. He had a garden and two or +three fields round his house, and there he would take his +exercise, though very often for weeks on end he would never leave +his room. He drank a great deal of brandy and smoked very +heavily, but he would see no society and did not want any +friends, not even his own brother. + +"He didn't mind me; in fact, he took a fancy to me, for at the +time when he saw me first I was a youngster of twelve or so. This +would be in the year 1878, after he had been eight or nine years +in England. He begged my father to let me live with him and he +was very kind to me in his way. When he was sober he used to be +fond of playing backgammon and draughts with me, and he would +make me his representative both with the servants and with the +tradespeople, so that by the time that I was sixteen I was quite +master of the house. I kept all the keys and could go where I +liked and do what I liked, so long as I did not disturb him in +his privacy. There was one singular exception, however, for he +had a single room, a lumber-room up among the attics, which was +invariably locked, and which he would never permit either me or +anyone else to enter. With a boy's curiosity I have peeped +through the keyhole, but I was never able to see more than such a +collection of old trunks and bundles as would be expected in such +a room. + +"One day--it was in March, 1883--a letter with a foreign stamp +lay upon the table in front of the colonel's plate. It was not a +common thing for him to receive letters, for his bills were all +paid in ready money, and he had no friends of any sort. 'From +India!' said he as he took it up, 'Pondicherry postmark! What can +this be?' Opening it hurriedly, out there jumped five little +dried orange pips, which pattered down upon his plate. I began to +laugh at this, but the laugh was struck from my lips at the sight +of his face. His lip had fallen, his eyes were protruding, his +skin the colour of putty, and he glared at the envelope which he +still held in his trembling hand, 'K. K. K.!' he shrieked, and +then, 'My God, my God, my sins have overtaken me!' + +"'What is it, uncle?' I cried. + +"'Death,' said he, and rising from the table he retired to his +room, leaving me palpitating with horror. I took up the envelope +and saw scrawled in red ink upon the inner flap, just above the +gum, the letter K three times repeated. There was nothing else +save the five dried pips. What could be the reason of his +overpowering terror? I left the breakfast-table, and as I +ascended the stair I met him coming down with an old rusty key, +which must have belonged to the attic, in one hand, and a small +brass box, like a cashbox, in the other. + +"'They may do what they like, but I'll checkmate them still,' +said he with an oath. 'Tell Mary that I shall want a fire in my +room to-day, and send down to Fordham, the Horsham lawyer.' + +"I did as he ordered, and when the lawyer arrived I was asked to +step up to the room. The fire was burning brightly, and in the +grate there was a mass of black, fluffy ashes, as of burned +paper, while the brass box stood open and empty beside it. As I +glanced at the box I noticed, with a start, that upon the lid was +printed the treble K which I had read in the morning upon the +envelope. + +"'I wish you, John,' said my uncle, 'to witness my will. I leave +my estate, with all its advantages and all its disadvantages, to +my brother, your father, whence it will, no doubt, descend to +you. If you can enjoy it in peace, well and good! If you find you +cannot, take my advice, my boy, and leave it to your deadliest +enemy. I am sorry to give you such a two-edged thing, but I can't +say what turn things are going to take. Kindly sign the paper +where Mr. Fordham shows you.' + +"I signed the paper as directed, and the lawyer took it away with +him. The singular incident made, as you may think, the deepest +impression upon me, and I pondered over it and turned it every +way in my mind without being able to make anything of it. Yet I +could not shake off the vague feeling of dread which it left +behind, though the sensation grew less keen as the weeks passed +and nothing happened to disturb the usual routine of our lives. I +could see a change in my uncle, however. He drank more than ever, +and he was less inclined for any sort of society. Most of his +time he would spend in his room, with the door locked upon the +inside, but sometimes he would emerge in a sort of drunken frenzy +and would burst out of the house and tear about the garden with a +revolver in his hand, screaming out that he was afraid of no man, +and that he was not to be cooped up, like a sheep in a pen, by +man or devil. When these hot fits were over, however, he would +rush tumultuously in at the door and lock and bar it behind him, +like a man who can brazen it out no longer against the terror +which lies at the roots of his soul. At such times I have seen +his face, even on a cold day, glisten with moisture, as though it +were new raised from a basin. + +"Well, to come to an end of the matter, Mr. Holmes, and not to +abuse your patience, there came a night when he made one of those +drunken sallies from which he never came back. We found him, when +we went to search for him, face downward in a little +green-scummed pool, which lay at the foot of the garden. There +was no sign of any violence, and the water was but two feet deep, +so that the jury, having regard to his known eccentricity, +brought in a verdict of 'suicide.' But I, who knew how he winced +from the very thought of death, had much ado to persuade myself +that he had gone out of his way to meet it. The matter passed, +however, and my father entered into possession of the estate, and +of some 14,000 pounds, which lay to his credit at the bank." + +"One moment," Holmes interposed, "your statement is, I foresee, +one of the most remarkable to which I have ever listened. Let me +have the date of the reception by your uncle of the letter, and +the date of his supposed suicide." + +"The letter arrived on March 10, 1883. His death was seven weeks +later, upon the night of May 2nd." + +"Thank you. Pray proceed." + +"When my father took over the Horsham property, he, at my +request, made a careful examination of the attic, which had been +always locked up. We found the brass box there, although its +contents had been destroyed. On the inside of the cover was a +paper label, with the initials of K. K. K. repeated upon it, and +'Letters, memoranda, receipts, and a register' written beneath. +These, we presume, indicated the nature of the papers which had +been destroyed by Colonel Openshaw. For the rest, there was +nothing of much importance in the attic save a great many +scattered papers and note-books bearing upon my uncle's life in +America. Some of them were of the war time and showed that he had +done his duty well and had borne the repute of a brave soldier. +Others were of a date during the reconstruction of the Southern +states, and were mostly concerned with politics, for he had +evidently taken a strong part in opposing the carpet-bag +politicians who had been sent down from the North. + +"Well, it was the beginning of '84 when my father came to live at +Horsham, and all went as well as possible with us until the +January of '85. On the fourth day after the new year I heard my +father give a sharp cry of surprise as we sat together at the +breakfast-table. There he was, sitting with a newly opened +envelope in one hand and five dried orange pips in the +outstretched palm of the other one. He had always laughed at what +he called my cock-and-bull story about the colonel, but he looked +very scared and puzzled now that the same thing had come upon +himself. + +"'Why, what on earth does this mean, John?' he stammered. + +"My heart had turned to lead. 'It is K. K. K.,' said I. + +"He looked inside the envelope. 'So it is,' he cried. 'Here are +the very letters. But what is this written above them?' + +"'Put the papers on the sundial,' I read, peeping over his +shoulder. + +"'What papers? What sundial?' he asked. + +"'The sundial in the garden. There is no other,' said I; 'but the +papers must be those that are destroyed.' + +"'Pooh!' said he, gripping hard at his courage. 'We are in a +civilised land here, and we can't have tomfoolery of this kind. +Where does the thing come from?' + +"'From Dundee,' I answered, glancing at the postmark. + +"'Some preposterous practical joke,' said he. 'What have I to do +with sundials and papers? I shall take no notice of such +nonsense.' + +"'I should certainly speak to the police,' I said. + +"'And be laughed at for my pains. Nothing of the sort.' + +"'Then let me do so?' + +"'No, I forbid you. I won't have a fuss made about such +nonsense.' + +"It was in vain to argue with him, for he was a very obstinate +man. I went about, however, with a heart which was full of +forebodings. + +"On the third day after the coming of the letter my father went +from home to visit an old friend of his, Major Freebody, who is +in command of one of the forts upon Portsdown Hill. I was glad +that he should go, for it seemed to me that he was farther from +danger when he was away from home. In that, however, I was in +error. Upon the second day of his absence I received a telegram +from the major, imploring me to come at once. My father had +fallen over one of the deep chalk-pits which abound in the +neighbourhood, and was lying senseless, with a shattered skull. I +hurried to him, but he passed away without having ever recovered +his consciousness. He had, as it appears, been returning from +Fareham in the twilight, and as the country was unknown to him, +and the chalk-pit unfenced, the jury had no hesitation in +bringing in a verdict of 'death from accidental causes.' +Carefully as I examined every fact connected with his death, I +was unable to find anything which could suggest the idea of +murder. There were no signs of violence, no footmarks, no +robbery, no record of strangers having been seen upon the roads. +And yet I need not tell you that my mind was far from at ease, +and that I was well-nigh certain that some foul plot had been +woven round him. + +"In this sinister way I came into my inheritance. You will ask me +why I did not dispose of it? I answer, because I was well +convinced that our troubles were in some way dependent upon an +incident in my uncle's life, and that the danger would be as +pressing in one house as in another. + +"It was in January, '85, that my poor father met his end, and two +years and eight months have elapsed since then. During that time +I have lived happily at Horsham, and I had begun to hope that +this curse had passed away from the family, and that it had ended +with the last generation. I had begun to take comfort too soon, +however; yesterday morning the blow fell in the very shape in +which it had come upon my father." + +The young man took from his waistcoat a crumpled envelope, and +turning to the table he shook out upon it five little dried +orange pips. + +"This is the envelope," he continued. "The postmark is +London--eastern division. Within are the very words which were +upon my father's last message: 'K. K. K.'; and then 'Put the +papers on the sundial.'" + +"What have you done?" asked Holmes. + +"Nothing." + +"Nothing?" + +"To tell the truth"--he sank his face into his thin, white +hands--"I have felt helpless. I have felt like one of those poor +rabbits when the snake is writhing towards it. I seem to be in +the grasp of some resistless, inexorable evil, which no foresight +and no precautions can guard against." + +"Tut! tut!" cried Sherlock Holmes. "You must act, man, or you are +lost. Nothing but energy can save you. This is no time for +despair." + +"I have seen the police." + +"Ah!" + +"But they listened to my story with a smile. I am convinced that +the inspector has formed the opinion that the letters are all +practical jokes, and that the deaths of my relations were really +accidents, as the jury stated, and were not to be connected with +the warnings." + +Holmes shook his clenched hands in the air. "Incredible +imbecility!" he cried. + +"They have, however, allowed me a policeman, who may remain in +the house with me." + +"Has he come with you to-night?" + +"No. His orders were to stay in the house." + +Again Holmes raved in the air. + +"Why did you come to me," he cried, "and, above all, why did you +not come at once?" + +"I did not know. It was only to-day that I spoke to Major +Prendergast about my troubles and was advised by him to come to +you." + +"It is really two days since you had the letter. We should have +acted before this. You have no further evidence, I suppose, than +that which you have placed before us--no suggestive detail which +might help us?" + +"There is one thing," said John Openshaw. He rummaged in his coat +pocket, and, drawing out a piece of discoloured, blue-tinted +paper, he laid it out upon the table. "I have some remembrance," +said he, "that on the day when my uncle burned the papers I +observed that the small, unburned margins which lay amid the +ashes were of this particular colour. I found this single sheet +upon the floor of his room, and I am inclined to think that it +may be one of the papers which has, perhaps, fluttered out from +among the others, and in that way has escaped destruction. Beyond +the mention of pips, I do not see that it helps us much. I think +myself that it is a page from some private diary. The writing is +undoubtedly my uncle's." + +Holmes moved the lamp, and we both bent over the sheet of paper, +which showed by its ragged edge that it had indeed been torn from +a book. It was headed, "March, 1869," and beneath were the +following enigmatical notices: + +"4th. Hudson came. Same old platform. + +"7th. Set the pips on McCauley, Paramore, and + John Swain, of St. Augustine. + +"9th. McCauley cleared. + +"10th. John Swain cleared. + +"12th. Visited Paramore. All well." + +"Thank you!" said Holmes, folding up the paper and returning it +to our visitor. "And now you must on no account lose another +instant. We cannot spare time even to discuss what you have told +me. You must get home instantly and act." + +"What shall I do?" + +"There is but one thing to do. It must be done at once. You must +put this piece of paper which you have shown us into the brass +box which you have described. You must also put in a note to say +that all the other papers were burned by your uncle, and that +this is the only one which remains. You must assert that in such +words as will carry conviction with them. Having done this, you +must at once put the box out upon the sundial, as directed. Do +you understand?" + +"Entirely." + +"Do not think of revenge, or anything of the sort, at present. I +think that we may gain that by means of the law; but we have our +web to weave, while theirs is already woven. The first +consideration is to remove the pressing danger which threatens +you. The second is to clear up the mystery and to punish the +guilty parties." + +"I thank you," said the young man, rising and pulling on his +overcoat. "You have given me fresh life and hope. I shall +certainly do as you advise." + +"Do not lose an instant. And, above all, take care of yourself in +the meanwhile, for I do not think that there can be a doubt that +you are threatened by a very real and imminent danger. How do you +go back?" + +"By train from Waterloo." + +"It is not yet nine. The streets will be crowded, so I trust that +you may be in safety. And yet you cannot guard yourself too +closely." + +"I am armed." + +"That is well. To-morrow I shall set to work upon your case." + +"I shall see you at Horsham, then?" + +"No, your secret lies in London. It is there that I shall seek +it." + +"Then I shall call upon you in a day, or in two days, with news +as to the box and the papers. I shall take your advice in every +particular." He shook hands with us and took his leave. Outside +the wind still screamed and the rain splashed and pattered +against the windows. This strange, wild story seemed to have come +to us from amid the mad elements--blown in upon us like a sheet +of sea-weed in a gale--and now to have been reabsorbed by them +once more. + +Sherlock Holmes sat for some time in silence, with his head sunk +forward and his eyes bent upon the red glow of the fire. Then he +lit his pipe, and leaning back in his chair he watched the blue +smoke-rings as they chased each other up to the ceiling. + +"I think, Watson," he remarked at last, "that of all our cases we +have had none more fantastic than this." + +"Save, perhaps, the Sign of Four." + +"Well, yes. Save, perhaps, that. And yet this John Openshaw seems +to me to be walking amid even greater perils than did the +Sholtos." + +"But have you," I asked, "formed any definite conception as to +what these perils are?" + +"There can be no question as to their nature," he answered. + +"Then what are they? Who is this K. K. K., and why does he pursue +this unhappy family?" + +Sherlock Holmes closed his eyes and placed his elbows upon the +arms of his chair, with his finger-tips together. "The ideal +reasoner," he remarked, "would, when he had once been shown a +single fact in all its bearings, deduce from it not only all the +chain of events which led up to it but also all the results which +would follow from it. As Cuvier could correctly describe a whole +animal by the contemplation of a single bone, so the observer who +has thoroughly understood one link in a series of incidents +should be able to accurately state all the other ones, both +before and after. We have not yet grasped the results which the +reason alone can attain to. Problems may be solved in the study +which have baffled all those who have sought a solution by the +aid of their senses. To carry the art, however, to its highest +pitch, it is necessary that the reasoner should be able to +utilise all the facts which have come to his knowledge; and this +in itself implies, as you will readily see, a possession of all +knowledge, which, even in these days of free education and +encyclopaedias, is a somewhat rare accomplishment. It is not so +impossible, however, that a man should possess all knowledge +which is likely to be useful to him in his work, and this I have +endeavoured in my case to do. If I remember rightly, you on one +occasion, in the early days of our friendship, defined my limits +in a very precise fashion." + +"Yes," I answered, laughing. "It was a singular document. +Philosophy, astronomy, and politics were marked at zero, I +remember. Botany variable, geology profound as regards the +mud-stains from any region within fifty miles of town, chemistry +eccentric, anatomy unsystematic, sensational literature and crime +records unique, violin-player, boxer, swordsman, lawyer, and +self-poisoner by cocaine and tobacco. Those, I think, were the +main points of my analysis." + +Holmes grinned at the last item. "Well," he said, "I say now, as +I said then, that a man should keep his little brain-attic +stocked with all the furniture that he is likely to use, and the +rest he can put away in the lumber-room of his library, where he +can get it if he wants it. Now, for such a case as the one which +has been submitted to us to-night, we need certainly to muster +all our resources. Kindly hand me down the letter K of the +'American Encyclopaedia' which stands upon the shelf beside you. +Thank you. Now let us consider the situation and see what may be +deduced from it. In the first place, we may start with a strong +presumption that Colonel Openshaw had some very strong reason for +leaving America. Men at his time of life do not change all their +habits and exchange willingly the charming climate of Florida for +the lonely life of an English provincial town. His extreme love +of solitude in England suggests the idea that he was in fear of +someone or something, so we may assume as a working hypothesis +that it was fear of someone or something which drove him from +America. As to what it was he feared, we can only deduce that by +considering the formidable letters which were received by himself +and his successors. Did you remark the postmarks of those +letters?" + +"The first was from Pondicherry, the second from Dundee, and the +third from London." + +"From East London. What do you deduce from that?" + +"They are all seaports. That the writer was on board of a ship." + +"Excellent. We have already a clue. There can be no doubt that +the probability--the strong probability--is that the writer was +on board of a ship. And now let us consider another point. In the +case of Pondicherry, seven weeks elapsed between the threat and +its fulfilment, in Dundee it was only some three or four days. +Does that suggest anything?" + +"A greater distance to travel." + +"But the letter had also a greater distance to come." + +"Then I do not see the point." + +"There is at least a presumption that the vessel in which the man +or men are is a sailing-ship. It looks as if they always send +their singular warning or token before them when starting upon +their mission. You see how quickly the deed followed the sign +when it came from Dundee. If they had come from Pondicherry in a +steamer they would have arrived almost as soon as their letter. +But, as a matter of fact, seven weeks elapsed. I think that those +seven weeks represented the difference between the mail-boat which +brought the letter and the sailing vessel which brought the +writer." + +"It is possible." + +"More than that. It is probable. And now you see the deadly +urgency of this new case, and why I urged young Openshaw to +caution. The blow has always fallen at the end of the time which +it would take the senders to travel the distance. But this one +comes from London, and therefore we cannot count upon delay." + +"Good God!" I cried. "What can it mean, this relentless +persecution?" + +"The papers which Openshaw carried are obviously of vital +importance to the person or persons in the sailing-ship. I think +that it is quite clear that there must be more than one of them. +A single man could not have carried out two deaths in such a way +as to deceive a coroner's jury. There must have been several in +it, and they must have been men of resource and determination. +Their papers they mean to have, be the holder of them who it may. +In this way you see K. K. K. ceases to be the initials of an +individual and becomes the badge of a society." + +"But of what society?" + +"Have you never--" said Sherlock Holmes, bending forward and +sinking his voice--"have you never heard of the Ku Klux Klan?" + +"I never have." + +Holmes turned over the leaves of the book upon his knee. "Here it +is," said he presently: + +"'Ku Klux Klan. A name derived from the fanciful resemblance to +the sound produced by cocking a rifle. This terrible secret +society was formed by some ex-Confederate soldiers in the +Southern states after the Civil War, and it rapidly formed local +branches in different parts of the country, notably in Tennessee, +Louisiana, the Carolinas, Georgia, and Florida. Its power was +used for political purposes, principally for the terrorising of +the negro voters and the murdering and driving from the country +of those who were opposed to its views. Its outrages were usually +preceded by a warning sent to the marked man in some fantastic +but generally recognised shape--a sprig of oak-leaves in some +parts, melon seeds or orange pips in others. On receiving this +the victim might either openly abjure his former ways, or might +fly from the country. If he braved the matter out, death would +unfailingly come upon him, and usually in some strange and +unforeseen manner. So perfect was the organisation of the +society, and so systematic its methods, that there is hardly a +case upon record where any man succeeded in braving it with +impunity, or in which any of its outrages were traced home to the +perpetrators. For some years the organisation flourished in spite +of the efforts of the United States government and of the better +classes of the community in the South. Eventually, in the year +1869, the movement rather suddenly collapsed, although there have +been sporadic outbreaks of the same sort since that date.' + +"You will observe," said Holmes, laying down the volume, "that +the sudden breaking up of the society was coincident with the +disappearance of Openshaw from America with their papers. It may +well have been cause and effect. It is no wonder that he and his +family have some of the more implacable spirits upon their track. +You can understand that this register and diary may implicate +some of the first men in the South, and that there may be many +who will not sleep easy at night until it is recovered." + +"Then the page we have seen--" + +"Is such as we might expect. It ran, if I remember right, 'sent +the pips to A, B, and C'--that is, sent the society's warning to +them. Then there are successive entries that A and B cleared, or +left the country, and finally that C was visited, with, I fear, a +sinister result for C. Well, I think, Doctor, that we may let +some light into this dark place, and I believe that the only +chance young Openshaw has in the meantime is to do what I have +told him. There is nothing more to be said or to be done +to-night, so hand me over my violin and let us try to forget for +half an hour the miserable weather and the still more miserable +ways of our fellow-men." + + +It had cleared in the morning, and the sun was shining with a +subdued brightness through the dim veil which hangs over the +great city. Sherlock Holmes was already at breakfast when I came +down. + +"You will excuse me for not waiting for you," said he; "I have, I +foresee, a very busy day before me in looking into this case of +young Openshaw's." + +"What steps will you take?" I asked. + +"It will very much depend upon the results of my first inquiries. +I may have to go down to Horsham, after all." + +"You will not go there first?" + +"No, I shall commence with the City. Just ring the bell and the +maid will bring up your coffee." + +As I waited, I lifted the unopened newspaper from the table and +glanced my eye over it. It rested upon a heading which sent a +chill to my heart. + +"Holmes," I cried, "you are too late." + +"Ah!" said he, laying down his cup, "I feared as much. How was it +done?" He spoke calmly, but I could see that he was deeply moved. + +"My eye caught the name of Openshaw, and the heading 'Tragedy +Near Waterloo Bridge.' Here is the account: + +"Between nine and ten last night Police-Constable Cook, of the H +Division, on duty near Waterloo Bridge, heard a cry for help and +a splash in the water. The night, however, was extremely dark and +stormy, so that, in spite of the help of several passers-by, it +was quite impossible to effect a rescue. The alarm, however, was +given, and, by the aid of the water-police, the body was +eventually recovered. It proved to be that of a young gentleman +whose name, as it appears from an envelope which was found in his +pocket, was John Openshaw, and whose residence is near Horsham. +It is conjectured that he may have been hurrying down to catch +the last train from Waterloo Station, and that in his haste and +the extreme darkness he missed his path and walked over the edge +of one of the small landing-places for river steamboats. The body +exhibited no traces of violence, and there can be no doubt that +the deceased had been the victim of an unfortunate accident, +which should have the effect of calling the attention of the +authorities to the condition of the riverside landing-stages." + +We sat in silence for some minutes, Holmes more depressed and +shaken than I had ever seen him. + +"That hurts my pride, Watson," he said at last. "It is a petty +feeling, no doubt, but it hurts my pride. It becomes a personal +matter with me now, and, if God sends me health, I shall set my +hand upon this gang. That he should come to me for help, and that +I should send him away to his death--!" He sprang from his chair +and paced about the room in uncontrollable agitation, with a +flush upon his sallow cheeks and a nervous clasping and +unclasping of his long thin hands. + +"They must be cunning devils," he exclaimed at last. "How could +they have decoyed him down there? The Embankment is not on the +direct line to the station. The bridge, no doubt, was too +crowded, even on such a night, for their purpose. Well, Watson, +we shall see who will win in the long run. I am going out now!" + +"To the police?" + +"No; I shall be my own police. When I have spun the web they may +take the flies, but not before." + +All day I was engaged in my professional work, and it was late in +the evening before I returned to Baker Street. Sherlock Holmes +had not come back yet. It was nearly ten o'clock before he +entered, looking pale and worn. He walked up to the sideboard, +and tearing a piece from the loaf he devoured it voraciously, +washing it down with a long draught of water. + +"You are hungry," I remarked. + +"Starving. It had escaped my memory. I have had nothing since +breakfast." + +"Nothing?" + +"Not a bite. I had no time to think of it." + +"And how have you succeeded?" + +"Well." + +"You have a clue?" + +"I have them in the hollow of my hand. Young Openshaw shall not +long remain unavenged. Why, Watson, let us put their own devilish +trade-mark upon them. It is well thought of!" + +"What do you mean?" + +He took an orange from the cupboard, and tearing it to pieces he +squeezed out the pips upon the table. Of these he took five and +thrust them into an envelope. On the inside of the flap he wrote +"S. H. for J. O." Then he sealed it and addressed it to "Captain +James Calhoun, Barque 'Lone Star,' Savannah, Georgia." + +"That will await him when he enters port," said he, chuckling. +"It may give him a sleepless night. He will find it as sure a +precursor of his fate as Openshaw did before him." + +"And who is this Captain Calhoun?" + +"The leader of the gang. I shall have the others, but he first." + +"How did you trace it, then?" + +He took a large sheet of paper from his pocket, all covered with +dates and names. + +"I have spent the whole day," said he, "over Lloyd's registers +and files of the old papers, following the future career of every +vessel which touched at Pondicherry in January and February in +'83. There were thirty-six ships of fair tonnage which were +reported there during those months. Of these, one, the 'Lone Star,' +instantly attracted my attention, since, although it was reported +as having cleared from London, the name is that which is given to +one of the states of the Union." + +"Texas, I think." + +"I was not and am not sure which; but I knew that the ship must +have an American origin." + +"What then?" + +"I searched the Dundee records, and when I found that the barque +'Lone Star' was there in January, '85, my suspicion became a +certainty. I then inquired as to the vessels which lay at present +in the port of London." + +"Yes?" + +"The 'Lone Star' had arrived here last week. I went down to the +Albert Dock and found that she had been taken down the river by +the early tide this morning, homeward bound to Savannah. I wired +to Gravesend and learned that she had passed some time ago, and +as the wind is easterly I have no doubt that she is now past the +Goodwins and not very far from the Isle of Wight." + +"What will you do, then?" + +"Oh, I have my hand upon him. He and the two mates, are as I +learn, the only native-born Americans in the ship. The others are +Finns and Germans. I know, also, that they were all three away +from the ship last night. I had it from the stevedore who has +been loading their cargo. By the time that their sailing-ship +reaches Savannah the mail-boat will have carried this letter, and +the cable will have informed the police of Savannah that these +three gentlemen are badly wanted here upon a charge of murder." + +There is ever a flaw, however, in the best laid of human plans, +and the murderers of John Openshaw were never to receive the +orange pips which would show them that another, as cunning and as +resolute as themselves, was upon their track. Very long and very +severe were the equinoctial gales that year. We waited long for +news of the "Lone Star" of Savannah, but none ever reached us. We +did at last hear that somewhere far out in the Atlantic a +shattered stern-post of a boat was seen swinging in the trough +of a wave, with the letters "L. S." carved upon it, and that is +all which we shall ever know of the fate of the "Lone Star." + + + +ADVENTURE VI. THE MAN WITH THE TWISTED LIP + +Isa Whitney, brother of the late Elias Whitney, D.D., Principal +of the Theological College of St. George's, was much addicted to +opium. The habit grew upon him, as I understand, from some +foolish freak when he was at college; for having read De +Quincey's description of his dreams and sensations, he had +drenched his tobacco with laudanum in an attempt to produce the +same effects. He found, as so many more have done, that the +practice is easier to attain than to get rid of, and for many +years he continued to be a slave to the drug, an object of +mingled horror and pity to his friends and relatives. I can see +him now, with yellow, pasty face, drooping lids, and pin-point +pupils, all huddled in a chair, the wreck and ruin of a noble +man. + +One night--it was in June, '89--there came a ring to my bell, +about the hour when a man gives his first yawn and glances at the +clock. I sat up in my chair, and my wife laid her needle-work +down in her lap and made a little face of disappointment. + +"A patient!" said she. "You'll have to go out." + +I groaned, for I was newly come back from a weary day. + +We heard the door open, a few hurried words, and then quick steps +upon the linoleum. Our own door flew open, and a lady, clad in +some dark-coloured stuff, with a black veil, entered the room. + +"You will excuse my calling so late," she began, and then, +suddenly losing her self-control, she ran forward, threw her arms +about my wife's neck, and sobbed upon her shoulder. "Oh, I'm in +such trouble!" she cried; "I do so want a little help." + +"Why," said my wife, pulling up her veil, "it is Kate Whitney. +How you startled me, Kate! I had not an idea who you were when +you came in." + +"I didn't know what to do, so I came straight to you." That was +always the way. Folk who were in grief came to my wife like birds +to a light-house. + +"It was very sweet of you to come. Now, you must have some wine +and water, and sit here comfortably and tell us all about it. Or +should you rather that I sent James off to bed?" + +"Oh, no, no! I want the doctor's advice and help, too. It's about +Isa. He has not been home for two days. I am so frightened about +him!" + +It was not the first time that she had spoken to us of her +husband's trouble, to me as a doctor, to my wife as an old friend +and school companion. We soothed and comforted her by such words +as we could find. Did she know where her husband was? Was it +possible that we could bring him back to her? + +It seems that it was. She had the surest information that of late +he had, when the fit was on him, made use of an opium den in the +farthest east of the City. Hitherto his orgies had always been +confined to one day, and he had come back, twitching and +shattered, in the evening. But now the spell had been upon him +eight-and-forty hours, and he lay there, doubtless among the +dregs of the docks, breathing in the poison or sleeping off the +effects. There he was to be found, she was sure of it, at the Bar +of Gold, in Upper Swandam Lane. But what was she to do? How could +she, a young and timid woman, make her way into such a place and +pluck her husband out from among the ruffians who surrounded him? + +There was the case, and of course there was but one way out of +it. Might I not escort her to this place? And then, as a second +thought, why should she come at all? I was Isa Whitney's medical +adviser, and as such I had influence over him. I could manage it +better if I were alone. I promised her on my word that I would +send him home in a cab within two hours if he were indeed at the +address which she had given me. And so in ten minutes I had left +my armchair and cheery sitting-room behind me, and was speeding +eastward in a hansom on a strange errand, as it seemed to me at +the time, though the future only could show how strange it was to +be. + +But there was no great difficulty in the first stage of my +adventure. Upper Swandam Lane is a vile alley lurking behind the +high wharves which line the north side of the river to the east +of London Bridge. Between a slop-shop and a gin-shop, approached +by a steep flight of steps leading down to a black gap like the +mouth of a cave, I found the den of which I was in search. +Ordering my cab to wait, I passed down the steps, worn hollow in +the centre by the ceaseless tread of drunken feet; and by the +light of a flickering oil-lamp above the door I found the latch +and made my way into a long, low room, thick and heavy with the +brown opium smoke, and terraced with wooden berths, like the +forecastle of an emigrant ship. + +Through the gloom one could dimly catch a glimpse of bodies lying +in strange fantastic poses, bowed shoulders, bent knees, heads +thrown back, and chins pointing upward, with here and there a +dark, lack-lustre eye turned upon the newcomer. Out of the black +shadows there glimmered little red circles of light, now bright, +now faint, as the burning poison waxed or waned in the bowls of +the metal pipes. The most lay silent, but some muttered to +themselves, and others talked together in a strange, low, +monotonous voice, their conversation coming in gushes, and then +suddenly tailing off into silence, each mumbling out his own +thoughts and paying little heed to the words of his neighbour. At +the farther end was a small brazier of burning charcoal, beside +which on a three-legged wooden stool there sat a tall, thin old +man, with his jaw resting upon his two fists, and his elbows upon +his knees, staring into the fire. + +As I entered, a sallow Malay attendant had hurried up with a pipe +for me and a supply of the drug, beckoning me to an empty berth. + +"Thank you. I have not come to stay," said I. "There is a friend +of mine here, Mr. Isa Whitney, and I wish to speak with him." + +There was a movement and an exclamation from my right, and +peering through the gloom, I saw Whitney, pale, haggard, and +unkempt, staring out at me. + +"My God! It's Watson," said he. He was in a pitiable state of +reaction, with every nerve in a twitter. "I say, Watson, what +o'clock is it?" + +"Nearly eleven." + +"Of what day?" + +"Of Friday, June 19th." + +"Good heavens! I thought it was Wednesday. It is Wednesday. What +d'you want to frighten a chap for?" He sank his face onto his +arms and began to sob in a high treble key. + +"I tell you that it is Friday, man. Your wife has been waiting +this two days for you. You should be ashamed of yourself!" + +"So I am. But you've got mixed, Watson, for I have only been here +a few hours, three pipes, four pipes--I forget how many. But I'll +go home with you. I wouldn't frighten Kate--poor little Kate. +Give me your hand! Have you a cab?" + +"Yes, I have one waiting." + +"Then I shall go in it. But I must owe something. Find what I +owe, Watson. I am all off colour. I can do nothing for myself." + +I walked down the narrow passage between the double row of +sleepers, holding my breath to keep out the vile, stupefying +fumes of the drug, and looking about for the manager. As I passed +the tall man who sat by the brazier I felt a sudden pluck at my +skirt, and a low voice whispered, "Walk past me, and then look +back at me." The words fell quite distinctly upon my ear. I +glanced down. They could only have come from the old man at my +side, and yet he sat now as absorbed as ever, very thin, very +wrinkled, bent with age, an opium pipe dangling down from between +his knees, as though it had dropped in sheer lassitude from his +fingers. I took two steps forward and looked back. It took all my +self-control to prevent me from breaking out into a cry of +astonishment. He had turned his back so that none could see him +but I. His form had filled out, his wrinkles were gone, the dull +eyes had regained their fire, and there, sitting by the fire and +grinning at my surprise, was none other than Sherlock Holmes. He +made a slight motion to me to approach him, and instantly, as he +turned his face half round to the company once more, subsided +into a doddering, loose-lipped senility. + +"Holmes!" I whispered, "what on earth are you doing in this den?" + +"As low as you can," he answered; "I have excellent ears. If you +would have the great kindness to get rid of that sottish friend +of yours I should be exceedingly glad to have a little talk with +you." + +"I have a cab outside." + +"Then pray send him home in it. You may safely trust him, for he +appears to be too limp to get into any mischief. I should +recommend you also to send a note by the cabman to your wife to +say that you have thrown in your lot with me. If you will wait +outside, I shall be with you in five minutes." + +It was difficult to refuse any of Sherlock Holmes' requests, for +they were always so exceedingly definite, and put forward with +such a quiet air of mastery. I felt, however, that when Whitney +was once confined in the cab my mission was practically +accomplished; and for the rest, I could not wish anything better +than to be associated with my friend in one of those singular +adventures which were the normal condition of his existence. In a +few minutes I had written my note, paid Whitney's bill, led him +out to the cab, and seen him driven through the darkness. In a +very short time a decrepit figure had emerged from the opium den, +and I was walking down the street with Sherlock Holmes. For two +streets he shuffled along with a bent back and an uncertain foot. +Then, glancing quickly round, he straightened himself out and +burst into a hearty fit of laughter. + +"I suppose, Watson," said he, "that you imagine that I have added +opium-smoking to cocaine injections, and all the other little +weaknesses on which you have favoured me with your medical +views." + +"I was certainly surprised to find you there." + +"But not more so than I to find you." + +"I came to find a friend." + +"And I to find an enemy." + +"An enemy?" + +"Yes; one of my natural enemies, or, shall I say, my natural +prey. Briefly, Watson, I am in the midst of a very remarkable +inquiry, and I have hoped to find a clue in the incoherent +ramblings of these sots, as I have done before now. Had I been +recognised in that den my life would not have been worth an +hour's purchase; for I have used it before now for my own +purposes, and the rascally Lascar who runs it has sworn to have +vengeance upon me. There is a trap-door at the back of that +building, near the corner of Paul's Wharf, which could tell some +strange tales of what has passed through it upon the moonless +nights." + +"What! You do not mean bodies?" + +"Ay, bodies, Watson. We should be rich men if we had 1000 pounds +for every poor devil who has been done to death in that den. It +is the vilest murder-trap on the whole riverside, and I fear that +Neville St. Clair has entered it never to leave it more. But our +trap should be here." He put his two forefingers between his +teeth and whistled shrilly--a signal which was answered by a +similar whistle from the distance, followed shortly by the rattle +of wheels and the clink of horses' hoofs. + +"Now, Watson," said Holmes, as a tall dog-cart dashed up through +the gloom, throwing out two golden tunnels of yellow light from +its side lanterns. "You'll come with me, won't you?" + +"If I can be of use." + +"Oh, a trusty comrade is always of use; and a chronicler still +more so. My room at The Cedars is a double-bedded one." + +"The Cedars?" + +"Yes; that is Mr. St. Clair's house. I am staying there while I +conduct the inquiry." + +"Where is it, then?" + +"Near Lee, in Kent. We have a seven-mile drive before us." + +"But I am all in the dark." + +"Of course you are. You'll know all about it presently. Jump up +here. All right, John; we shall not need you. Here's half a +crown. Look out for me to-morrow, about eleven. Give her her +head. So long, then!" + +He flicked the horse with his whip, and we dashed away through +the endless succession of sombre and deserted streets, which +widened gradually, until we were flying across a broad +balustraded bridge, with the murky river flowing sluggishly +beneath us. Beyond lay another dull wilderness of bricks and +mortar, its silence broken only by the heavy, regular footfall of +the policeman, or the songs and shouts of some belated party of +revellers. A dull wrack was drifting slowly across the sky, and a +star or two twinkled dimly here and there through the rifts of +the clouds. Holmes drove in silence, with his head sunk upon his +breast, and the air of a man who is lost in thought, while I sat +beside him, curious to learn what this new quest might be which +seemed to tax his powers so sorely, and yet afraid to break in +upon the current of his thoughts. We had driven several miles, +and were beginning to get to the fringe of the belt of suburban +villas, when he shook himself, shrugged his shoulders, and lit up +his pipe with the air of a man who has satisfied himself that he +is acting for the best. + +"You have a grand gift of silence, Watson," said he. "It makes +you quite invaluable as a companion. 'Pon my word, it is a great +thing for me to have someone to talk to, for my own thoughts are +not over-pleasant. I was wondering what I should say to this dear +little woman to-night when she meets me at the door." + +"You forget that I know nothing about it." + +"I shall just have time to tell you the facts of the case before +we get to Lee. It seems absurdly simple, and yet, somehow I can +get nothing to go upon. There's plenty of thread, no doubt, but I +can't get the end of it into my hand. Now, I'll state the case +clearly and concisely to you, Watson, and maybe you can see a +spark where all is dark to me." + +"Proceed, then." + +"Some years ago--to be definite, in May, 1884--there came to Lee +a gentleman, Neville St. Clair by name, who appeared to have +plenty of money. He took a large villa, laid out the grounds very +nicely, and lived generally in good style. By degrees he made +friends in the neighbourhood, and in 1887 he married the daughter +of a local brewer, by whom he now has two children. He had no +occupation, but was interested in several companies and went into +town as a rule in the morning, returning by the 5:14 from Cannon +Street every night. Mr. St. Clair is now thirty-seven years of +age, is a man of temperate habits, a good husband, a very +affectionate father, and a man who is popular with all who know +him. I may add that his whole debts at the present moment, as far +as we have been able to ascertain, amount to 88 pounds 10s., while +he has 220 pounds standing to his credit in the Capital and +Counties Bank. There is no reason, therefore, to think that money +troubles have been weighing upon his mind. + +"Last Monday Mr. Neville St. Clair went into town rather earlier +than usual, remarking before he started that he had two important +commissions to perform, and that he would bring his little boy +home a box of bricks. Now, by the merest chance, his wife +received a telegram upon this same Monday, very shortly after his +departure, to the effect that a small parcel of considerable +value which she had been expecting was waiting for her at the +offices of the Aberdeen Shipping Company. Now, if you are well up +in your London, you will know that the office of the company is +in Fresno Street, which branches out of Upper Swandam Lane, where +you found me to-night. Mrs. St. Clair had her lunch, started for +the City, did some shopping, proceeded to the company's office, +got her packet, and found herself at exactly 4:35 walking through +Swandam Lane on her way back to the station. Have you followed me +so far?" + +"It is very clear." + +"If you remember, Monday was an exceedingly hot day, and Mrs. St. +Clair walked slowly, glancing about in the hope of seeing a cab, +as she did not like the neighbourhood in which she found herself. +While she was walking in this way down Swandam Lane, she suddenly +heard an ejaculation or cry, and was struck cold to see her +husband looking down at her and, as it seemed to her, beckoning +to her from a second-floor window. The window was open, and she +distinctly saw his face, which she describes as being terribly +agitated. He waved his hands frantically to her, and then +vanished from the window so suddenly that it seemed to her that +he had been plucked back by some irresistible force from behind. +One singular point which struck her quick feminine eye was that +although he wore some dark coat, such as he had started to town +in, he had on neither collar nor necktie. + +"Convinced that something was amiss with him, she rushed down the +steps--for the house was none other than the opium den in which +you found me to-night--and running through the front room she +attempted to ascend the stairs which led to the first floor. At +the foot of the stairs, however, she met this Lascar scoundrel of +whom I have spoken, who thrust her back and, aided by a Dane, who +acts as assistant there, pushed her out into the street. Filled +with the most maddening doubts and fears, she rushed down the +lane and, by rare good-fortune, met in Fresno Street a number of +constables with an inspector, all on their way to their beat. The +inspector and two men accompanied her back, and in spite of the +continued resistance of the proprietor, they made their way to +the room in which Mr. St. Clair had last been seen. There was no +sign of him there. In fact, in the whole of that floor there was +no one to be found save a crippled wretch of hideous aspect, who, +it seems, made his home there. Both he and the Lascar stoutly +swore that no one else had been in the front room during the +afternoon. So determined was their denial that the inspector was +staggered, and had almost come to believe that Mrs. St. Clair had +been deluded when, with a cry, she sprang at a small deal box +which lay upon the table and tore the lid from it. Out there fell +a cascade of children's bricks. It was the toy which he had +promised to bring home. + +"This discovery, and the evident confusion which the cripple +showed, made the inspector realise that the matter was serious. +The rooms were carefully examined, and results all pointed to an +abominable crime. The front room was plainly furnished as a +sitting-room and led into a small bedroom, which looked out upon +the back of one of the wharves. Between the wharf and the bedroom +window is a narrow strip, which is dry at low tide but is covered +at high tide with at least four and a half feet of water. The +bedroom window was a broad one and opened from below. On +examination traces of blood were to be seen upon the windowsill, +and several scattered drops were visible upon the wooden floor of +the bedroom. Thrust away behind a curtain in the front room were +all the clothes of Mr. Neville St. Clair, with the exception of +his coat. His boots, his socks, his hat, and his watch--all were +there. There were no signs of violence upon any of these +garments, and there were no other traces of Mr. Neville St. +Clair. Out of the window he must apparently have gone for no +other exit could be discovered, and the ominous bloodstains upon +the sill gave little promise that he could save himself by +swimming, for the tide was at its very highest at the moment of +the tragedy. + +"And now as to the villains who seemed to be immediately +implicated in the matter. The Lascar was known to be a man of the +vilest antecedents, but as, by Mrs. St. Clair's story, he was +known to have been at the foot of the stair within a very few +seconds of her husband's appearance at the window, he could +hardly have been more than an accessory to the crime. His defence +was one of absolute ignorance, and he protested that he had no +knowledge as to the doings of Hugh Boone, his lodger, and that he +could not account in any way for the presence of the missing +gentleman's clothes. + +"So much for the Lascar manager. Now for the sinister cripple who +lives upon the second floor of the opium den, and who was +certainly the last human being whose eyes rested upon Neville St. +Clair. His name is Hugh Boone, and his hideous face is one which +is familiar to every man who goes much to the City. He is a +professional beggar, though in order to avoid the police +regulations he pretends to a small trade in wax vestas. Some +little distance down Threadneedle Street, upon the left-hand +side, there is, as you may have remarked, a small angle in the +wall. Here it is that this creature takes his daily seat, +cross-legged with his tiny stock of matches on his lap, and as he +is a piteous spectacle a small rain of charity descends into the +greasy leather cap which lies upon the pavement beside him. I +have watched the fellow more than once before ever I thought of +making his professional acquaintance, and I have been surprised +at the harvest which he has reaped in a short time. His +appearance, you see, is so remarkable that no one can pass him +without observing him. A shock of orange hair, a pale face +disfigured by a horrible scar, which, by its contraction, has +turned up the outer edge of his upper lip, a bulldog chin, and a +pair of very penetrating dark eyes, which present a singular +contrast to the colour of his hair, all mark him out from amid +the common crowd of mendicants and so, too, does his wit, for he +is ever ready with a reply to any piece of chaff which may be +thrown at him by the passers-by. This is the man whom we now +learn to have been the lodger at the opium den, and to have been +the last man to see the gentleman of whom we are in quest." + +"But a cripple!" said I. "What could he have done single-handed +against a man in the prime of life?" + +"He is a cripple in the sense that he walks with a limp; but in +other respects he appears to be a powerful and well-nurtured man. +Surely your medical experience would tell you, Watson, that +weakness in one limb is often compensated for by exceptional +strength in the others." + +"Pray continue your narrative." + +"Mrs. St. Clair had fainted at the sight of the blood upon the +window, and she was escorted home in a cab by the police, as her +presence could be of no help to them in their investigations. +Inspector Barton, who had charge of the case, made a very careful +examination of the premises, but without finding anything which +threw any light upon the matter. One mistake had been made in not +arresting Boone instantly, as he was allowed some few minutes +during which he might have communicated with his friend the +Lascar, but this fault was soon remedied, and he was seized and +searched, without anything being found which could incriminate +him. There were, it is true, some blood-stains upon his right +shirt-sleeve, but he pointed to his ring-finger, which had been +cut near the nail, and explained that the bleeding came from +there, adding that he had been to the window not long before, and +that the stains which had been observed there came doubtless from +the same source. He denied strenuously having ever seen Mr. +Neville St. Clair and swore that the presence of the clothes in +his room was as much a mystery to him as to the police. As to +Mrs. St. Clair's assertion that she had actually seen her husband +at the window, he declared that she must have been either mad or +dreaming. He was removed, loudly protesting, to the +police-station, while the inspector remained upon the premises in +the hope that the ebbing tide might afford some fresh clue. + +"And it did, though they hardly found upon the mud-bank what they +had feared to find. It was Neville St. Clair's coat, and not +Neville St. Clair, which lay uncovered as the tide receded. And +what do you think they found in the pockets?" + +"I cannot imagine." + +"No, I don't think you would guess. Every pocket stuffed with +pennies and half-pennies--421 pennies and 270 half-pennies. It +was no wonder that it had not been swept away by the tide. But a +human body is a different matter. There is a fierce eddy between +the wharf and the house. It seemed likely enough that the +weighted coat had remained when the stripped body had been sucked +away into the river." + +"But I understand that all the other clothes were found in the +room. Would the body be dressed in a coat alone?" + +"No, sir, but the facts might be met speciously enough. Suppose +that this man Boone had thrust Neville St. Clair through the +window, there is no human eye which could have seen the deed. +What would he do then? It would of course instantly strike him +that he must get rid of the tell-tale garments. He would seize +the coat, then, and be in the act of throwing it out, when it +would occur to him that it would swim and not sink. He has little +time, for he has heard the scuffle downstairs when the wife tried +to force her way up, and perhaps he has already heard from his +Lascar confederate that the police are hurrying up the street. +There is not an instant to be lost. He rushes to some secret +hoard, where he has accumulated the fruits of his beggary, and he +stuffs all the coins upon which he can lay his hands into the +pockets to make sure of the coat's sinking. He throws it out, and +would have done the same with the other garments had not he heard +the rush of steps below, and only just had time to close the +window when the police appeared." + +"It certainly sounds feasible." + +"Well, we will take it as a working hypothesis for want of a +better. Boone, as I have told you, was arrested and taken to the +station, but it could not be shown that there had ever before +been anything against him. He had for years been known as a +professional beggar, but his life appeared to have been a very +quiet and innocent one. There the matter stands at present, and +the questions which have to be solved--what Neville St. Clair was +doing in the opium den, what happened to him when there, where is +he now, and what Hugh Boone had to do with his disappearance--are +all as far from a solution as ever. I confess that I cannot +recall any case within my experience which looked at the first +glance so simple and yet which presented such difficulties." + +While Sherlock Holmes had been detailing this singular series of +events, we had been whirling through the outskirts of the great +town until the last straggling houses had been left behind, and +we rattled along with a country hedge upon either side of us. +Just as he finished, however, we drove through two scattered +villages, where a few lights still glimmered in the windows. + +"We are on the outskirts of Lee," said my companion. "We have +touched on three English counties in our short drive, starting in +Middlesex, passing over an angle of Surrey, and ending in Kent. +See that light among the trees? That is The Cedars, and beside +that lamp sits a woman whose anxious ears have already, I have +little doubt, caught the clink of our horse's feet." + +"But why are you not conducting the case from Baker Street?" I +asked. + +"Because there are many inquiries which must be made out here. +Mrs. St. Clair has most kindly put two rooms at my disposal, and +you may rest assured that she will have nothing but a welcome for +my friend and colleague. I hate to meet her, Watson, when I have +no news of her husband. Here we are. Whoa, there, whoa!" + +We had pulled up in front of a large villa which stood within its +own grounds. A stable-boy had run out to the horse's head, and +springing down, I followed Holmes up the small, winding +gravel-drive which led to the house. As we approached, the door +flew open, and a little blonde woman stood in the opening, clad +in some sort of light mousseline de soie, with a touch of fluffy +pink chiffon at her neck and wrists. She stood with her figure +outlined against the flood of light, one hand upon the door, one +half-raised in her eagerness, her body slightly bent, her head +and face protruded, with eager eyes and parted lips, a standing +question. + +"Well?" she cried, "well?" And then, seeing that there were two +of us, she gave a cry of hope which sank into a groan as she saw +that my companion shook his head and shrugged his shoulders. + +"No good news?" + +"None." + +"No bad?" + +"No." + +"Thank God for that. But come in. You must be weary, for you have +had a long day." + +"This is my friend, Dr. Watson. He has been of most vital use to +me in several of my cases, and a lucky chance has made it +possible for me to bring him out and associate him with this +investigation." + +"I am delighted to see you," said she, pressing my hand warmly. +"You will, I am sure, forgive anything that may be wanting in our +arrangements, when you consider the blow which has come so +suddenly upon us." + +"My dear madam," said I, "I am an old campaigner, and if I were +not I can very well see that no apology is needed. If I can be of +any assistance, either to you or to my friend here, I shall be +indeed happy." + +"Now, Mr. Sherlock Holmes," said the lady as we entered a +well-lit dining-room, upon the table of which a cold supper had +been laid out, "I should very much like to ask you one or two +plain questions, to which I beg that you will give a plain +answer." + +"Certainly, madam." + +"Do not trouble about my feelings. I am not hysterical, nor given +to fainting. I simply wish to hear your real, real opinion." + +"Upon what point?" + +"In your heart of hearts, do you think that Neville is alive?" + +Sherlock Holmes seemed to be embarrassed by the question. +"Frankly, now!" she repeated, standing upon the rug and looking +keenly down at him as he leaned back in a basket-chair. + +"Frankly, then, madam, I do not." + +"You think that he is dead?" + +"I do." + +"Murdered?" + +"I don't say that. Perhaps." + +"And on what day did he meet his death?" + +"On Monday." + +"Then perhaps, Mr. Holmes, you will be good enough to explain how +it is that I have received a letter from him to-day." + +Sherlock Holmes sprang out of his chair as if he had been +galvanised. + +"What!" he roared. + +"Yes, to-day." She stood smiling, holding up a little slip of +paper in the air. + +"May I see it?" + +"Certainly." + +He snatched it from her in his eagerness, and smoothing it out +upon the table he drew over the lamp and examined it intently. I +had left my chair and was gazing at it over his shoulder. The +envelope was a very coarse one and was stamped with the Gravesend +postmark and with the date of that very day, or rather of the day +before, for it was considerably after midnight. + +"Coarse writing," murmured Holmes. "Surely this is not your +husband's writing, madam." + +"No, but the enclosure is." + +"I perceive also that whoever addressed the envelope had to go +and inquire as to the address." + +"How can you tell that?" + +"The name, you see, is in perfectly black ink, which has dried +itself. The rest is of the greyish colour, which shows that +blotting-paper has been used. If it had been written straight +off, and then blotted, none would be of a deep black shade. This +man has written the name, and there has then been a pause before +he wrote the address, which can only mean that he was not +familiar with it. It is, of course, a trifle, but there is +nothing so important as trifles. Let us now see the letter. Ha! +there has been an enclosure here!" + +"Yes, there was a ring. His signet-ring." + +"And you are sure that this is your husband's hand?" + +"One of his hands." + +"One?" + +"His hand when he wrote hurriedly. It is very unlike his usual +writing, and yet I know it well." + +"'Dearest do not be frightened. All will come well. There is a +huge error which it may take some little time to rectify. +Wait in patience.--NEVILLE.' Written in pencil upon the fly-leaf +of a book, octavo size, no water-mark. Hum! Posted to-day in +Gravesend by a man with a dirty thumb. Ha! And the flap has been +gummed, if I am not very much in error, by a person who had been +chewing tobacco. And you have no doubt that it is your husband's +hand, madam?" + +"None. Neville wrote those words." + +"And they were posted to-day at Gravesend. Well, Mrs. St. Clair, +the clouds lighten, though I should not venture to say that the +danger is over." + +"But he must be alive, Mr. Holmes." + +"Unless this is a clever forgery to put us on the wrong scent. +The ring, after all, proves nothing. It may have been taken from +him." + +"No, no; it is, it is his very own writing!" + +"Very well. It may, however, have been written on Monday and only +posted to-day." + +"That is possible." + +"If so, much may have happened between." + +"Oh, you must not discourage me, Mr. Holmes. I know that all is +well with him. There is so keen a sympathy between us that I +should know if evil came upon him. On the very day that I saw him +last he cut himself in the bedroom, and yet I in the dining-room +rushed upstairs instantly with the utmost certainty that +something had happened. Do you think that I would respond to such +a trifle and yet be ignorant of his death?" + +"I have seen too much not to know that the impression of a woman +may be more valuable than the conclusion of an analytical +reasoner. And in this letter you certainly have a very strong +piece of evidence to corroborate your view. But if your husband +is alive and able to write letters, why should he remain away +from you?" + +"I cannot imagine. It is unthinkable." + +"And on Monday he made no remarks before leaving you?" + +"No." + +"And you were surprised to see him in Swandam Lane?" + +"Very much so." + +"Was the window open?" + +"Yes." + +"Then he might have called to you?" + +"He might." + +"He only, as I understand, gave an inarticulate cry?" + +"Yes." + +"A call for help, you thought?" + +"Yes. He waved his hands." + +"But it might have been a cry of surprise. Astonishment at the +unexpected sight of you might cause him to throw up his hands?" + +"It is possible." + +"And you thought he was pulled back?" + +"He disappeared so suddenly." + +"He might have leaped back. You did not see anyone else in the +room?" + +"No, but this horrible man confessed to having been there, and +the Lascar was at the foot of the stairs." + +"Quite so. Your husband, as far as you could see, had his +ordinary clothes on?" + +"But without his collar or tie. I distinctly saw his bare +throat." + +"Had he ever spoken of Swandam Lane?" + +"Never." + +"Had he ever showed any signs of having taken opium?" + +"Never." + +"Thank you, Mrs. St. Clair. Those are the principal points about +which I wished to be absolutely clear. We shall now have a little +supper and then retire, for we may have a very busy day +to-morrow." + +A large and comfortable double-bedded room had been placed at our +disposal, and I was quickly between the sheets, for I was weary +after my night of adventure. Sherlock Holmes was a man, however, +who, when he had an unsolved problem upon his mind, would go for +days, and even for a week, without rest, turning it over, +rearranging his facts, looking at it from every point of view +until he had either fathomed it or convinced himself that his +data were insufficient. It was soon evident to me that he was now +preparing for an all-night sitting. He took off his coat and +waistcoat, put on a large blue dressing-gown, and then wandered +about the room collecting pillows from his bed and cushions from +the sofa and armchairs. With these he constructed a sort of +Eastern divan, upon which he perched himself cross-legged, with +an ounce of shag tobacco and a box of matches laid out in front +of him. In the dim light of the lamp I saw him sitting there, an +old briar pipe between his lips, his eyes fixed vacantly upon the +corner of the ceiling, the blue smoke curling up from him, +silent, motionless, with the light shining upon his strong-set +aquiline features. So he sat as I dropped off to sleep, and so he +sat when a sudden ejaculation caused me to wake up, and I found +the summer sun shining into the apartment. The pipe was still +between his lips, the smoke still curled upward, and the room was +full of a dense tobacco haze, but nothing remained of the heap of +shag which I had seen upon the previous night. + +"Awake, Watson?" he asked. + +"Yes." + +"Game for a morning drive?" + +"Certainly." + +"Then dress. No one is stirring yet, but I know where the +stable-boy sleeps, and we shall soon have the trap out." He +chuckled to himself as he spoke, his eyes twinkled, and he seemed +a different man to the sombre thinker of the previous night. + +As I dressed I glanced at my watch. It was no wonder that no one +was stirring. It was twenty-five minutes past four. I had hardly +finished when Holmes returned with the news that the boy was +putting in the horse. + +"I want to test a little theory of mine," said he, pulling on his +boots. "I think, Watson, that you are now standing in the +presence of one of the most absolute fools in Europe. I deserve +to be kicked from here to Charing Cross. But I think I have the +key of the affair now." + +"And where is it?" I asked, smiling. + +"In the bathroom," he answered. "Oh, yes, I am not joking," he +continued, seeing my look of incredulity. "I have just been +there, and I have taken it out, and I have got it in this +Gladstone bag. Come on, my boy, and we shall see whether it will +not fit the lock." + +We made our way downstairs as quietly as possible, and out into +the bright morning sunshine. In the road stood our horse and +trap, with the half-clad stable-boy waiting at the head. We both +sprang in, and away we dashed down the London Road. A few country +carts were stirring, bearing in vegetables to the metropolis, but +the lines of villas on either side were as silent and lifeless as +some city in a dream. + +"It has been in some points a singular case," said Holmes, +flicking the horse on into a gallop. "I confess that I have been +as blind as a mole, but it is better to learn wisdom late than +never to learn it at all." + +In town the earliest risers were just beginning to look sleepily +from their windows as we drove through the streets of the Surrey +side. Passing down the Waterloo Bridge Road we crossed over the +river, and dashing up Wellington Street wheeled sharply to the +right and found ourselves in Bow Street. Sherlock Holmes was well +known to the force, and the two constables at the door saluted +him. One of them held the horse's head while the other led us in. + +"Who is on duty?" asked Holmes. + +"Inspector Bradstreet, sir." + +"Ah, Bradstreet, how are you?" A tall, stout official had come +down the stone-flagged passage, in a peaked cap and frogged +jacket. "I wish to have a quiet word with you, Bradstreet." +"Certainly, Mr. Holmes. Step into my room here." It was a small, +office-like room, with a huge ledger upon the table, and a +telephone projecting from the wall. The inspector sat down at his +desk. + +"What can I do for you, Mr. Holmes?" + +"I called about that beggarman, Boone--the one who was charged +with being concerned in the disappearance of Mr. Neville St. +Clair, of Lee." + +"Yes. He was brought up and remanded for further inquiries." + +"So I heard. You have him here?" + +"In the cells." + +"Is he quiet?" + +"Oh, he gives no trouble. But he is a dirty scoundrel." + +"Dirty?" + +"Yes, it is all we can do to make him wash his hands, and his +face is as black as a tinker's. Well, when once his case has been +settled, he will have a regular prison bath; and I think, if you +saw him, you would agree with me that he needed it." + +"I should like to see him very much." + +"Would you? That is easily done. Come this way. You can leave +your bag." + +"No, I think that I'll take it." + +"Very good. Come this way, if you please." He led us down a +passage, opened a barred door, passed down a winding stair, and +brought us to a whitewashed corridor with a line of doors on each +side. + +"The third on the right is his," said the inspector. "Here it +is!" He quietly shot back a panel in the upper part of the door +and glanced through. + +"He is asleep," said he. "You can see him very well." + +We both put our eyes to the grating. The prisoner lay with his +face towards us, in a very deep sleep, breathing slowly and +heavily. He was a middle-sized man, coarsely clad as became his +calling, with a coloured shirt protruding through the rent in his +tattered coat. He was, as the inspector had said, extremely +dirty, but the grime which covered his face could not conceal its +repulsive ugliness. A broad wheal from an old scar ran right +across it from eye to chin, and by its contraction had turned up +one side of the upper lip, so that three teeth were exposed in a +perpetual snarl. A shock of very bright red hair grew low over +his eyes and forehead. + +"He's a beauty, isn't he?" said the inspector. + +"He certainly needs a wash," remarked Holmes. "I had an idea that +he might, and I took the liberty of bringing the tools with me." +He opened the Gladstone bag as he spoke, and took out, to my +astonishment, a very large bath-sponge. + +"He! he! You are a funny one," chuckled the inspector. + +"Now, if you will have the great goodness to open that door very +quietly, we will soon make him cut a much more respectable +figure." + +"Well, I don't know why not," said the inspector. "He doesn't +look a credit to the Bow Street cells, does he?" He slipped his +key into the lock, and we all very quietly entered the cell. The +sleeper half turned, and then settled down once more into a deep +slumber. Holmes stooped to the water-jug, moistened his sponge, +and then rubbed it twice vigorously across and down the +prisoner's face. + +"Let me introduce you," he shouted, "to Mr. Neville St. Clair, of +Lee, in the county of Kent." + +Never in my life have I seen such a sight. The man's face peeled +off under the sponge like the bark from a tree. Gone was the +coarse brown tint! Gone, too, was the horrid scar which had +seamed it across, and the twisted lip which had given the +repulsive sneer to the face! A twitch brought away the tangled +red hair, and there, sitting up in his bed, was a pale, +sad-faced, refined-looking man, black-haired and smooth-skinned, +rubbing his eyes and staring about him with sleepy bewilderment. +Then suddenly realising the exposure, he broke into a scream and +threw himself down with his face to the pillow. + +"Great heavens!" cried the inspector, "it is, indeed, the missing +man. I know him from the photograph." + +The prisoner turned with the reckless air of a man who abandons +himself to his destiny. "Be it so," said he. "And pray what am I +charged with?" + +"With making away with Mr. Neville St.-- Oh, come, you can't be +charged with that unless they make a case of attempted suicide of +it," said the inspector with a grin. "Well, I have been +twenty-seven years in the force, but this really takes the cake." + +"If I am Mr. Neville St. Clair, then it is obvious that no crime +has been committed, and that, therefore, I am illegally +detained." + +"No crime, but a very great error has been committed," said +Holmes. "You would have done better to have trusted your wife." + +"It was not the wife; it was the children," groaned the prisoner. +"God help me, I would not have them ashamed of their father. My +God! What an exposure! What can I do?" + +Sherlock Holmes sat down beside him on the couch and patted him +kindly on the shoulder. + +"If you leave it to a court of law to clear the matter up," said +he, "of course you can hardly avoid publicity. On the other hand, +if you convince the police authorities that there is no possible +case against you, I do not know that there is any reason that the +details should find their way into the papers. Inspector +Bradstreet would, I am sure, make notes upon anything which you +might tell us and submit it to the proper authorities. The case +would then never go into court at all." + +"God bless you!" cried the prisoner passionately. "I would have +endured imprisonment, ay, even execution, rather than have left +my miserable secret as a family blot to my children. + +"You are the first who have ever heard my story. My father was a +schoolmaster in Chesterfield, where I received an excellent +education. I travelled in my youth, took to the stage, and +finally became a reporter on an evening paper in London. One day +my editor wished to have a series of articles upon begging in the +metropolis, and I volunteered to supply them. There was the point +from which all my adventures started. It was only by trying +begging as an amateur that I could get the facts upon which to +base my articles. When an actor I had, of course, learned all the +secrets of making up, and had been famous in the green-room for +my skill. I took advantage now of my attainments. I painted my +face, and to make myself as pitiable as possible I made a good +scar and fixed one side of my lip in a twist by the aid of a +small slip of flesh-coloured plaster. Then with a red head of +hair, and an appropriate dress, I took my station in the business +part of the city, ostensibly as a match-seller but really as a +beggar. For seven hours I plied my trade, and when I returned +home in the evening I found to my surprise that I had received no +less than 26s. 4d. + +"I wrote my articles and thought little more of the matter until, +some time later, I backed a bill for a friend and had a writ +served upon me for 25 pounds. I was at my wit's end where to get +the money, but a sudden idea came to me. I begged a fortnight's +grace from the creditor, asked for a holiday from my employers, +and spent the time in begging in the City under my disguise. In +ten days I had the money and had paid the debt. + +"Well, you can imagine how hard it was to settle down to arduous +work at 2 pounds a week when I knew that I could earn as much in +a day by smearing my face with a little paint, laying my cap on +the ground, and sitting still. It was a long fight between my +pride and the money, but the dollars won at last, and I threw up +reporting and sat day after day in the corner which I had first +chosen, inspiring pity by my ghastly face and filling my pockets +with coppers. Only one man knew my secret. He was the keeper of a +low den in which I used to lodge in Swandam Lane, where I could +every morning emerge as a squalid beggar and in the evenings +transform myself into a well-dressed man about town. This fellow, +a Lascar, was well paid by me for his rooms, so that I knew that +my secret was safe in his possession. + +"Well, very soon I found that I was saving considerable sums of +money. I do not mean that any beggar in the streets of London +could earn 700 pounds a year--which is less than my average +takings--but I had exceptional advantages in my power of making +up, and also in a facility of repartee, which improved by +practice and made me quite a recognised character in the City. +All day a stream of pennies, varied by silver, poured in upon me, +and it was a very bad day in which I failed to take 2 pounds. + +"As I grew richer I grew more ambitious, took a house in the +country, and eventually married, without anyone having a +suspicion as to my real occupation. My dear wife knew that I had +business in the City. She little knew what. + +"Last Monday I had finished for the day and was dressing in my +room above the opium den when I looked out of my window and saw, +to my horror and astonishment, that my wife was standing in the +street, with her eyes fixed full upon me. I gave a cry of +surprise, threw up my arms to cover my face, and, rushing to my +confidant, the Lascar, entreated him to prevent anyone from +coming up to me. I heard her voice downstairs, but I knew that +she could not ascend. Swiftly I threw off my clothes, pulled on +those of a beggar, and put on my pigments and wig. Even a wife's +eyes could not pierce so complete a disguise. But then it +occurred to me that there might be a search in the room, and that +the clothes might betray me. I threw open the window, reopening +by my violence a small cut which I had inflicted upon myself in +the bedroom that morning. Then I seized my coat, which was +weighted by the coppers which I had just transferred to it from +the leather bag in which I carried my takings. I hurled it out of +the window, and it disappeared into the Thames. The other clothes +would have followed, but at that moment there was a rush of +constables up the stair, and a few minutes after I found, rather, +I confess, to my relief, that instead of being identified as Mr. +Neville St. Clair, I was arrested as his murderer. + +"I do not know that there is anything else for me to explain. I +was determined to preserve my disguise as long as possible, and +hence my preference for a dirty face. Knowing that my wife would +be terribly anxious, I slipped off my ring and confided it to the +Lascar at a moment when no constable was watching me, together +with a hurried scrawl, telling her that she had no cause to +fear." + +"That note only reached her yesterday," said Holmes. + +"Good God! What a week she must have spent!" + +"The police have watched this Lascar," said Inspector Bradstreet, +"and I can quite understand that he might find it difficult to +post a letter unobserved. Probably he handed it to some sailor +customer of his, who forgot all about it for some days." + +"That was it," said Holmes, nodding approvingly; "I have no doubt +of it. But have you never been prosecuted for begging?" + +"Many times; but what was a fine to me?" + +"It must stop here, however," said Bradstreet. "If the police are +to hush this thing up, there must be no more of Hugh Boone." + +"I have sworn it by the most solemn oaths which a man can take." + +"In that case I think that it is probable that no further steps +may be taken. But if you are found again, then all must come out. +I am sure, Mr. Holmes, that we are very much indebted to you for +having cleared the matter up. I wish I knew how you reach your +results." + +"I reached this one," said my friend, "by sitting upon five +pillows and consuming an ounce of shag. I think, Watson, that if +we drive to Baker Street we shall just be in time for breakfast." + + + +VII. THE ADVENTURE OF THE BLUE CARBUNCLE + +I had called upon my friend Sherlock Holmes upon the second +morning after Christmas, with the intention of wishing him the +compliments of the season. He was lounging upon the sofa in a +purple dressing-gown, a pipe-rack within his reach upon the +right, and a pile of crumpled morning papers, evidently newly +studied, near at hand. Beside the couch was a wooden chair, and +on the angle of the back hung a very seedy and disreputable +hard-felt hat, much the worse for wear, and cracked in several +places. A lens and a forceps lying upon the seat of the chair +suggested that the hat had been suspended in this manner for the +purpose of examination. + +"You are engaged," said I; "perhaps I interrupt you." + +"Not at all. I am glad to have a friend with whom I can discuss +my results. The matter is a perfectly trivial one"--he jerked his +thumb in the direction of the old hat--"but there are points in +connection with it which are not entirely devoid of interest and +even of instruction." + +I seated myself in his armchair and warmed my hands before his +crackling fire, for a sharp frost had set in, and the windows +were thick with the ice crystals. "I suppose," I remarked, "that, +homely as it looks, this thing has some deadly story linked on to +it--that it is the clue which will guide you in the solution of +some mystery and the punishment of some crime." + +"No, no. No crime," said Sherlock Holmes, laughing. "Only one of +those whimsical little incidents which will happen when you have +four million human beings all jostling each other within the +space of a few square miles. Amid the action and reaction of so +dense a swarm of humanity, every possible combination of events +may be expected to take place, and many a little problem will be +presented which may be striking and bizarre without being +criminal. We have already had experience of such." + +"So much so," I remarked, "that of the last six cases which I +have added to my notes, three have been entirely free of any +legal crime." + +"Precisely. You allude to my attempt to recover the Irene Adler +papers, to the singular case of Miss Mary Sutherland, and to the +adventure of the man with the twisted lip. Well, I have no doubt +that this small matter will fall into the same innocent category. +You know Peterson, the commissionaire?" + +"Yes." + +"It is to him that this trophy belongs." + +"It is his hat." + +"No, no, he found it. Its owner is unknown. I beg that you will +look upon it not as a battered billycock but as an intellectual +problem. And, first, as to how it came here. It arrived upon +Christmas morning, in company with a good fat goose, which is, I +have no doubt, roasting at this moment in front of Peterson's +fire. The facts are these: about four o'clock on Christmas +morning, Peterson, who, as you know, is a very honest fellow, was +returning from some small jollification and was making his way +homeward down Tottenham Court Road. In front of him he saw, in +the gaslight, a tallish man, walking with a slight stagger, and +carrying a white goose slung over his shoulder. As he reached the +corner of Goodge Street, a row broke out between this stranger +and a little knot of roughs. One of the latter knocked off the +man's hat, on which he raised his stick to defend himself and, +swinging it over his head, smashed the shop window behind him. +Peterson had rushed forward to protect the stranger from his +assailants; but the man, shocked at having broken the window, and +seeing an official-looking person in uniform rushing towards him, +dropped his goose, took to his heels, and vanished amid the +labyrinth of small streets which lie at the back of Tottenham +Court Road. The roughs had also fled at the appearance of +Peterson, so that he was left in possession of the field of +battle, and also of the spoils of victory in the shape of this +battered hat and a most unimpeachable Christmas goose." + +"Which surely he restored to their owner?" + +"My dear fellow, there lies the problem. It is true that 'For +Mrs. Henry Baker' was printed upon a small card which was tied to +the bird's left leg, and it is also true that the initials 'H. +B.' are legible upon the lining of this hat, but as there are +some thousands of Bakers, and some hundreds of Henry Bakers in +this city of ours, it is not easy to restore lost property to any +one of them." + +"What, then, did Peterson do?" + +"He brought round both hat and goose to me on Christmas morning, +knowing that even the smallest problems are of interest to me. +The goose we retained until this morning, when there were signs +that, in spite of the slight frost, it would be well that it +should be eaten without unnecessary delay. Its finder has carried +it off, therefore, to fulfil the ultimate destiny of a goose, +while I continue to retain the hat of the unknown gentleman who +lost his Christmas dinner." + +"Did he not advertise?" + +"No." + +"Then, what clue could you have as to his identity?" + +"Only as much as we can deduce." + +"From his hat?" + +"Precisely." + +"But you are joking. What can you gather from this old battered +felt?" + +"Here is my lens. You know my methods. What can you gather +yourself as to the individuality of the man who has worn this +article?" + +I took the tattered object in my hands and turned it over rather +ruefully. It was a very ordinary black hat of the usual round +shape, hard and much the worse for wear. The lining had been of +red silk, but was a good deal discoloured. There was no maker's +name; but, as Holmes had remarked, the initials "H. B." were +scrawled upon one side. It was pierced in the brim for a +hat-securer, but the elastic was missing. For the rest, it was +cracked, exceedingly dusty, and spotted in several places, +although there seemed to have been some attempt to hide the +discoloured patches by smearing them with ink. + +"I can see nothing," said I, handing it back to my friend. + +"On the contrary, Watson, you can see everything. You fail, +however, to reason from what you see. You are too timid in +drawing your inferences." + +"Then, pray tell me what it is that you can infer from this hat?" + +He picked it up and gazed at it in the peculiar introspective +fashion which was characteristic of him. "It is perhaps less +suggestive than it might have been," he remarked, "and yet there +are a few inferences which are very distinct, and a few others +which represent at least a strong balance of probability. That +the man was highly intellectual is of course obvious upon the +face of it, and also that he was fairly well-to-do within the +last three years, although he has now fallen upon evil days. He +had foresight, but has less now than formerly, pointing to a +moral retrogression, which, when taken with the decline of his +fortunes, seems to indicate some evil influence, probably drink, +at work upon him. This may account also for the obvious fact that +his wife has ceased to love him." + +"My dear Holmes!" + +"He has, however, retained some degree of self-respect," he +continued, disregarding my remonstrance. "He is a man who leads a +sedentary life, goes out little, is out of training entirely, is +middle-aged, has grizzled hair which he has had cut within the +last few days, and which he anoints with lime-cream. These are +the more patent facts which are to be deduced from his hat. Also, +by the way, that it is extremely improbable that he has gas laid +on in his house." + +"You are certainly joking, Holmes." + +"Not in the least. Is it possible that even now, when I give you +these results, you are unable to see how they are attained?" + +"I have no doubt that I am very stupid, but I must confess that I +am unable to follow you. For example, how did you deduce that +this man was intellectual?" + +For answer Holmes clapped the hat upon his head. It came right +over the forehead and settled upon the bridge of his nose. "It is +a question of cubic capacity," said he; "a man with so large a +brain must have something in it." + +"The decline of his fortunes, then?" + +"This hat is three years old. These flat brims curled at the edge +came in then. It is a hat of the very best quality. Look at the +band of ribbed silk and the excellent lining. If this man could +afford to buy so expensive a hat three years ago, and has had no +hat since, then he has assuredly gone down in the world." + +"Well, that is clear enough, certainly. But how about the +foresight and the moral retrogression?" + +Sherlock Holmes laughed. "Here is the foresight," said he putting +his finger upon the little disc and loop of the hat-securer. +"They are never sold upon hats. If this man ordered one, it is a +sign of a certain amount of foresight, since he went out of his +way to take this precaution against the wind. But since we see +that he has broken the elastic and has not troubled to replace +it, it is obvious that he has less foresight now than formerly, +which is a distinct proof of a weakening nature. On the other +hand, he has endeavoured to conceal some of these stains upon the +felt by daubing them with ink, which is a sign that he has not +entirely lost his self-respect." + +"Your reasoning is certainly plausible." + +"The further points, that he is middle-aged, that his hair is +grizzled, that it has been recently cut, and that he uses +lime-cream, are all to be gathered from a close examination of the +lower part of the lining. The lens discloses a large number of +hair-ends, clean cut by the scissors of the barber. They all +appear to be adhesive, and there is a distinct odour of +lime-cream. This dust, you will observe, is not the gritty, grey +dust of the street but the fluffy brown dust of the house, +showing that it has been hung up indoors most of the time, while +the marks of moisture upon the inside are proof positive that the +wearer perspired very freely, and could therefore, hardly be in +the best of training." + +"But his wife--you said that she had ceased to love him." + +"This hat has not been brushed for weeks. When I see you, my dear +Watson, with a week's accumulation of dust upon your hat, and +when your wife allows you to go out in such a state, I shall fear +that you also have been unfortunate enough to lose your wife's +affection." + +"But he might be a bachelor." + +"Nay, he was bringing home the goose as a peace-offering to his +wife. Remember the card upon the bird's leg." + +"You have an answer to everything. But how on earth do you deduce +that the gas is not laid on in his house?" + +"One tallow stain, or even two, might come by chance; but when I +see no less than five, I think that there can be little doubt +that the individual must be brought into frequent contact with +burning tallow--walks upstairs at night probably with his hat in +one hand and a guttering candle in the other. Anyhow, he never +got tallow-stains from a gas-jet. Are you satisfied?" + +"Well, it is very ingenious," said I, laughing; "but since, as +you said just now, there has been no crime committed, and no harm +done save the loss of a goose, all this seems to be rather a +waste of energy." + +Sherlock Holmes had opened his mouth to reply, when the door flew +open, and Peterson, the commissionaire, rushed into the apartment +with flushed cheeks and the face of a man who is dazed with +astonishment. + +"The goose, Mr. Holmes! The goose, sir!" he gasped. + +"Eh? What of it, then? Has it returned to life and flapped off +through the kitchen window?" Holmes twisted himself round upon +the sofa to get a fairer view of the man's excited face. + +"See here, sir! See what my wife found in its crop!" He held out +his hand and displayed upon the centre of the palm a brilliantly +scintillating blue stone, rather smaller than a bean in size, but +of such purity and radiance that it twinkled like an electric +point in the dark hollow of his hand. + +Sherlock Holmes sat up with a whistle. "By Jove, Peterson!" said +he, "this is treasure trove indeed. I suppose you know what you +have got?" + +"A diamond, sir? A precious stone. It cuts into glass as though +it were putty." + +"It's more than a precious stone. It is the precious stone." + +"Not the Countess of Morcar's blue carbuncle!" I ejaculated. + +"Precisely so. I ought to know its size and shape, seeing that I +have read the advertisement about it in The Times every day +lately. It is absolutely unique, and its value can only be +conjectured, but the reward offered of 1000 pounds is certainly +not within a twentieth part of the market price." + +"A thousand pounds! Great Lord of mercy!" The commissionaire +plumped down into a chair and stared from one to the other of us. + +"That is the reward, and I have reason to know that there are +sentimental considerations in the background which would induce +the Countess to part with half her fortune if she could but +recover the gem." + +"It was lost, if I remember aright, at the Hotel Cosmopolitan," I +remarked. + +"Precisely so, on December 22nd, just five days ago. John Horner, +a plumber, was accused of having abstracted it from the lady's +jewel-case. The evidence against him was so strong that the case +has been referred to the Assizes. I have some account of the +matter here, I believe." He rummaged amid his newspapers, +glancing over the dates, until at last he smoothed one out, +doubled it over, and read the following paragraph: + +"Hotel Cosmopolitan Jewel Robbery. John Horner, 26, plumber, was +brought up upon the charge of having upon the 22nd inst., +abstracted from the jewel-case of the Countess of Morcar the +valuable gem known as the blue carbuncle. James Ryder, +upper-attendant at the hotel, gave his evidence to the effect +that he had shown Horner up to the dressing-room of the Countess +of Morcar upon the day of the robbery in order that he might +solder the second bar of the grate, which was loose. He had +remained with Horner some little time, but had finally been +called away. On returning, he found that Horner had disappeared, +that the bureau had been forced open, and that the small morocco +casket in which, as it afterwards transpired, the Countess was +accustomed to keep her jewel, was lying empty upon the +dressing-table. Ryder instantly gave the alarm, and Horner was +arrested the same evening; but the stone could not be found +either upon his person or in his rooms. Catherine Cusack, maid to +the Countess, deposed to having heard Ryder's cry of dismay on +discovering the robbery, and to having rushed into the room, +where she found matters as described by the last witness. +Inspector Bradstreet, B division, gave evidence as to the arrest +of Horner, who struggled frantically, and protested his innocence +in the strongest terms. Evidence of a previous conviction for +robbery having been given against the prisoner, the magistrate +refused to deal summarily with the offence, but referred it to +the Assizes. Horner, who had shown signs of intense emotion +during the proceedings, fainted away at the conclusion and was +carried out of court." + +"Hum! So much for the police-court," said Holmes thoughtfully, +tossing aside the paper. "The question for us now to solve is the +sequence of events leading from a rifled jewel-case at one end to +the crop of a goose in Tottenham Court Road at the other. You +see, Watson, our little deductions have suddenly assumed a much +more important and less innocent aspect. Here is the stone; the +stone came from the goose, and the goose came from Mr. Henry +Baker, the gentleman with the bad hat and all the other +characteristics with which I have bored you. So now we must set +ourselves very seriously to finding this gentleman and +ascertaining what part he has played in this little mystery. To +do this, we must try the simplest means first, and these lie +undoubtedly in an advertisement in all the evening papers. If +this fail, I shall have recourse to other methods." + +"What will you say?" + +"Give me a pencil and that slip of paper. Now, then: 'Found at +the corner of Goodge Street, a goose and a black felt hat. Mr. +Henry Baker can have the same by applying at 6:30 this evening at +221B, Baker Street.' That is clear and concise." + +"Very. But will he see it?" + +"Well, he is sure to keep an eye on the papers, since, to a poor +man, the loss was a heavy one. He was clearly so scared by his +mischance in breaking the window and by the approach of Peterson +that he thought of nothing but flight, but since then he must +have bitterly regretted the impulse which caused him to drop his +bird. Then, again, the introduction of his name will cause him to +see it, for everyone who knows him will direct his attention to +it. Here you are, Peterson, run down to the advertising agency +and have this put in the evening papers." + +"In which, sir?" + +"Oh, in the Globe, Star, Pall Mall, St. James's, Evening News, +Standard, Echo, and any others that occur to you." + +"Very well, sir. And this stone?" + +"Ah, yes, I shall keep the stone. Thank you. And, I say, +Peterson, just buy a goose on your way back and leave it here +with me, for we must have one to give to this gentleman in place +of the one which your family is now devouring." + +When the commissionaire had gone, Holmes took up the stone and +held it against the light. "It's a bonny thing," said he. "Just +see how it glints and sparkles. Of course it is a nucleus and +focus of crime. Every good stone is. They are the devil's pet +baits. In the larger and older jewels every facet may stand for a +bloody deed. This stone is not yet twenty years old. It was found +in the banks of the Amoy River in southern China and is remarkable +in having every characteristic of the carbuncle, save that it is +blue in shade instead of ruby red. In spite of its youth, it has +already a sinister history. There have been two murders, a +vitriol-throwing, a suicide, and several robberies brought about +for the sake of this forty-grain weight of crystallised charcoal. +Who would think that so pretty a toy would be a purveyor to the +gallows and the prison? I'll lock it up in my strong box now and +drop a line to the Countess to say that we have it." + +"Do you think that this man Horner is innocent?" + +"I cannot tell." + +"Well, then, do you imagine that this other one, Henry Baker, had +anything to do with the matter?" + +"It is, I think, much more likely that Henry Baker is an +absolutely innocent man, who had no idea that the bird which he +was carrying was of considerably more value than if it were made +of solid gold. That, however, I shall determine by a very simple +test if we have an answer to our advertisement." + +"And you can do nothing until then?" + +"Nothing." + +"In that case I shall continue my professional round. But I shall +come back in the evening at the hour you have mentioned, for I +should like to see the solution of so tangled a business." + +"Very glad to see you. I dine at seven. There is a woodcock, I +believe. By the way, in view of recent occurrences, perhaps I +ought to ask Mrs. Hudson to examine its crop." + +I had been delayed at a case, and it was a little after half-past +six when I found myself in Baker Street once more. As I +approached the house I saw a tall man in a Scotch bonnet with a +coat which was buttoned up to his chin waiting outside in the +bright semicircle which was thrown from the fanlight. Just as I +arrived the door was opened, and we were shown up together to +Holmes' room. + +"Mr. Henry Baker, I believe," said he, rising from his armchair +and greeting his visitor with the easy air of geniality which he +could so readily assume. "Pray take this chair by the fire, Mr. +Baker. It is a cold night, and I observe that your circulation is +more adapted for summer than for winter. Ah, Watson, you have +just come at the right time. Is that your hat, Mr. Baker?" + +"Yes, sir, that is undoubtedly my hat." + +He was a large man with rounded shoulders, a massive head, and a +broad, intelligent face, sloping down to a pointed beard of +grizzled brown. A touch of red in nose and cheeks, with a slight +tremor of his extended hand, recalled Holmes' surmise as to his +habits. His rusty black frock-coat was buttoned right up in +front, with the collar turned up, and his lank wrists protruded +from his sleeves without a sign of cuff or shirt. He spoke in a +slow staccato fashion, choosing his words with care, and gave the +impression generally of a man of learning and letters who had had +ill-usage at the hands of fortune. + +"We have retained these things for some days," said Holmes, +"because we expected to see an advertisement from you giving your +address. I am at a loss to know now why you did not advertise." + +Our visitor gave a rather shamefaced laugh. "Shillings have not +been so plentiful with me as they once were," he remarked. "I had +no doubt that the gang of roughs who assaulted me had carried off +both my hat and the bird. I did not care to spend more money in a +hopeless attempt at recovering them." + +"Very naturally. By the way, about the bird, we were compelled to +eat it." + +"To eat it!" Our visitor half rose from his chair in his +excitement. + +"Yes, it would have been of no use to anyone had we not done so. +But I presume that this other goose upon the sideboard, which is +about the same weight and perfectly fresh, will answer your +purpose equally well?" + +"Oh, certainly, certainly," answered Mr. Baker with a sigh of +relief. + +"Of course, we still have the feathers, legs, crop, and so on of +your own bird, so if you wish--" + +The man burst into a hearty laugh. "They might be useful to me as +relics of my adventure," said he, "but beyond that I can hardly +see what use the disjecta membra of my late acquaintance are +going to be to me. No, sir, I think that, with your permission, I +will confine my attentions to the excellent bird which I perceive +upon the sideboard." + +Sherlock Holmes glanced sharply across at me with a slight shrug +of his shoulders. + +"There is your hat, then, and there your bird," said he. "By the +way, would it bore you to tell me where you got the other one +from? I am somewhat of a fowl fancier, and I have seldom seen a +better grown goose." + +"Certainly, sir," said Baker, who had risen and tucked his newly +gained property under his arm. "There are a few of us who +frequent the Alpha Inn, near the Museum--we are to be found in +the Museum itself during the day, you understand. This year our +good host, Windigate by name, instituted a goose club, by which, +on consideration of some few pence every week, we were each to +receive a bird at Christmas. My pence were duly paid, and the +rest is familiar to you. I am much indebted to you, sir, for a +Scotch bonnet is fitted neither to my years nor my gravity." With +a comical pomposity of manner he bowed solemnly to both of us and +strode off upon his way. + +"So much for Mr. Henry Baker," said Holmes when he had closed the +door behind him. "It is quite certain that he knows nothing +whatever about the matter. Are you hungry, Watson?" + +"Not particularly." + +"Then I suggest that we turn our dinner into a supper and follow +up this clue while it is still hot." + +"By all means." + +It was a bitter night, so we drew on our ulsters and wrapped +cravats about our throats. Outside, the stars were shining coldly +in a cloudless sky, and the breath of the passers-by blew out +into smoke like so many pistol shots. Our footfalls rang out +crisply and loudly as we swung through the doctors' quarter, +Wimpole Street, Harley Street, and so through Wigmore Street into +Oxford Street. In a quarter of an hour we were in Bloomsbury at +the Alpha Inn, which is a small public-house at the corner of one +of the streets which runs down into Holborn. Holmes pushed open +the door of the private bar and ordered two glasses of beer from +the ruddy-faced, white-aproned landlord. + +"Your beer should be excellent if it is as good as your geese," +said he. + +"My geese!" The man seemed surprised. + +"Yes. I was speaking only half an hour ago to Mr. Henry Baker, +who was a member of your goose club." + +"Ah! yes, I see. But you see, sir, them's not our geese." + +"Indeed! Whose, then?" + +"Well, I got the two dozen from a salesman in Covent Garden." + +"Indeed? I know some of them. Which was it?" + +"Breckinridge is his name." + +"Ah! I don't know him. Well, here's your good health landlord, +and prosperity to your house. Good-night." + +"Now for Mr. Breckinridge," he continued, buttoning up his coat +as we came out into the frosty air. "Remember, Watson that though +we have so homely a thing as a goose at one end of this chain, we +have at the other a man who will certainly get seven years' penal +servitude unless we can establish his innocence. It is possible +that our inquiry may but confirm his guilt; but, in any case, we +have a line of investigation which has been missed by the police, +and which a singular chance has placed in our hands. Let us +follow it out to the bitter end. Faces to the south, then, and +quick march!" + +We passed across Holborn, down Endell Street, and so through a +zigzag of slums to Covent Garden Market. One of the largest +stalls bore the name of Breckinridge upon it, and the proprietor +a horsey-looking man, with a sharp face and trim side-whiskers was +helping a boy to put up the shutters. + +"Good-evening. It's a cold night," said Holmes. + +The salesman nodded and shot a questioning glance at my +companion. + +"Sold out of geese, I see," continued Holmes, pointing at the +bare slabs of marble. + +"Let you have five hundred to-morrow morning." + +"That's no good." + +"Well, there are some on the stall with the gas-flare." + +"Ah, but I was recommended to you." + +"Who by?" + +"The landlord of the Alpha." + +"Oh, yes; I sent him a couple of dozen." + +"Fine birds they were, too. Now where did you get them from?" + +To my surprise the question provoked a burst of anger from the +salesman. + +"Now, then, mister," said he, with his head cocked and his arms +akimbo, "what are you driving at? Let's have it straight, now." + +"It is straight enough. I should like to know who sold you the +geese which you supplied to the Alpha." + +"Well then, I shan't tell you. So now!" + +"Oh, it is a matter of no importance; but I don't know why you +should be so warm over such a trifle." + +"Warm! You'd be as warm, maybe, if you were as pestered as I am. +When I pay good money for a good article there should be an end +of the business; but it's 'Where are the geese?' and 'Who did you +sell the geese to?' and 'What will you take for the geese?' One +would think they were the only geese in the world, to hear the +fuss that is made over them." + +"Well, I have no connection with any other people who have been +making inquiries," said Holmes carelessly. "If you won't tell us +the bet is off, that is all. But I'm always ready to back my +opinion on a matter of fowls, and I have a fiver on it that the +bird I ate is country bred." + +"Well, then, you've lost your fiver, for it's town bred," snapped +the salesman. + +"It's nothing of the kind." + +"I say it is." + +"I don't believe it." + +"D'you think you know more about fowls than I, who have handled +them ever since I was a nipper? I tell you, all those birds that +went to the Alpha were town bred." + +"You'll never persuade me to believe that." + +"Will you bet, then?" + +"It's merely taking your money, for I know that I am right. But +I'll have a sovereign on with you, just to teach you not to be +obstinate." + +The salesman chuckled grimly. "Bring me the books, Bill," said +he. + +The small boy brought round a small thin volume and a great +greasy-backed one, laying them out together beneath the hanging +lamp. + +"Now then, Mr. Cocksure," said the salesman, "I thought that I +was out of geese, but before I finish you'll find that there is +still one left in my shop. You see this little book?" + +"Well?" + +"That's the list of the folk from whom I buy. D'you see? Well, +then, here on this page are the country folk, and the numbers +after their names are where their accounts are in the big ledger. +Now, then! You see this other page in red ink? Well, that is a +list of my town suppliers. Now, look at that third name. Just +read it out to me." + +"Mrs. Oakshott, 117, Brixton Road--249," read Holmes. + +"Quite so. Now turn that up in the ledger." + +Holmes turned to the page indicated. "Here you are, 'Mrs. +Oakshott, 117, Brixton Road, egg and poultry supplier.'" + +"Now, then, what's the last entry?" + +"'December 22nd. Twenty-four geese at 7s. 6d.'" + +"Quite so. There you are. And underneath?" + +"'Sold to Mr. Windigate of the Alpha, at 12s.'" + +"What have you to say now?" + +Sherlock Holmes looked deeply chagrined. He drew a sovereign from +his pocket and threw it down upon the slab, turning away with the +air of a man whose disgust is too deep for words. A few yards off +he stopped under a lamp-post and laughed in the hearty, noiseless +fashion which was peculiar to him. + +"When you see a man with whiskers of that cut and the 'Pink 'un' +protruding out of his pocket, you can always draw him by a bet," +said he. "I daresay that if I had put 100 pounds down in front of +him, that man would not have given me such complete information +as was drawn from him by the idea that he was doing me on a +wager. Well, Watson, we are, I fancy, nearing the end of our +quest, and the only point which remains to be determined is +whether we should go on to this Mrs. Oakshott to-night, or +whether we should reserve it for to-morrow. It is clear from what +that surly fellow said that there are others besides ourselves +who are anxious about the matter, and I should--" + +His remarks were suddenly cut short by a loud hubbub which broke +out from the stall which we had just left. Turning round we saw a +little rat-faced fellow standing in the centre of the circle of +yellow light which was thrown by the swinging lamp, while +Breckinridge, the salesman, framed in the door of his stall, was +shaking his fists fiercely at the cringing figure. + +"I've had enough of you and your geese," he shouted. "I wish you +were all at the devil together. If you come pestering me any more +with your silly talk I'll set the dog at you. You bring Mrs. +Oakshott here and I'll answer her, but what have you to do with +it? Did I buy the geese off you?" + +"No; but one of them was mine all the same," whined the little +man. + +"Well, then, ask Mrs. Oakshott for it." + +"She told me to ask you." + +"Well, you can ask the King of Proosia, for all I care. I've had +enough of it. Get out of this!" He rushed fiercely forward, and +the inquirer flitted away into the darkness. + +"Ha! this may save us a visit to Brixton Road," whispered Holmes. +"Come with me, and we will see what is to be made of this +fellow." Striding through the scattered knots of people who +lounged round the flaring stalls, my companion speedily overtook +the little man and touched him upon the shoulder. He sprang +round, and I could see in the gas-light that every vestige of +colour had been driven from his face. + +"Who are you, then? What do you want?" he asked in a quavering +voice. + +"You will excuse me," said Holmes blandly, "but I could not help +overhearing the questions which you put to the salesman just now. +I think that I could be of assistance to you." + +"You? Who are you? How could you know anything of the matter?" + +"My name is Sherlock Holmes. It is my business to know what other +people don't know." + +"But you can know nothing of this?" + +"Excuse me, I know everything of it. You are endeavouring to +trace some geese which were sold by Mrs. Oakshott, of Brixton +Road, to a salesman named Breckinridge, by him in turn to Mr. +Windigate, of the Alpha, and by him to his club, of which Mr. +Henry Baker is a member." + +"Oh, sir, you are the very man whom I have longed to meet," cried +the little fellow with outstretched hands and quivering fingers. +"I can hardly explain to you how interested I am in this matter." + +Sherlock Holmes hailed a four-wheeler which was passing. "In that +case we had better discuss it in a cosy room rather than in this +wind-swept market-place," said he. "But pray tell me, before we +go farther, who it is that I have the pleasure of assisting." + +The man hesitated for an instant. "My name is John Robinson," he +answered with a sidelong glance. + +"No, no; the real name," said Holmes sweetly. "It is always +awkward doing business with an alias." + +A flush sprang to the white cheeks of the stranger. "Well then," +said he, "my real name is James Ryder." + +"Precisely so. Head attendant at the Hotel Cosmopolitan. Pray +step into the cab, and I shall soon be able to tell you +everything which you would wish to know." + +The little man stood glancing from one to the other of us with +half-frightened, half-hopeful eyes, as one who is not sure +whether he is on the verge of a windfall or of a catastrophe. +Then he stepped into the cab, and in half an hour we were back in +the sitting-room at Baker Street. Nothing had been said during +our drive, but the high, thin breathing of our new companion, and +the claspings and unclaspings of his hands, spoke of the nervous +tension within him. + +"Here we are!" said Holmes cheerily as we filed into the room. +"The fire looks very seasonable in this weather. You look cold, +Mr. Ryder. Pray take the basket-chair. I will just put on my +slippers before we settle this little matter of yours. Now, then! +You want to know what became of those geese?" + +"Yes, sir." + +"Or rather, I fancy, of that goose. It was one bird, I imagine in +which you were interested--white, with a black bar across the +tail." + +Ryder quivered with emotion. "Oh, sir," he cried, "can you tell +me where it went to?" + +"It came here." + +"Here?" + +"Yes, and a most remarkable bird it proved. I don't wonder that +you should take an interest in it. It laid an egg after it was +dead--the bonniest, brightest little blue egg that ever was seen. +I have it here in my museum." + +Our visitor staggered to his feet and clutched the mantelpiece +with his right hand. Holmes unlocked his strong-box and held up +the blue carbuncle, which shone out like a star, with a cold, +brilliant, many-pointed radiance. Ryder stood glaring with a +drawn face, uncertain whether to claim or to disown it. + +"The game's up, Ryder," said Holmes quietly. "Hold up, man, or +you'll be into the fire! Give him an arm back into his chair, +Watson. He's not got blood enough to go in for felony with +impunity. Give him a dash of brandy. So! Now he looks a little +more human. What a shrimp it is, to be sure!" + +For a moment he had staggered and nearly fallen, but the brandy +brought a tinge of colour into his cheeks, and he sat staring +with frightened eyes at his accuser. + +"I have almost every link in my hands, and all the proofs which I +could possibly need, so there is little which you need tell me. +Still, that little may as well be cleared up to make the case +complete. You had heard, Ryder, of this blue stone of the +Countess of Morcar's?" + +"It was Catherine Cusack who told me of it," said he in a +crackling voice. + +"I see--her ladyship's waiting-maid. Well, the temptation of +sudden wealth so easily acquired was too much for you, as it has +been for better men before you; but you were not very scrupulous +in the means you used. It seems to me, Ryder, that there is the +making of a very pretty villain in you. You knew that this man +Horner, the plumber, had been concerned in some such matter +before, and that suspicion would rest the more readily upon him. +What did you do, then? You made some small job in my lady's +room--you and your confederate Cusack--and you managed that he +should be the man sent for. Then, when he had left, you rifled +the jewel-case, raised the alarm, and had this unfortunate man +arrested. You then--" + +Ryder threw himself down suddenly upon the rug and clutched at my +companion's knees. "For God's sake, have mercy!" he shrieked. +"Think of my father! Of my mother! It would break their hearts. I +never went wrong before! I never will again. I swear it. I'll +swear it on a Bible. Oh, don't bring it into court! For Christ's +sake, don't!" + +"Get back into your chair!" said Holmes sternly. "It is very well +to cringe and crawl now, but you thought little enough of this +poor Horner in the dock for a crime of which he knew nothing." + +"I will fly, Mr. Holmes. I will leave the country, sir. Then the +charge against him will break down." + +"Hum! We will talk about that. And now let us hear a true account +of the next act. How came the stone into the goose, and how came +the goose into the open market? Tell us the truth, for there lies +your only hope of safety." + +Ryder passed his tongue over his parched lips. "I will tell you +it just as it happened, sir," said he. "When Horner had been +arrested, it seemed to me that it would be best for me to get +away with the stone at once, for I did not know at what moment +the police might not take it into their heads to search me and my +room. There was no place about the hotel where it would be safe. +I went out, as if on some commission, and I made for my sister's +house. She had married a man named Oakshott, and lived in Brixton +Road, where she fattened fowls for the market. All the way there +every man I met seemed to me to be a policeman or a detective; +and, for all that it was a cold night, the sweat was pouring down +my face before I came to the Brixton Road. My sister asked me +what was the matter, and why I was so pale; but I told her that I +had been upset by the jewel robbery at the hotel. Then I went +into the back yard and smoked a pipe and wondered what it would +be best to do. + +"I had a friend once called Maudsley, who went to the bad, and +has just been serving his time in Pentonville. One day he had met +me, and fell into talk about the ways of thieves, and how they +could get rid of what they stole. I knew that he would be true to +me, for I knew one or two things about him; so I made up my mind +to go right on to Kilburn, where he lived, and take him into my +confidence. He would show me how to turn the stone into money. +But how to get to him in safety? I thought of the agonies I had +gone through in coming from the hotel. I might at any moment be +seized and searched, and there would be the stone in my waistcoat +pocket. I was leaning against the wall at the time and looking at +the geese which were waddling about round my feet, and suddenly +an idea came into my head which showed me how I could beat the +best detective that ever lived. + +"My sister had told me some weeks before that I might have the +pick of her geese for a Christmas present, and I knew that she +was always as good as her word. I would take my goose now, and in +it I would carry my stone to Kilburn. There was a little shed in +the yard, and behind this I drove one of the birds--a fine big +one, white, with a barred tail. I caught it, and prying its bill +open, I thrust the stone down its throat as far as my finger +could reach. The bird gave a gulp, and I felt the stone pass +along its gullet and down into its crop. But the creature flapped +and struggled, and out came my sister to know what was the +matter. As I turned to speak to her the brute broke loose and +fluttered off among the others. + +"'Whatever were you doing with that bird, Jem?' says she. + +"'Well,' said I, 'you said you'd give me one for Christmas, and I +was feeling which was the fattest.' + +"'Oh,' says she, 'we've set yours aside for you--Jem's bird, we +call it. It's the big white one over yonder. There's twenty-six +of them, which makes one for you, and one for us, and two dozen +for the market.' + +"'Thank you, Maggie,' says I; 'but if it is all the same to you, +I'd rather have that one I was handling just now.' + +"'The other is a good three pound heavier,' said she, 'and we +fattened it expressly for you.' + +"'Never mind. I'll have the other, and I'll take it now,' said I. + +"'Oh, just as you like,' said she, a little huffed. 'Which is it +you want, then?' + +"'That white one with the barred tail, right in the middle of the +flock.' + +"'Oh, very well. Kill it and take it with you.' + +"Well, I did what she said, Mr. Holmes, and I carried the bird +all the way to Kilburn. I told my pal what I had done, for he was +a man that it was easy to tell a thing like that to. He laughed +until he choked, and we got a knife and opened the goose. My +heart turned to water, for there was no sign of the stone, and I +knew that some terrible mistake had occurred. I left the bird, +rushed back to my sister's, and hurried into the back yard. There +was not a bird to be seen there. + +"'Where are they all, Maggie?' I cried. + +"'Gone to the dealer's, Jem.' + +"'Which dealer's?' + +"'Breckinridge, of Covent Garden.' + +"'But was there another with a barred tail?' I asked, 'the same +as the one I chose?' + +"'Yes, Jem; there were two barred-tailed ones, and I could never +tell them apart.' + +"Well, then, of course I saw it all, and I ran off as hard as my +feet would carry me to this man Breckinridge; but he had sold the +lot at once, and not one word would he tell me as to where they +had gone. You heard him yourselves to-night. Well, he has always +answered me like that. My sister thinks that I am going mad. +Sometimes I think that I am myself. And now--and now I am myself +a branded thief, without ever having touched the wealth for which +I sold my character. God help me! God help me!" He burst into +convulsive sobbing, with his face buried in his hands. + +There was a long silence, broken only by his heavy breathing and +by the measured tapping of Sherlock Holmes' finger-tips upon the +edge of the table. Then my friend rose and threw open the door. + +"Get out!" said he. + +"What, sir! Oh, Heaven bless you!" + +"No more words. Get out!" + +And no more words were needed. There was a rush, a clatter upon +the stairs, the bang of a door, and the crisp rattle of running +footfalls from the street. + +"After all, Watson," said Holmes, reaching up his hand for his +clay pipe, "I am not retained by the police to supply their +deficiencies. If Horner were in danger it would be another thing; +but this fellow will not appear against him, and the case must +collapse. I suppose that I am commuting a felony, but it is just +possible that I am saving a soul. This fellow will not go wrong +again; he is too terribly frightened. Send him to gaol now, and +you make him a gaol-bird for life. Besides, it is the season of +forgiveness. Chance has put in our way a most singular and +whimsical problem, and its solution is its own reward. If you +will have the goodness to touch the bell, Doctor, we will begin +another investigation, in which, also a bird will be the chief +feature." + + + +VIII. THE ADVENTURE OF THE SPECKLED BAND + +On glancing over my notes of the seventy odd cases in which I +have during the last eight years studied the methods of my friend +Sherlock Holmes, I find many tragic, some comic, a large number +merely strange, but none commonplace; for, working as he did +rather for the love of his art than for the acquirement of +wealth, he refused to associate himself with any investigation +which did not tend towards the unusual, and even the fantastic. +Of all these varied cases, however, I cannot recall any which +presented more singular features than that which was associated +with the well-known Surrey family of the Roylotts of Stoke Moran. +The events in question occurred in the early days of my +association with Holmes, when we were sharing rooms as bachelors +in Baker Street. It is possible that I might have placed them +upon record before, but a promise of secrecy was made at the +time, from which I have only been freed during the last month by +the untimely death of the lady to whom the pledge was given. It +is perhaps as well that the facts should now come to light, for I +have reasons to know that there are widespread rumours as to the +death of Dr. Grimesby Roylott which tend to make the matter even +more terrible than the truth. + +It was early in April in the year '83 that I woke one morning to +find Sherlock Holmes standing, fully dressed, by the side of my +bed. He was a late riser, as a rule, and as the clock on the +mantelpiece showed me that it was only a quarter-past seven, I +blinked up at him in some surprise, and perhaps just a little +resentment, for I was myself regular in my habits. + +"Very sorry to knock you up, Watson," said he, "but it's the +common lot this morning. Mrs. Hudson has been knocked up, she +retorted upon me, and I on you." + +"What is it, then--a fire?" + +"No; a client. It seems that a young lady has arrived in a +considerable state of excitement, who insists upon seeing me. She +is waiting now in the sitting-room. Now, when young ladies wander +about the metropolis at this hour of the morning, and knock +sleepy people up out of their beds, I presume that it is +something very pressing which they have to communicate. Should it +prove to be an interesting case, you would, I am sure, wish to +follow it from the outset. I thought, at any rate, that I should +call you and give you the chance." + +"My dear fellow, I would not miss it for anything." + +I had no keener pleasure than in following Holmes in his +professional investigations, and in admiring the rapid +deductions, as swift as intuitions, and yet always founded on a +logical basis with which he unravelled the problems which were +submitted to him. I rapidly threw on my clothes and was ready in +a few minutes to accompany my friend down to the sitting-room. A +lady dressed in black and heavily veiled, who had been sitting in +the window, rose as we entered. + +"Good-morning, madam," said Holmes cheerily. "My name is Sherlock +Holmes. This is my intimate friend and associate, Dr. Watson, +before whom you can speak as freely as before myself. Ha! I am +glad to see that Mrs. Hudson has had the good sense to light the +fire. Pray draw up to it, and I shall order you a cup of hot +coffee, for I observe that you are shivering." + +"It is not cold which makes me shiver," said the woman in a low +voice, changing her seat as requested. + +"What, then?" + +"It is fear, Mr. Holmes. It is terror." She raised her veil as +she spoke, and we could see that she was indeed in a pitiable +state of agitation, her face all drawn and grey, with restless +frightened eyes, like those of some hunted animal. Her features +and figure were those of a woman of thirty, but her hair was shot +with premature grey, and her expression was weary and haggard. +Sherlock Holmes ran her over with one of his quick, +all-comprehensive glances. + +"You must not fear," said he soothingly, bending forward and +patting her forearm. "We shall soon set matters right, I have no +doubt. You have come in by train this morning, I see." + +"You know me, then?" + +"No, but I observe the second half of a return ticket in the palm +of your left glove. You must have started early, and yet you had +a good drive in a dog-cart, along heavy roads, before you reached +the station." + +The lady gave a violent start and stared in bewilderment at my +companion. + +"There is no mystery, my dear madam," said he, smiling. "The left +arm of your jacket is spattered with mud in no less than seven +places. The marks are perfectly fresh. There is no vehicle save a +dog-cart which throws up mud in that way, and then only when you +sit on the left-hand side of the driver." + +"Whatever your reasons may be, you are perfectly correct," said +she. "I started from home before six, reached Leatherhead at +twenty past, and came in by the first train to Waterloo. Sir, I +can stand this strain no longer; I shall go mad if it continues. +I have no one to turn to--none, save only one, who cares for me, +and he, poor fellow, can be of little aid. I have heard of you, +Mr. Holmes; I have heard of you from Mrs. Farintosh, whom you +helped in the hour of her sore need. It was from her that I had +your address. Oh, sir, do you not think that you could help me, +too, and at least throw a little light through the dense darkness +which surrounds me? At present it is out of my power to reward +you for your services, but in a month or six weeks I shall be +married, with the control of my own income, and then at least you +shall not find me ungrateful." + +Holmes turned to his desk and, unlocking it, drew out a small +case-book, which he consulted. + +"Farintosh," said he. "Ah yes, I recall the case; it was +concerned with an opal tiara. I think it was before your time, +Watson. I can only say, madam, that I shall be happy to devote +the same care to your case as I did to that of your friend. As to +reward, my profession is its own reward; but you are at liberty +to defray whatever expenses I may be put to, at the time which +suits you best. And now I beg that you will lay before us +everything that may help us in forming an opinion upon the +matter." + +"Alas!" replied our visitor, "the very horror of my situation +lies in the fact that my fears are so vague, and my suspicions +depend so entirely upon small points, which might seem trivial to +another, that even he to whom of all others I have a right to +look for help and advice looks upon all that I tell him about it +as the fancies of a nervous woman. He does not say so, but I can +read it from his soothing answers and averted eyes. But I have +heard, Mr. Holmes, that you can see deeply into the manifold +wickedness of the human heart. You may advise me how to walk amid +the dangers which encompass me." + +"I am all attention, madam." + +"My name is Helen Stoner, and I am living with my stepfather, who +is the last survivor of one of the oldest Saxon families in +England, the Roylotts of Stoke Moran, on the western border of +Surrey." + +Holmes nodded his head. "The name is familiar to me," said he. + +"The family was at one time among the richest in England, and the +estates extended over the borders into Berkshire in the north, +and Hampshire in the west. In the last century, however, four +successive heirs were of a dissolute and wasteful disposition, +and the family ruin was eventually completed by a gambler in the +days of the Regency. Nothing was left save a few acres of ground, +and the two-hundred-year-old house, which is itself crushed under +a heavy mortgage. The last squire dragged out his existence +there, living the horrible life of an aristocratic pauper; but +his only son, my stepfather, seeing that he must adapt himself to +the new conditions, obtained an advance from a relative, which +enabled him to take a medical degree and went out to Calcutta, +where, by his professional skill and his force of character, he +established a large practice. In a fit of anger, however, caused +by some robberies which had been perpetrated in the house, he +beat his native butler to death and narrowly escaped a capital +sentence. As it was, he suffered a long term of imprisonment and +afterwards returned to England a morose and disappointed man. + +"When Dr. Roylott was in India he married my mother, Mrs. Stoner, +the young widow of Major-General Stoner, of the Bengal Artillery. +My sister Julia and I were twins, and we were only two years old +at the time of my mother's re-marriage. She had a considerable +sum of money--not less than 1000 pounds a year--and this she +bequeathed to Dr. Roylott entirely while we resided with him, +with a provision that a certain annual sum should be allowed to +each of us in the event of our marriage. Shortly after our return +to England my mother died--she was killed eight years ago in a +railway accident near Crewe. Dr. Roylott then abandoned his +attempts to establish himself in practice in London and took us +to live with him in the old ancestral house at Stoke Moran. The +money which my mother had left was enough for all our wants, and +there seemed to be no obstacle to our happiness. + +"But a terrible change came over our stepfather about this time. +Instead of making friends and exchanging visits with our +neighbours, who had at first been overjoyed to see a Roylott of +Stoke Moran back in the old family seat, he shut himself up in +his house and seldom came out save to indulge in ferocious +quarrels with whoever might cross his path. Violence of temper +approaching to mania has been hereditary in the men of the +family, and in my stepfather's case it had, I believe, been +intensified by his long residence in the tropics. A series of +disgraceful brawls took place, two of which ended in the +police-court, until at last he became the terror of the village, +and the folks would fly at his approach, for he is a man of +immense strength, and absolutely uncontrollable in his anger. + +"Last week he hurled the local blacksmith over a parapet into a +stream, and it was only by paying over all the money which I +could gather together that I was able to avert another public +exposure. He had no friends at all save the wandering gipsies, +and he would give these vagabonds leave to encamp upon the few +acres of bramble-covered land which represent the family estate, +and would accept in return the hospitality of their tents, +wandering away with them sometimes for weeks on end. He has a +passion also for Indian animals, which are sent over to him by a +correspondent, and he has at this moment a cheetah and a baboon, +which wander freely over his grounds and are feared by the +villagers almost as much as their master. + +"You can imagine from what I say that my poor sister Julia and I +had no great pleasure in our lives. No servant would stay with +us, and for a long time we did all the work of the house. She was +but thirty at the time of her death, and yet her hair had already +begun to whiten, even as mine has." + +"Your sister is dead, then?" + +"She died just two years ago, and it is of her death that I wish +to speak to you. You can understand that, living the life which I +have described, we were little likely to see anyone of our own +age and position. We had, however, an aunt, my mother's maiden +sister, Miss Honoria Westphail, who lives near Harrow, and we +were occasionally allowed to pay short visits at this lady's +house. Julia went there at Christmas two years ago, and met there +a half-pay major of marines, to whom she became engaged. My +stepfather learned of the engagement when my sister returned and +offered no objection to the marriage; but within a fortnight of +the day which had been fixed for the wedding, the terrible event +occurred which has deprived me of my only companion." + +Sherlock Holmes had been leaning back in his chair with his eyes +closed and his head sunk in a cushion, but he half opened his +lids now and glanced across at his visitor. + +"Pray be precise as to details," said he. + +"It is easy for me to be so, for every event of that dreadful +time is seared into my memory. The manor-house is, as I have +already said, very old, and only one wing is now inhabited. The +bedrooms in this wing are on the ground floor, the sitting-rooms +being in the central block of the buildings. Of these bedrooms +the first is Dr. Roylott's, the second my sister's, and the third +my own. There is no communication between them, but they all open +out into the same corridor. Do I make myself plain?" + +"Perfectly so." + +"The windows of the three rooms open out upon the lawn. That +fatal night Dr. Roylott had gone to his room early, though we +knew that he had not retired to rest, for my sister was troubled +by the smell of the strong Indian cigars which it was his custom +to smoke. She left her room, therefore, and came into mine, where +she sat for some time, chatting about her approaching wedding. At +eleven o'clock she rose to leave me, but she paused at the door +and looked back. + +"'Tell me, Helen,' said she, 'have you ever heard anyone whistle +in the dead of the night?' + +"'Never,' said I. + +"'I suppose that you could not possibly whistle, yourself, in +your sleep?' + +"'Certainly not. But why?' + +"'Because during the last few nights I have always, about three +in the morning, heard a low, clear whistle. I am a light sleeper, +and it has awakened me. I cannot tell where it came from--perhaps +from the next room, perhaps from the lawn. I thought that I would +just ask you whether you had heard it.' + +"'No, I have not. It must be those wretched gipsies in the +plantation.' + +"'Very likely. And yet if it were on the lawn, I wonder that you +did not hear it also.' + +"'Ah, but I sleep more heavily than you.' + +"'Well, it is of no great consequence, at any rate.' She smiled +back at me, closed my door, and a few moments later I heard her +key turn in the lock." + +"Indeed," said Holmes. "Was it your custom always to lock +yourselves in at night?" + +"Always." + +"And why?" + +"I think that I mentioned to you that the doctor kept a cheetah +and a baboon. We had no feeling of security unless our doors were +locked." + +"Quite so. Pray proceed with your statement." + +"I could not sleep that night. A vague feeling of impending +misfortune impressed me. My sister and I, you will recollect, +were twins, and you know how subtle are the links which bind two +souls which are so closely allied. It was a wild night. The wind +was howling outside, and the rain was beating and splashing +against the windows. Suddenly, amid all the hubbub of the gale, +there burst forth the wild scream of a terrified woman. I knew +that it was my sister's voice. I sprang from my bed, wrapped a +shawl round me, and rushed into the corridor. As I opened my door +I seemed to hear a low whistle, such as my sister described, and +a few moments later a clanging sound, as if a mass of metal had +fallen. As I ran down the passage, my sister's door was unlocked, +and revolved slowly upon its hinges. I stared at it +horror-stricken, not knowing what was about to issue from it. By +the light of the corridor-lamp I saw my sister appear at the +opening, her face blanched with terror, her hands groping for +help, her whole figure swaying to and fro like that of a +drunkard. I ran to her and threw my arms round her, but at that +moment her knees seemed to give way and she fell to the ground. +She writhed as one who is in terrible pain, and her limbs were +dreadfully convulsed. At first I thought that she had not +recognised me, but as I bent over her she suddenly shrieked out +in a voice which I shall never forget, 'Oh, my God! Helen! It was +the band! The speckled band!' There was something else which she +would fain have said, and she stabbed with her finger into the +air in the direction of the doctor's room, but a fresh convulsion +seized her and choked her words. I rushed out, calling loudly for +my stepfather, and I met him hastening from his room in his +dressing-gown. When he reached my sister's side she was +unconscious, and though he poured brandy down her throat and sent +for medical aid from the village, all efforts were in vain, for +she slowly sank and died without having recovered her +consciousness. Such was the dreadful end of my beloved sister." + +"One moment," said Holmes, "are you sure about this whistle and +metallic sound? Could you swear to it?" + +"That was what the county coroner asked me at the inquiry. It is +my strong impression that I heard it, and yet, among the crash of +the gale and the creaking of an old house, I may possibly have +been deceived." + +"Was your sister dressed?" + +"No, she was in her night-dress. In her right hand was found the +charred stump of a match, and in her left a match-box." + +"Showing that she had struck a light and looked about her when +the alarm took place. That is important. And what conclusions did +the coroner come to?" + +"He investigated the case with great care, for Dr. Roylott's +conduct had long been notorious in the county, but he was unable +to find any satisfactory cause of death. My evidence showed that +the door had been fastened upon the inner side, and the windows +were blocked by old-fashioned shutters with broad iron bars, +which were secured every night. The walls were carefully sounded, +and were shown to be quite solid all round, and the flooring was +also thoroughly examined, with the same result. The chimney is +wide, but is barred up by four large staples. It is certain, +therefore, that my sister was quite alone when she met her end. +Besides, there were no marks of any violence upon her." + +"How about poison?" + +"The doctors examined her for it, but without success." + +"What do you think that this unfortunate lady died of, then?" + +"It is my belief that she died of pure fear and nervous shock, +though what it was that frightened her I cannot imagine." + +"Were there gipsies in the plantation at the time?" + +"Yes, there are nearly always some there." + +"Ah, and what did you gather from this allusion to a band--a +speckled band?" + +"Sometimes I have thought that it was merely the wild talk of +delirium, sometimes that it may have referred to some band of +people, perhaps to these very gipsies in the plantation. I do not +know whether the spotted handkerchiefs which so many of them wear +over their heads might have suggested the strange adjective which +she used." + +Holmes shook his head like a man who is far from being satisfied. + +"These are very deep waters," said he; "pray go on with your +narrative." + +"Two years have passed since then, and my life has been until +lately lonelier than ever. A month ago, however, a dear friend, +whom I have known for many years, has done me the honour to ask +my hand in marriage. His name is Armitage--Percy Armitage--the +second son of Mr. Armitage, of Crane Water, near Reading. My +stepfather has offered no opposition to the match, and we are to +be married in the course of the spring. Two days ago some repairs +were started in the west wing of the building, and my bedroom +wall has been pierced, so that I have had to move into the +chamber in which my sister died, and to sleep in the very bed in +which she slept. Imagine, then, my thrill of terror when last +night, as I lay awake, thinking over her terrible fate, I +suddenly heard in the silence of the night the low whistle which +had been the herald of her own death. I sprang up and lit the +lamp, but nothing was to be seen in the room. I was too shaken to +go to bed again, however, so I dressed, and as soon as it was +daylight I slipped down, got a dog-cart at the Crown Inn, which +is opposite, and drove to Leatherhead, from whence I have come on +this morning with the one object of seeing you and asking your +advice." + +"You have done wisely," said my friend. "But have you told me +all?" + +"Yes, all." + +"Miss Roylott, you have not. You are screening your stepfather." + +"Why, what do you mean?" + +For answer Holmes pushed back the frill of black lace which +fringed the hand that lay upon our visitor's knee. Five little +livid spots, the marks of four fingers and a thumb, were printed +upon the white wrist. + +"You have been cruelly used," said Holmes. + +The lady coloured deeply and covered over her injured wrist. "He +is a hard man," she said, "and perhaps he hardly knows his own +strength." + +There was a long silence, during which Holmes leaned his chin +upon his hands and stared into the crackling fire. + +"This is a very deep business," he said at last. "There are a +thousand details which I should desire to know before I decide +upon our course of action. Yet we have not a moment to lose. If +we were to come to Stoke Moran to-day, would it be possible for +us to see over these rooms without the knowledge of your +stepfather?" + +"As it happens, he spoke of coming into town to-day upon some +most important business. It is probable that he will be away all +day, and that there would be nothing to disturb you. We have a +housekeeper now, but she is old and foolish, and I could easily +get her out of the way." + +"Excellent. You are not averse to this trip, Watson?" + +"By no means." + +"Then we shall both come. What are you going to do yourself?" + +"I have one or two things which I would wish to do now that I am +in town. But I shall return by the twelve o'clock train, so as to +be there in time for your coming." + +"And you may expect us early in the afternoon. I have myself some +small business matters to attend to. Will you not wait and +breakfast?" + +"No, I must go. My heart is lightened already since I have +confided my trouble to you. I shall look forward to seeing you +again this afternoon." She dropped her thick black veil over her +face and glided from the room. + +"And what do you think of it all, Watson?" asked Sherlock Holmes, +leaning back in his chair. + +"It seems to me to be a most dark and sinister business." + +"Dark enough and sinister enough." + +"Yet if the lady is correct in saying that the flooring and walls +are sound, and that the door, window, and chimney are impassable, +then her sister must have been undoubtedly alone when she met her +mysterious end." + +"What becomes, then, of these nocturnal whistles, and what of the +very peculiar words of the dying woman?" + +"I cannot think." + +"When you combine the ideas of whistles at night, the presence of +a band of gipsies who are on intimate terms with this old doctor, +the fact that we have every reason to believe that the doctor has +an interest in preventing his stepdaughter's marriage, the dying +allusion to a band, and, finally, the fact that Miss Helen Stoner +heard a metallic clang, which might have been caused by one of +those metal bars that secured the shutters falling back into its +place, I think that there is good ground to think that the +mystery may be cleared along those lines." + +"But what, then, did the gipsies do?" + +"I cannot imagine." + +"I see many objections to any such theory." + +"And so do I. It is precisely for that reason that we are going +to Stoke Moran this day. I want to see whether the objections are +fatal, or if they may be explained away. But what in the name of +the devil!" + +The ejaculation had been drawn from my companion by the fact that +our door had been suddenly dashed open, and that a huge man had +framed himself in the aperture. His costume was a peculiar +mixture of the professional and of the agricultural, having a +black top-hat, a long frock-coat, and a pair of high gaiters, +with a hunting-crop swinging in his hand. So tall was he that his +hat actually brushed the cross bar of the doorway, and his +breadth seemed to span it across from side to side. A large face, +seared with a thousand wrinkles, burned yellow with the sun, and +marked with every evil passion, was turned from one to the other +of us, while his deep-set, bile-shot eyes, and his high, thin, +fleshless nose, gave him somewhat the resemblance to a fierce old +bird of prey. + +"Which of you is Holmes?" asked this apparition. + +"My name, sir; but you have the advantage of me," said my +companion quietly. + +"I am Dr. Grimesby Roylott, of Stoke Moran." + +"Indeed, Doctor," said Holmes blandly. "Pray take a seat." + +"I will do nothing of the kind. My stepdaughter has been here. I +have traced her. What has she been saying to you?" + +"It is a little cold for the time of the year," said Holmes. + +"What has she been saying to you?" screamed the old man +furiously. + +"But I have heard that the crocuses promise well," continued my +companion imperturbably. + +"Ha! You put me off, do you?" said our new visitor, taking a step +forward and shaking his hunting-crop. "I know you, you scoundrel! +I have heard of you before. You are Holmes, the meddler." + +My friend smiled. + +"Holmes, the busybody!" + +His smile broadened. + +"Holmes, the Scotland Yard Jack-in-office!" + +Holmes chuckled heartily. "Your conversation is most +entertaining," said he. "When you go out close the door, for +there is a decided draught." + +"I will go when I have said my say. Don't you dare to meddle with +my affairs. I know that Miss Stoner has been here. I traced her! +I am a dangerous man to fall foul of! See here." He stepped +swiftly forward, seized the poker, and bent it into a curve with +his huge brown hands. + +"See that you keep yourself out of my grip," he snarled, and +hurling the twisted poker into the fireplace he strode out of the +room. + +"He seems a very amiable person," said Holmes, laughing. "I am +not quite so bulky, but if he had remained I might have shown him +that my grip was not much more feeble than his own." As he spoke +he picked up the steel poker and, with a sudden effort, +straightened it out again. + +"Fancy his having the insolence to confound me with the official +detective force! This incident gives zest to our investigation, +however, and I only trust that our little friend will not suffer +from her imprudence in allowing this brute to trace her. And now, +Watson, we shall order breakfast, and afterwards I shall walk +down to Doctors' Commons, where I hope to get some data which may +help us in this matter." + + +It was nearly one o'clock when Sherlock Holmes returned from his +excursion. He held in his hand a sheet of blue paper, scrawled +over with notes and figures. + +"I have seen the will of the deceased wife," said he. "To +determine its exact meaning I have been obliged to work out the +present prices of the investments with which it is concerned. The +total income, which at the time of the wife's death was little +short of 1100 pounds, is now, through the fall in agricultural +prices, not more than 750 pounds. Each daughter can claim an +income of 250 pounds, in case of marriage. It is evident, +therefore, that if both girls had married, this beauty would have +had a mere pittance, while even one of them would cripple him to +a very serious extent. My morning's work has not been wasted, +since it has proved that he has the very strongest motives for +standing in the way of anything of the sort. And now, Watson, +this is too serious for dawdling, especially as the old man is +aware that we are interesting ourselves in his affairs; so if you +are ready, we shall call a cab and drive to Waterloo. I should be +very much obliged if you would slip your revolver into your +pocket. An Eley's No. 2 is an excellent argument with gentlemen +who can twist steel pokers into knots. That and a tooth-brush +are, I think, all that we need." + +At Waterloo we were fortunate in catching a train for +Leatherhead, where we hired a trap at the station inn and drove +for four or five miles through the lovely Surrey lanes. It was a +perfect day, with a bright sun and a few fleecy clouds in the +heavens. The trees and wayside hedges were just throwing out +their first green shoots, and the air was full of the pleasant +smell of the moist earth. To me at least there was a strange +contrast between the sweet promise of the spring and this +sinister quest upon which we were engaged. My companion sat in +the front of the trap, his arms folded, his hat pulled down over +his eyes, and his chin sunk upon his breast, buried in the +deepest thought. Suddenly, however, he started, tapped me on the +shoulder, and pointed over the meadows. + +"Look there!" said he. + +A heavily timbered park stretched up in a gentle slope, +thickening into a grove at the highest point. From amid the +branches there jutted out the grey gables and high roof-tree of a +very old mansion. + +"Stoke Moran?" said he. + +"Yes, sir, that be the house of Dr. Grimesby Roylott," remarked +the driver. + +"There is some building going on there," said Holmes; "that is +where we are going." + +"There's the village," said the driver, pointing to a cluster of +roofs some distance to the left; "but if you want to get to the +house, you'll find it shorter to get over this stile, and so by +the foot-path over the fields. There it is, where the lady is +walking." + +"And the lady, I fancy, is Miss Stoner," observed Holmes, shading +his eyes. "Yes, I think we had better do as you suggest." + +We got off, paid our fare, and the trap rattled back on its way +to Leatherhead. + +"I thought it as well," said Holmes as we climbed the stile, +"that this fellow should think we had come here as architects, or +on some definite business. It may stop his gossip. +Good-afternoon, Miss Stoner. You see that we have been as good as +our word." + +Our client of the morning had hurried forward to meet us with a +face which spoke her joy. "I have been waiting so eagerly for +you," she cried, shaking hands with us warmly. "All has turned +out splendidly. Dr. Roylott has gone to town, and it is unlikely +that he will be back before evening." + +"We have had the pleasure of making the doctor's acquaintance," +said Holmes, and in a few words he sketched out what had +occurred. Miss Stoner turned white to the lips as she listened. + +"Good heavens!" she cried, "he has followed me, then." + +"So it appears." + +"He is so cunning that I never know when I am safe from him. What +will he say when he returns?" + +"He must guard himself, for he may find that there is someone +more cunning than himself upon his track. You must lock yourself +up from him to-night. If he is violent, we shall take you away to +your aunt's at Harrow. Now, we must make the best use of our +time, so kindly take us at once to the rooms which we are to +examine." + +The building was of grey, lichen-blotched stone, with a high +central portion and two curving wings, like the claws of a crab, +thrown out on each side. In one of these wings the windows were +broken and blocked with wooden boards, while the roof was partly +caved in, a picture of ruin. The central portion was in little +better repair, but the right-hand block was comparatively modern, +and the blinds in the windows, with the blue smoke curling up +from the chimneys, showed that this was where the family resided. +Some scaffolding had been erected against the end wall, and the +stone-work had been broken into, but there were no signs of any +workmen at the moment of our visit. Holmes walked slowly up and +down the ill-trimmed lawn and examined with deep attention the +outsides of the windows. + +"This, I take it, belongs to the room in which you used to sleep, +the centre one to your sister's, and the one next to the main +building to Dr. Roylott's chamber?" + +"Exactly so. But I am now sleeping in the middle one." + +"Pending the alterations, as I understand. By the way, there does +not seem to be any very pressing need for repairs at that end +wall." + +"There were none. I believe that it was an excuse to move me from +my room." + +"Ah! that is suggestive. Now, on the other side of this narrow +wing runs the corridor from which these three rooms open. There +are windows in it, of course?" + +"Yes, but very small ones. Too narrow for anyone to pass +through." + +"As you both locked your doors at night, your rooms were +unapproachable from that side. Now, would you have the kindness +to go into your room and bar your shutters?" + +Miss Stoner did so, and Holmes, after a careful examination +through the open window, endeavoured in every way to force the +shutter open, but without success. There was no slit through +which a knife could be passed to raise the bar. Then with his +lens he tested the hinges, but they were of solid iron, built +firmly into the massive masonry. "Hum!" said he, scratching his +chin in some perplexity, "my theory certainly presents some +difficulties. No one could pass these shutters if they were +bolted. Well, we shall see if the inside throws any light upon +the matter." + +A small side door led into the whitewashed corridor from which +the three bedrooms opened. Holmes refused to examine the third +chamber, so we passed at once to the second, that in which Miss +Stoner was now sleeping, and in which her sister had met with her +fate. It was a homely little room, with a low ceiling and a +gaping fireplace, after the fashion of old country-houses. A +brown chest of drawers stood in one corner, a narrow +white-counterpaned bed in another, and a dressing-table on the +left-hand side of the window. These articles, with two small +wicker-work chairs, made up all the furniture in the room save +for a square of Wilton carpet in the centre. The boards round and +the panelling of the walls were of brown, worm-eaten oak, so old +and discoloured that it may have dated from the original building +of the house. Holmes drew one of the chairs into a corner and sat +silent, while his eyes travelled round and round and up and down, +taking in every detail of the apartment. + +"Where does that bell communicate with?" he asked at last +pointing to a thick bell-rope which hung down beside the bed, the +tassel actually lying upon the pillow. + +"It goes to the housekeeper's room." + +"It looks newer than the other things?" + +"Yes, it was only put there a couple of years ago." + +"Your sister asked for it, I suppose?" + +"No, I never heard of her using it. We used always to get what we +wanted for ourselves." + +"Indeed, it seemed unnecessary to put so nice a bell-pull there. +You will excuse me for a few minutes while I satisfy myself as to +this floor." He threw himself down upon his face with his lens in +his hand and crawled swiftly backward and forward, examining +minutely the cracks between the boards. Then he did the same with +the wood-work with which the chamber was panelled. Finally he +walked over to the bed and spent some time in staring at it and +in running his eye up and down the wall. Finally he took the +bell-rope in his hand and gave it a brisk tug. + +"Why, it's a dummy," said he. + +"Won't it ring?" + +"No, it is not even attached to a wire. This is very interesting. +You can see now that it is fastened to a hook just above where +the little opening for the ventilator is." + +"How very absurd! I never noticed that before." + +"Very strange!" muttered Holmes, pulling at the rope. "There are +one or two very singular points about this room. For example, +what a fool a builder must be to open a ventilator into another +room, when, with the same trouble, he might have communicated +with the outside air!" + +"That is also quite modern," said the lady. + +"Done about the same time as the bell-rope?" remarked Holmes. + +"Yes, there were several little changes carried out about that +time." + +"They seem to have been of a most interesting character--dummy +bell-ropes, and ventilators which do not ventilate. With your +permission, Miss Stoner, we shall now carry our researches into +the inner apartment." + +Dr. Grimesby Roylott's chamber was larger than that of his +step-daughter, but was as plainly furnished. A camp-bed, a small +wooden shelf full of books, mostly of a technical character, an +armchair beside the bed, a plain wooden chair against the wall, a +round table, and a large iron safe were the principal things +which met the eye. Holmes walked slowly round and examined each +and all of them with the keenest interest. + +"What's in here?" he asked, tapping the safe. + +"My stepfather's business papers." + +"Oh! you have seen inside, then?" + +"Only once, some years ago. I remember that it was full of +papers." + +"There isn't a cat in it, for example?" + +"No. What a strange idea!" + +"Well, look at this!" He took up a small saucer of milk which +stood on the top of it. + +"No; we don't keep a cat. But there is a cheetah and a baboon." + +"Ah, yes, of course! Well, a cheetah is just a big cat, and yet a +saucer of milk does not go very far in satisfying its wants, I +daresay. There is one point which I should wish to determine." He +squatted down in front of the wooden chair and examined the seat +of it with the greatest attention. + +"Thank you. That is quite settled," said he, rising and putting +his lens in his pocket. "Hullo! Here is something interesting!" + +The object which had caught his eye was a small dog lash hung on +one corner of the bed. The lash, however, was curled upon itself +and tied so as to make a loop of whipcord. + +"What do you make of that, Watson?" + +"It's a common enough lash. But I don't know why it should be +tied." + +"That is not quite so common, is it? Ah, me! it's a wicked world, +and when a clever man turns his brains to crime it is the worst +of all. I think that I have seen enough now, Miss Stoner, and +with your permission we shall walk out upon the lawn." + +I had never seen my friend's face so grim or his brow so dark as +it was when we turned from the scene of this investigation. We +had walked several times up and down the lawn, neither Miss +Stoner nor myself liking to break in upon his thoughts before he +roused himself from his reverie. + +"It is very essential, Miss Stoner," said he, "that you should +absolutely follow my advice in every respect." + +"I shall most certainly do so." + +"The matter is too serious for any hesitation. Your life may +depend upon your compliance." + +"I assure you that I am in your hands." + +"In the first place, both my friend and I must spend the night in +your room." + +Both Miss Stoner and I gazed at him in astonishment. + +"Yes, it must be so. Let me explain. I believe that that is the +village inn over there?" + +"Yes, that is the Crown." + +"Very good. Your windows would be visible from there?" + +"Certainly." + +"You must confine yourself to your room, on pretence of a +headache, when your stepfather comes back. Then when you hear him +retire for the night, you must open the shutters of your window, +undo the hasp, put your lamp there as a signal to us, and then +withdraw quietly with everything which you are likely to want +into the room which you used to occupy. I have no doubt that, in +spite of the repairs, you could manage there for one night." + +"Oh, yes, easily." + +"The rest you will leave in our hands." + +"But what will you do?" + +"We shall spend the night in your room, and we shall investigate +the cause of this noise which has disturbed you." + +"I believe, Mr. Holmes, that you have already made up your mind," +said Miss Stoner, laying her hand upon my companion's sleeve. + +"Perhaps I have." + +"Then, for pity's sake, tell me what was the cause of my sister's +death." + +"I should prefer to have clearer proofs before I speak." + +"You can at least tell me whether my own thought is correct, and +if she died from some sudden fright." + +"No, I do not think so. I think that there was probably some more +tangible cause. And now, Miss Stoner, we must leave you for if +Dr. Roylott returned and saw us our journey would be in vain. +Good-bye, and be brave, for if you will do what I have told you, +you may rest assured that we shall soon drive away the dangers +that threaten you." + +Sherlock Holmes and I had no difficulty in engaging a bedroom and +sitting-room at the Crown Inn. They were on the upper floor, and +from our window we could command a view of the avenue gate, and +of the inhabited wing of Stoke Moran Manor House. At dusk we saw +Dr. Grimesby Roylott drive past, his huge form looming up beside +the little figure of the lad who drove him. The boy had some +slight difficulty in undoing the heavy iron gates, and we heard +the hoarse roar of the doctor's voice and saw the fury with which +he shook his clinched fists at him. The trap drove on, and a few +minutes later we saw a sudden light spring up among the trees as +the lamp was lit in one of the sitting-rooms. + +"Do you know, Watson," said Holmes as we sat together in the +gathering darkness, "I have really some scruples as to taking you +to-night. There is a distinct element of danger." + +"Can I be of assistance?" + +"Your presence might be invaluable." + +"Then I shall certainly come." + +"It is very kind of you." + +"You speak of danger. You have evidently seen more in these rooms +than was visible to me." + +"No, but I fancy that I may have deduced a little more. I imagine +that you saw all that I did." + +"I saw nothing remarkable save the bell-rope, and what purpose +that could answer I confess is more than I can imagine." + +"You saw the ventilator, too?" + +"Yes, but I do not think that it is such a very unusual thing to +have a small opening between two rooms. It was so small that a +rat could hardly pass through." + +"I knew that we should find a ventilator before ever we came to +Stoke Moran." + +"My dear Holmes!" + +"Oh, yes, I did. You remember in her statement she said that her +sister could smell Dr. Roylott's cigar. Now, of course that +suggested at once that there must be a communication between the +two rooms. It could only be a small one, or it would have been +remarked upon at the coroner's inquiry. I deduced a ventilator." + +"But what harm can there be in that?" + +"Well, there is at least a curious coincidence of dates. A +ventilator is made, a cord is hung, and a lady who sleeps in the +bed dies. Does not that strike you?" + +"I cannot as yet see any connection." + +"Did you observe anything very peculiar about that bed?" + +"No." + +"It was clamped to the floor. Did you ever see a bed fastened +like that before?" + +"I cannot say that I have." + +"The lady could not move her bed. It must always be in the same +relative position to the ventilator and to the rope--or so we may +call it, since it was clearly never meant for a bell-pull." + +"Holmes," I cried, "I seem to see dimly what you are hinting at. +We are only just in time to prevent some subtle and horrible +crime." + +"Subtle enough and horrible enough. When a doctor does go wrong +he is the first of criminals. He has nerve and he has knowledge. +Palmer and Pritchard were among the heads of their profession. +This man strikes even deeper, but I think, Watson, that we shall +be able to strike deeper still. But we shall have horrors enough +before the night is over; for goodness' sake let us have a quiet +pipe and turn our minds for a few hours to something more +cheerful." + + +About nine o'clock the light among the trees was extinguished, +and all was dark in the direction of the Manor House. Two hours +passed slowly away, and then, suddenly, just at the stroke of +eleven, a single bright light shone out right in front of us. + +"That is our signal," said Holmes, springing to his feet; "it +comes from the middle window." + +As we passed out he exchanged a few words with the landlord, +explaining that we were going on a late visit to an acquaintance, +and that it was possible that we might spend the night there. A +moment later we were out on the dark road, a chill wind blowing +in our faces, and one yellow light twinkling in front of us +through the gloom to guide us on our sombre errand. + +There was little difficulty in entering the grounds, for +unrepaired breaches gaped in the old park wall. Making our way +among the trees, we reached the lawn, crossed it, and were about +to enter through the window when out from a clump of laurel +bushes there darted what seemed to be a hideous and distorted +child, who threw itself upon the grass with writhing limbs and +then ran swiftly across the lawn into the darkness. + +"My God!" I whispered; "did you see it?" + +Holmes was for the moment as startled as I. His hand closed like +a vice upon my wrist in his agitation. Then he broke into a low +laugh and put his lips to my ear. + +"It is a nice household," he murmured. "That is the baboon." + +I had forgotten the strange pets which the doctor affected. There +was a cheetah, too; perhaps we might find it upon our shoulders +at any moment. I confess that I felt easier in my mind when, +after following Holmes' example and slipping off my shoes, I +found myself inside the bedroom. My companion noiselessly closed +the shutters, moved the lamp onto the table, and cast his eyes +round the room. All was as we had seen it in the daytime. Then +creeping up to me and making a trumpet of his hand, he whispered +into my ear again so gently that it was all that I could do to +distinguish the words: + +"The least sound would be fatal to our plans." + +I nodded to show that I had heard. + +"We must sit without light. He would see it through the +ventilator." + +I nodded again. + +"Do not go asleep; your very life may depend upon it. Have your +pistol ready in case we should need it. I will sit on the side of +the bed, and you in that chair." + +I took out my revolver and laid it on the corner of the table. + +Holmes had brought up a long thin cane, and this he placed upon +the bed beside him. By it he laid the box of matches and the +stump of a candle. Then he turned down the lamp, and we were left +in darkness. + +How shall I ever forget that dreadful vigil? I could not hear a +sound, not even the drawing of a breath, and yet I knew that my +companion sat open-eyed, within a few feet of me, in the same +state of nervous tension in which I was myself. The shutters cut +off the least ray of light, and we waited in absolute darkness. + +From outside came the occasional cry of a night-bird, and once at +our very window a long drawn catlike whine, which told us that +the cheetah was indeed at liberty. Far away we could hear the +deep tones of the parish clock, which boomed out every quarter of +an hour. How long they seemed, those quarters! Twelve struck, and +one and two and three, and still we sat waiting silently for +whatever might befall. + +Suddenly there was the momentary gleam of a light up in the +direction of the ventilator, which vanished immediately, but was +succeeded by a strong smell of burning oil and heated metal. +Someone in the next room had lit a dark-lantern. I heard a gentle +sound of movement, and then all was silent once more, though the +smell grew stronger. For half an hour I sat with straining ears. +Then suddenly another sound became audible--a very gentle, +soothing sound, like that of a small jet of steam escaping +continually from a kettle. The instant that we heard it, Holmes +sprang from the bed, struck a match, and lashed furiously with +his cane at the bell-pull. + +"You see it, Watson?" he yelled. "You see it?" + +But I saw nothing. At the moment when Holmes struck the light I +heard a low, clear whistle, but the sudden glare flashing into my +weary eyes made it impossible for me to tell what it was at which +my friend lashed so savagely. I could, however, see that his face +was deadly pale and filled with horror and loathing. He had +ceased to strike and was gazing up at the ventilator when +suddenly there broke from the silence of the night the most +horrible cry to which I have ever listened. It swelled up louder +and louder, a hoarse yell of pain and fear and anger all mingled +in the one dreadful shriek. They say that away down in the +village, and even in the distant parsonage, that cry raised the +sleepers from their beds. It struck cold to our hearts, and I +stood gazing at Holmes, and he at me, until the last echoes of it +had died away into the silence from which it rose. + +"What can it mean?" I gasped. + +"It means that it is all over," Holmes answered. "And perhaps, +after all, it is for the best. Take your pistol, and we will +enter Dr. Roylott's room." + +With a grave face he lit the lamp and led the way down the +corridor. Twice he struck at the chamber door without any reply +from within. Then he turned the handle and entered, I at his +heels, with the cocked pistol in my hand. + +It was a singular sight which met our eyes. On the table stood a +dark-lantern with the shutter half open, throwing a brilliant +beam of light upon the iron safe, the door of which was ajar. +Beside this table, on the wooden chair, sat Dr. Grimesby Roylott +clad in a long grey dressing-gown, his bare ankles protruding +beneath, and his feet thrust into red heelless Turkish slippers. +Across his lap lay the short stock with the long lash which we +had noticed during the day. His chin was cocked upward and his +eyes were fixed in a dreadful, rigid stare at the corner of the +ceiling. Round his brow he had a peculiar yellow band, with +brownish speckles, which seemed to be bound tightly round his +head. As we entered he made neither sound nor motion. + +"The band! the speckled band!" whispered Holmes. + +I took a step forward. In an instant his strange headgear began +to move, and there reared itself from among his hair the squat +diamond-shaped head and puffed neck of a loathsome serpent. + +"It is a swamp adder!" cried Holmes; "the deadliest snake in +India. He has died within ten seconds of being bitten. Violence +does, in truth, recoil upon the violent, and the schemer falls +into the pit which he digs for another. Let us thrust this +creature back into its den, and we can then remove Miss Stoner to +some place of shelter and let the county police know what has +happened." + +As he spoke he drew the dog-whip swiftly from the dead man's lap, +and throwing the noose round the reptile's neck he drew it from +its horrid perch and, carrying it at arm's length, threw it into +the iron safe, which he closed upon it. + +Such are the true facts of the death of Dr. Grimesby Roylott, of +Stoke Moran. It is not necessary that I should prolong a +narrative which has already run to too great a length by telling +how we broke the sad news to the terrified girl, how we conveyed +her by the morning train to the care of her good aunt at Harrow, +of how the slow process of official inquiry came to the +conclusion that the doctor met his fate while indiscreetly +playing with a dangerous pet. The little which I had yet to learn +of the case was told me by Sherlock Holmes as we travelled back +next day. + +"I had," said he, "come to an entirely erroneous conclusion which +shows, my dear Watson, how dangerous it always is to reason from +insufficient data. The presence of the gipsies, and the use of +the word 'band,' which was used by the poor girl, no doubt, to +explain the appearance which she had caught a hurried glimpse of +by the light of her match, were sufficient to put me upon an +entirely wrong scent. I can only claim the merit that I instantly +reconsidered my position when, however, it became clear to me +that whatever danger threatened an occupant of the room could not +come either from the window or the door. My attention was +speedily drawn, as I have already remarked to you, to this +ventilator, and to the bell-rope which hung down to the bed. The +discovery that this was a dummy, and that the bed was clamped to +the floor, instantly gave rise to the suspicion that the rope was +there as a bridge for something passing through the hole and +coming to the bed. The idea of a snake instantly occurred to me, +and when I coupled it with my knowledge that the doctor was +furnished with a supply of creatures from India, I felt that I +was probably on the right track. The idea of using a form of +poison which could not possibly be discovered by any chemical +test was just such a one as would occur to a clever and ruthless +man who had had an Eastern training. The rapidity with which such +a poison would take effect would also, from his point of view, be +an advantage. It would be a sharp-eyed coroner, indeed, who could +distinguish the two little dark punctures which would show where +the poison fangs had done their work. Then I thought of the +whistle. Of course he must recall the snake before the morning +light revealed it to the victim. He had trained it, probably by +the use of the milk which we saw, to return to him when summoned. +He would put it through this ventilator at the hour that he +thought best, with the certainty that it would crawl down the +rope and land on the bed. It might or might not bite the +occupant, perhaps she might escape every night for a week, but +sooner or later she must fall a victim. + +"I had come to these conclusions before ever I had entered his +room. An inspection of his chair showed me that he had been in +the habit of standing on it, which of course would be necessary +in order that he should reach the ventilator. The sight of the +safe, the saucer of milk, and the loop of whipcord were enough to +finally dispel any doubts which may have remained. The metallic +clang heard by Miss Stoner was obviously caused by her stepfather +hastily closing the door of his safe upon its terrible occupant. +Having once made up my mind, you know the steps which I took in +order to put the matter to the proof. I heard the creature hiss +as I have no doubt that you did also, and I instantly lit the +light and attacked it." + +"With the result of driving it through the ventilator." + +"And also with the result of causing it to turn upon its master +at the other side. Some of the blows of my cane came home and +roused its snakish temper, so that it flew upon the first person +it saw. In this way I am no doubt indirectly responsible for Dr. +Grimesby Roylott's death, and I cannot say that it is likely to +weigh very heavily upon my conscience." + + + +IX. THE ADVENTURE OF THE ENGINEER'S THUMB + +Of all the problems which have been submitted to my friend, Mr. +Sherlock Holmes, for solution during the years of our intimacy, +there were only two which I was the means of introducing to his +notice--that of Mr. Hatherley's thumb, and that of Colonel +Warburton's madness. Of these the latter may have afforded a +finer field for an acute and original observer, but the other was +so strange in its inception and so dramatic in its details that +it may be the more worthy of being placed upon record, even if it +gave my friend fewer openings for those deductive methods of +reasoning by which he achieved such remarkable results. The story +has, I believe, been told more than once in the newspapers, but, +like all such narratives, its effect is much less striking when +set forth en bloc in a single half-column of print than when the +facts slowly evolve before your own eyes, and the mystery clears +gradually away as each new discovery furnishes a step which leads +on to the complete truth. At the time the circumstances made a +deep impression upon me, and the lapse of two years has hardly +served to weaken the effect. + +It was in the summer of '89, not long after my marriage, that the +events occurred which I am now about to summarise. I had returned +to civil practice and had finally abandoned Holmes in his Baker +Street rooms, although I continually visited him and occasionally +even persuaded him to forgo his Bohemian habits so far as to come +and visit us. My practice had steadily increased, and as I +happened to live at no very great distance from Paddington +Station, I got a few patients from among the officials. One of +these, whom I had cured of a painful and lingering disease, was +never weary of advertising my virtues and of endeavouring to send +me on every sufferer over whom he might have any influence. + +One morning, at a little before seven o'clock, I was awakened by +the maid tapping at the door to announce that two men had come +from Paddington and were waiting in the consulting-room. I +dressed hurriedly, for I knew by experience that railway cases +were seldom trivial, and hastened downstairs. As I descended, my +old ally, the guard, came out of the room and closed the door +tightly behind him. + +"I've got him here," he whispered, jerking his thumb over his +shoulder; "he's all right." + +"What is it, then?" I asked, for his manner suggested that it was +some strange creature which he had caged up in my room. + +"It's a new patient," he whispered. "I thought I'd bring him +round myself; then he couldn't slip away. There he is, all safe +and sound. I must go now, Doctor; I have my dooties, just the +same as you." And off he went, this trusty tout, without even +giving me time to thank him. + +I entered my consulting-room and found a gentleman seated by the +table. He was quietly dressed in a suit of heather tweed with a +soft cloth cap which he had laid down upon my books. Round one of +his hands he had a handkerchief wrapped, which was mottled all +over with bloodstains. He was young, not more than +five-and-twenty, I should say, with a strong, masculine face; but +he was exceedingly pale and gave me the impression of a man who +was suffering from some strong agitation, which it took all his +strength of mind to control. + +"I am sorry to knock you up so early, Doctor," said he, "but I +have had a very serious accident during the night. I came in by +train this morning, and on inquiring at Paddington as to where I +might find a doctor, a worthy fellow very kindly escorted me +here. I gave the maid a card, but I see that she has left it upon +the side-table." + +I took it up and glanced at it. "Mr. Victor Hatherley, hydraulic +engineer, 16A, Victoria Street (3rd floor)." That was the name, +style, and abode of my morning visitor. "I regret that I have +kept you waiting," said I, sitting down in my library-chair. "You +are fresh from a night journey, I understand, which is in itself +a monotonous occupation." + +"Oh, my night could not be called monotonous," said he, and +laughed. He laughed very heartily, with a high, ringing note, +leaning back in his chair and shaking his sides. All my medical +instincts rose up against that laugh. + +"Stop it!" I cried; "pull yourself together!" and I poured out +some water from a caraffe. + +It was useless, however. He was off in one of those hysterical +outbursts which come upon a strong nature when some great crisis +is over and gone. Presently he came to himself once more, very +weary and pale-looking. + +"I have been making a fool of myself," he gasped. + +"Not at all. Drink this." I dashed some brandy into the water, +and the colour began to come back to his bloodless cheeks. + +"That's better!" said he. "And now, Doctor, perhaps you would +kindly attend to my thumb, or rather to the place where my thumb +used to be." + +He unwound the handkerchief and held out his hand. It gave even +my hardened nerves a shudder to look at it. There were four +protruding fingers and a horrid red, spongy surface where the +thumb should have been. It had been hacked or torn right out from +the roots. + +"Good heavens!" I cried, "this is a terrible injury. It must have +bled considerably." + +"Yes, it did. I fainted when it was done, and I think that I must +have been senseless for a long time. When I came to I found that +it was still bleeding, so I tied one end of my handkerchief very +tightly round the wrist and braced it up with a twig." + +"Excellent! You should have been a surgeon." + +"It is a question of hydraulics, you see, and came within my own +province." + +"This has been done," said I, examining the wound, "by a very +heavy and sharp instrument." + +"A thing like a cleaver," said he. + +"An accident, I presume?" + +"By no means." + +"What! a murderous attack?" + +"Very murderous indeed." + +"You horrify me." + +I sponged the wound, cleaned it, dressed it, and finally covered +it over with cotton wadding and carbolised bandages. He lay back +without wincing, though he bit his lip from time to time. + +"How is that?" I asked when I had finished. + +"Capital! Between your brandy and your bandage, I feel a new man. +I was very weak, but I have had a good deal to go through." + +"Perhaps you had better not speak of the matter. It is evidently +trying to your nerves." + +"Oh, no, not now. I shall have to tell my tale to the police; +but, between ourselves, if it were not for the convincing +evidence of this wound of mine, I should be surprised if they +believed my statement, for it is a very extraordinary one, and I +have not much in the way of proof with which to back it up; and, +even if they believe me, the clues which I can give them are so +vague that it is a question whether justice will be done." + +"Ha!" cried I, "if it is anything in the nature of a problem +which you desire to see solved, I should strongly recommend you +to come to my friend, Mr. Sherlock Holmes, before you go to the +official police." + +"Oh, I have heard of that fellow," answered my visitor, "and I +should be very glad if he would take the matter up, though of +course I must use the official police as well. Would you give me +an introduction to him?" + +"I'll do better. I'll take you round to him myself." + +"I should be immensely obliged to you." + +"We'll call a cab and go together. We shall just be in time to +have a little breakfast with him. Do you feel equal to it?" + +"Yes; I shall not feel easy until I have told my story." + +"Then my servant will call a cab, and I shall be with you in an +instant." I rushed upstairs, explained the matter shortly to my +wife, and in five minutes was inside a hansom, driving with my +new acquaintance to Baker Street. + +Sherlock Holmes was, as I expected, lounging about his +sitting-room in his dressing-gown, reading the agony column of The +Times and smoking his before-breakfast pipe, which was composed +of all the plugs and dottles left from his smokes of the day +before, all carefully dried and collected on the corner of the +mantelpiece. He received us in his quietly genial fashion, +ordered fresh rashers and eggs, and joined us in a hearty meal. +When it was concluded he settled our new acquaintance upon the +sofa, placed a pillow beneath his head, and laid a glass of +brandy and water within his reach. + +"It is easy to see that your experience has been no common one, +Mr. Hatherley," said he. "Pray, lie down there and make yourself +absolutely at home. Tell us what you can, but stop when you are +tired and keep up your strength with a little stimulant." + +"Thank you," said my patient, "but I have felt another man since +the doctor bandaged me, and I think that your breakfast has +completed the cure. I shall take up as little of your valuable +time as possible, so I shall start at once upon my peculiar +experiences." + +Holmes sat in his big armchair with the weary, heavy-lidded +expression which veiled his keen and eager nature, while I sat +opposite to him, and we listened in silence to the strange story +which our visitor detailed to us. + +"You must know," said he, "that I am an orphan and a bachelor, +residing alone in lodgings in London. By profession I am a +hydraulic engineer, and I have had considerable experience of my +work during the seven years that I was apprenticed to Venner & +Matheson, the well-known firm, of Greenwich. Two years ago, +having served my time, and having also come into a fair sum of +money through my poor father's death, I determined to start in +business for myself and took professional chambers in Victoria +Street. + +"I suppose that everyone finds his first independent start in +business a dreary experience. To me it has been exceptionally so. +During two years I have had three consultations and one small +job, and that is absolutely all that my profession has brought +me. My gross takings amount to 27 pounds 10s. Every day, from +nine in the morning until four in the afternoon, I waited in my +little den, until at last my heart began to sink, and I came to +believe that I should never have any practice at all. + +"Yesterday, however, just as I was thinking of leaving the +office, my clerk entered to say there was a gentleman waiting who +wished to see me upon business. He brought up a card, too, with +the name of 'Colonel Lysander Stark' engraved upon it. Close at +his heels came the colonel himself, a man rather over the middle +size, but of an exceeding thinness. I do not think that I have +ever seen so thin a man. His whole face sharpened away into nose +and chin, and the skin of his cheeks was drawn quite tense over +his outstanding bones. Yet this emaciation seemed to be his +natural habit, and due to no disease, for his eye was bright, his +step brisk, and his bearing assured. He was plainly but neatly +dressed, and his age, I should judge, would be nearer forty than +thirty. + +"'Mr. Hatherley?' said he, with something of a German accent. +'You have been recommended to me, Mr. Hatherley, as being a man +who is not only proficient in his profession but is also discreet +and capable of preserving a secret.' + +"I bowed, feeling as flattered as any young man would at such an +address. 'May I ask who it was who gave me so good a character?' + +"'Well, perhaps it is better that I should not tell you that just +at this moment. I have it from the same source that you are both +an orphan and a bachelor and are residing alone in London.' + +"'That is quite correct,' I answered; 'but you will excuse me if +I say that I cannot see how all this bears upon my professional +qualifications. I understand that it was on a professional matter +that you wished to speak to me?' + +"'Undoubtedly so. But you will find that all I say is really to +the point. I have a professional commission for you, but absolute +secrecy is quite essential--absolute secrecy, you understand, and +of course we may expect that more from a man who is alone than +from one who lives in the bosom of his family.' + +"'If I promise to keep a secret,' said I, 'you may absolutely +depend upon my doing so.' + +"He looked very hard at me as I spoke, and it seemed to me that I +had never seen so suspicious and questioning an eye. + +"'Do you promise, then?' said he at last. + +"'Yes, I promise.' + +"'Absolute and complete silence before, during, and after? No +reference to the matter at all, either in word or writing?' + +"'I have already given you my word.' + +"'Very good.' He suddenly sprang up, and darting like lightning +across the room he flung open the door. The passage outside was +empty. + +"'That's all right,' said he, coming back. 'I know that clerks are +sometimes curious as to their master's affairs. Now we can talk +in safety.' He drew up his chair very close to mine and began to +stare at me again with the same questioning and thoughtful look. + +"A feeling of repulsion, and of something akin to fear had begun +to rise within me at the strange antics of this fleshless man. +Even my dread of losing a client could not restrain me from +showing my impatience. + +"'I beg that you will state your business, sir,' said I; 'my time +is of value.' Heaven forgive me for that last sentence, but the +words came to my lips. + +"'How would fifty guineas for a night's work suit you?' he asked. + +"'Most admirably.' + +"'I say a night's work, but an hour's would be nearer the mark. I +simply want your opinion about a hydraulic stamping machine which +has got out of gear. If you show us what is wrong we shall soon +set it right ourselves. What do you think of such a commission as +that?' + +"'The work appears to be light and the pay munificent.' + +"'Precisely so. We shall want you to come to-night by the last +train.' + +"'Where to?' + +"'To Eyford, in Berkshire. It is a little place near the borders +of Oxfordshire, and within seven miles of Reading. There is a +train from Paddington which would bring you there at about +11:15.' + +"'Very good.' + +"'I shall come down in a carriage to meet you.' + +"'There is a drive, then?' + +"'Yes, our little place is quite out in the country. It is a good +seven miles from Eyford Station.' + +"'Then we can hardly get there before midnight. I suppose there +would be no chance of a train back. I should be compelled to stop +the night.' + +"'Yes, we could easily give you a shake-down.' + +"'That is very awkward. Could I not come at some more convenient +hour?' + +"'We have judged it best that you should come late. It is to +recompense you for any inconvenience that we are paying to you, a +young and unknown man, a fee which would buy an opinion from the +very heads of your profession. Still, of course, if you would +like to draw out of the business, there is plenty of time to do +so.' + +"I thought of the fifty guineas, and of how very useful they +would be to me. 'Not at all,' said I, 'I shall be very happy to +accommodate myself to your wishes. I should like, however, to +understand a little more clearly what it is that you wish me to +do.' + +"'Quite so. It is very natural that the pledge of secrecy which +we have exacted from you should have aroused your curiosity. I +have no wish to commit you to anything without your having it all +laid before you. I suppose that we are absolutely safe from +eavesdroppers?' + +"'Entirely.' + +"'Then the matter stands thus. You are probably aware that +fuller's-earth is a valuable product, and that it is only found +in one or two places in England?' + +"'I have heard so.' + +"'Some little time ago I bought a small place--a very small +place--within ten miles of Reading. I was fortunate enough to +discover that there was a deposit of fuller's-earth in one of my +fields. On examining it, however, I found that this deposit was a +comparatively small one, and that it formed a link between two +very much larger ones upon the right and left--both of them, +however, in the grounds of my neighbours. These good people were +absolutely ignorant that their land contained that which was +quite as valuable as a gold-mine. Naturally, it was to my +interest to buy their land before they discovered its true value, +but unfortunately I had no capital by which I could do this. I +took a few of my friends into the secret, however, and they +suggested that we should quietly and secretly work our own little +deposit and that in this way we should earn the money which would +enable us to buy the neighbouring fields. This we have now been +doing for some time, and in order to help us in our operations we +erected a hydraulic press. This press, as I have already +explained, has got out of order, and we wish your advice upon the +subject. We guard our secret very jealously, however, and if it +once became known that we had hydraulic engineers coming to our +little house, it would soon rouse inquiry, and then, if the facts +came out, it would be good-bye to any chance of getting these +fields and carrying out our plans. That is why I have made you +promise me that you will not tell a human being that you are +going to Eyford to-night. I hope that I make it all plain?' + +"'I quite follow you,' said I. 'The only point which I could not +quite understand was what use you could make of a hydraulic press +in excavating fuller's-earth, which, as I understand, is dug out +like gravel from a pit.' + +"'Ah!' said he carelessly, 'we have our own process. We compress +the earth into bricks, so as to remove them without revealing +what they are. But that is a mere detail. I have taken you fully +into my confidence now, Mr. Hatherley, and I have shown you how I +trust you.' He rose as he spoke. 'I shall expect you, then, at +Eyford at 11:15.' + +"'I shall certainly be there.' + +"'And not a word to a soul.' He looked at me with a last long, +questioning gaze, and then, pressing my hand in a cold, dank +grasp, he hurried from the room. + +"Well, when I came to think it all over in cool blood I was very +much astonished, as you may both think, at this sudden commission +which had been intrusted to me. On the one hand, of course, I was +glad, for the fee was at least tenfold what I should have asked +had I set a price upon my own services, and it was possible that +this order might lead to other ones. On the other hand, the face +and manner of my patron had made an unpleasant impression upon +me, and I could not think that his explanation of the +fuller's-earth was sufficient to explain the necessity for my +coming at midnight, and his extreme anxiety lest I should tell +anyone of my errand. However, I threw all fears to the winds, ate +a hearty supper, drove to Paddington, and started off, having +obeyed to the letter the injunction as to holding my tongue. + +"At Reading I had to change not only my carriage but my station. +However, I was in time for the last train to Eyford, and I +reached the little dim-lit station after eleven o'clock. I was the +only passenger who got out there, and there was no one upon the +platform save a single sleepy porter with a lantern. As I passed +out through the wicket gate, however, I found my acquaintance of +the morning waiting in the shadow upon the other side. Without a +word he grasped my arm and hurried me into a carriage, the door +of which was standing open. He drew up the windows on either +side, tapped on the wood-work, and away we went as fast as the +horse could go." + +"One horse?" interjected Holmes. + +"Yes, only one." + +"Did you observe the colour?" + +"Yes, I saw it by the side-lights when I was stepping into the +carriage. It was a chestnut." + +"Tired-looking or fresh?" + +"Oh, fresh and glossy." + +"Thank you. I am sorry to have interrupted you. Pray continue +your most interesting statement." + +"Away we went then, and we drove for at least an hour. Colonel +Lysander Stark had said that it was only seven miles, but I +should think, from the rate that we seemed to go, and from the +time that we took, that it must have been nearer twelve. He sat +at my side in silence all the time, and I was aware, more than +once when I glanced in his direction, that he was looking at me +with great intensity. The country roads seem to be not very good +in that part of the world, for we lurched and jolted terribly. I +tried to look out of the windows to see something of where we +were, but they were made of frosted glass, and I could make out +nothing save the occasional bright blur of a passing light. Now +and then I hazarded some remark to break the monotony of the +journey, but the colonel answered only in monosyllables, and the +conversation soon flagged. At last, however, the bumping of the +road was exchanged for the crisp smoothness of a gravel-drive, +and the carriage came to a stand. Colonel Lysander Stark sprang +out, and, as I followed after him, pulled me swiftly into a porch +which gaped in front of us. We stepped, as it were, right out of +the carriage and into the hall, so that I failed to catch the +most fleeting glance of the front of the house. The instant that +I had crossed the threshold the door slammed heavily behind us, +and I heard faintly the rattle of the wheels as the carriage +drove away. + +"It was pitch dark inside the house, and the colonel fumbled +about looking for matches and muttering under his breath. +Suddenly a door opened at the other end of the passage, and a +long, golden bar of light shot out in our direction. It grew +broader, and a woman appeared with a lamp in her hand, which she +held above her head, pushing her face forward and peering at us. +I could see that she was pretty, and from the gloss with which +the light shone upon her dark dress I knew that it was a rich +material. She spoke a few words in a foreign tongue in a tone as +though asking a question, and when my companion answered in a +gruff monosyllable she gave such a start that the lamp nearly +fell from her hand. Colonel Stark went up to her, whispered +something in her ear, and then, pushing her back into the room +from whence she had come, he walked towards me again with the +lamp in his hand. + +"'Perhaps you will have the kindness to wait in this room for a +few minutes,' said he, throwing open another door. It was a +quiet, little, plainly furnished room, with a round table in the +centre, on which several German books were scattered. Colonel +Stark laid down the lamp on the top of a harmonium beside the +door. 'I shall not keep you waiting an instant,' said he, and +vanished into the darkness. + +"I glanced at the books upon the table, and in spite of my +ignorance of German I could see that two of them were treatises +on science, the others being volumes of poetry. Then I walked +across to the window, hoping that I might catch some glimpse of +the country-side, but an oak shutter, heavily barred, was folded +across it. It was a wonderfully silent house. There was an old +clock ticking loudly somewhere in the passage, but otherwise +everything was deadly still. A vague feeling of uneasiness began +to steal over me. Who were these German people, and what were +they doing living in this strange, out-of-the-way place? And +where was the place? I was ten miles or so from Eyford, that was +all I knew, but whether north, south, east, or west I had no +idea. For that matter, Reading, and possibly other large towns, +were within that radius, so the place might not be so secluded, +after all. Yet it was quite certain, from the absolute stillness, +that we were in the country. I paced up and down the room, +humming a tune under my breath to keep up my spirits and feeling +that I was thoroughly earning my fifty-guinea fee. + +"Suddenly, without any preliminary sound in the midst of the +utter stillness, the door of my room swung slowly open. The woman +was standing in the aperture, the darkness of the hall behind +her, the yellow light from my lamp beating upon her eager and +beautiful face. I could see at a glance that she was sick with +fear, and the sight sent a chill to my own heart. She held up one +shaking finger to warn me to be silent, and she shot a few +whispered words of broken English at me, her eyes glancing back, +like those of a frightened horse, into the gloom behind her. + +"'I would go,' said she, trying hard, as it seemed to me, to +speak calmly; 'I would go. I should not stay here. There is no +good for you to do.' + +"'But, madam,' said I, 'I have not yet done what I came for. I +cannot possibly leave until I have seen the machine.' + +"'It is not worth your while to wait,' she went on. 'You can pass +through the door; no one hinders.' And then, seeing that I smiled +and shook my head, she suddenly threw aside her constraint and +made a step forward, with her hands wrung together. 'For the love +of Heaven!' she whispered, 'get away from here before it is too +late!' + +"But I am somewhat headstrong by nature, and the more ready to +engage in an affair when there is some obstacle in the way. I +thought of my fifty-guinea fee, of my wearisome journey, and of +the unpleasant night which seemed to be before me. Was it all to +go for nothing? Why should I slink away without having carried +out my commission, and without the payment which was my due? This +woman might, for all I knew, be a monomaniac. With a stout +bearing, therefore, though her manner had shaken me more than I +cared to confess, I still shook my head and declared my intention +of remaining where I was. She was about to renew her entreaties +when a door slammed overhead, and the sound of several footsteps +was heard upon the stairs. She listened for an instant, threw up +her hands with a despairing gesture, and vanished as suddenly and +as noiselessly as she had come. + +"The newcomers were Colonel Lysander Stark and a short thick man +with a chinchilla beard growing out of the creases of his double +chin, who was introduced to me as Mr. Ferguson. + +"'This is my secretary and manager,' said the colonel. 'By the +way, I was under the impression that I left this door shut just +now. I fear that you have felt the draught.' + +"'On the contrary,' said I, 'I opened the door myself because I +felt the room to be a little close.' + +"He shot one of his suspicious looks at me. 'Perhaps we had +better proceed to business, then,' said he. 'Mr. Ferguson and I +will take you up to see the machine.' + +"'I had better put my hat on, I suppose.' + +"'Oh, no, it is in the house.' + +"'What, you dig fuller's-earth in the house?' + +"'No, no. This is only where we compress it. But never mind that. +All we wish you to do is to examine the machine and to let us +know what is wrong with it.' + +"We went upstairs together, the colonel first with the lamp, the +fat manager and I behind him. It was a labyrinth of an old house, +with corridors, passages, narrow winding staircases, and little +low doors, the thresholds of which were hollowed out by the +generations who had crossed them. There were no carpets and no +signs of any furniture above the ground floor, while the plaster +was peeling off the walls, and the damp was breaking through in +green, unhealthy blotches. I tried to put on as unconcerned an +air as possible, but I had not forgotten the warnings of the +lady, even though I disregarded them, and I kept a keen eye upon +my two companions. Ferguson appeared to be a morose and silent +man, but I could see from the little that he said that he was at +least a fellow-countryman. + +"Colonel Lysander Stark stopped at last before a low door, which +he unlocked. Within was a small, square room, in which the three +of us could hardly get at one time. Ferguson remained outside, +and the colonel ushered me in. + +"'We are now,' said he, 'actually within the hydraulic press, and +it would be a particularly unpleasant thing for us if anyone were +to turn it on. The ceiling of this small chamber is really the +end of the descending piston, and it comes down with the force of +many tons upon this metal floor. There are small lateral columns +of water outside which receive the force, and which transmit and +multiply it in the manner which is familiar to you. The machine +goes readily enough, but there is some stiffness in the working +of it, and it has lost a little of its force. Perhaps you will +have the goodness to look it over and to show us how we can set +it right.' + +"I took the lamp from him, and I examined the machine very +thoroughly. It was indeed a gigantic one, and capable of +exercising enormous pressure. When I passed outside, however, and +pressed down the levers which controlled it, I knew at once by +the whishing sound that there was a slight leakage, which allowed +a regurgitation of water through one of the side cylinders. An +examination showed that one of the india-rubber bands which was +round the head of a driving-rod had shrunk so as not quite to +fill the socket along which it worked. This was clearly the cause +of the loss of power, and I pointed it out to my companions, who +followed my remarks very carefully and asked several practical +questions as to how they should proceed to set it right. When I +had made it clear to them, I returned to the main chamber of the +machine and took a good look at it to satisfy my own curiosity. +It was obvious at a glance that the story of the fuller's-earth +was the merest fabrication, for it would be absurd to suppose +that so powerful an engine could be designed for so inadequate a +purpose. The walls were of wood, but the floor consisted of a +large iron trough, and when I came to examine it I could see a +crust of metallic deposit all over it. I had stooped and was +scraping at this to see exactly what it was when I heard a +muttered exclamation in German and saw the cadaverous face of the +colonel looking down at me. + +"'What are you doing there?' he asked. + +"I felt angry at having been tricked by so elaborate a story as +that which he had told me. 'I was admiring your fuller's-earth,' +said I; 'I think that I should be better able to advise you as to +your machine if I knew what the exact purpose was for which it +was used.' + +"The instant that I uttered the words I regretted the rashness of +my speech. His face set hard, and a baleful light sprang up in +his grey eyes. + +"'Very well,' said he, 'you shall know all about the machine.' He +took a step backward, slammed the little door, and turned the key +in the lock. I rushed towards it and pulled at the handle, but it +was quite secure, and did not give in the least to my kicks and +shoves. 'Hullo!' I yelled. 'Hullo! Colonel! Let me out!' + +"And then suddenly in the silence I heard a sound which sent my +heart into my mouth. It was the clank of the levers and the swish +of the leaking cylinder. He had set the engine at work. The lamp +still stood upon the floor where I had placed it when examining +the trough. By its light I saw that the black ceiling was coming +down upon me, slowly, jerkily, but, as none knew better than +myself, with a force which must within a minute grind me to a +shapeless pulp. I threw myself, screaming, against the door, and +dragged with my nails at the lock. I implored the colonel to let +me out, but the remorseless clanking of the levers drowned my +cries. The ceiling was only a foot or two above my head, and with +my hand upraised I could feel its hard, rough surface. Then it +flashed through my mind that the pain of my death would depend +very much upon the position in which I met it. If I lay on my +face the weight would come upon my spine, and I shuddered to +think of that dreadful snap. Easier the other way, perhaps; and +yet, had I the nerve to lie and look up at that deadly black +shadow wavering down upon me? Already I was unable to stand +erect, when my eye caught something which brought a gush of hope +back to my heart. + +"I have said that though the floor and ceiling were of iron, the +walls were of wood. As I gave a last hurried glance around, I saw +a thin line of yellow light between two of the boards, which +broadened and broadened as a small panel was pushed backward. For +an instant I could hardly believe that here was indeed a door +which led away from death. The next instant I threw myself +through, and lay half-fainting upon the other side. The panel had +closed again behind me, but the crash of the lamp, and a few +moments afterwards the clang of the two slabs of metal, told me +how narrow had been my escape. + +"I was recalled to myself by a frantic plucking at my wrist, and +I found myself lying upon the stone floor of a narrow corridor, +while a woman bent over me and tugged at me with her left hand, +while she held a candle in her right. It was the same good friend +whose warning I had so foolishly rejected. + +"'Come! come!' she cried breathlessly. 'They will be here in a +moment. They will see that you are not there. Oh, do not waste +the so-precious time, but come!' + +"This time, at least, I did not scorn her advice. I staggered to +my feet and ran with her along the corridor and down a winding +stair. The latter led to another broad passage, and just as we +reached it we heard the sound of running feet and the shouting of +two voices, one answering the other from the floor on which we +were and from the one beneath. My guide stopped and looked about +her like one who is at her wit's end. Then she threw open a door +which led into a bedroom, through the window of which the moon +was shining brightly. + +"'It is your only chance,' said she. 'It is high, but it may be +that you can jump it.' + +"As she spoke a light sprang into view at the further end of the +passage, and I saw the lean figure of Colonel Lysander Stark +rushing forward with a lantern in one hand and a weapon like a +butcher's cleaver in the other. I rushed across the bedroom, +flung open the window, and looked out. How quiet and sweet and +wholesome the garden looked in the moonlight, and it could not be +more than thirty feet down. I clambered out upon the sill, but I +hesitated to jump until I should have heard what passed between +my saviour and the ruffian who pursued me. If she were ill-used, +then at any risks I was determined to go back to her assistance. +The thought had hardly flashed through my mind before he was at +the door, pushing his way past her; but she threw her arms round +him and tried to hold him back. + +"'Fritz! Fritz!' she cried in English, 'remember your promise +after the last time. You said it should not be again. He will be +silent! Oh, he will be silent!' + +"'You are mad, Elise!' he shouted, struggling to break away from +her. 'You will be the ruin of us. He has seen too much. Let me +pass, I say!' He dashed her to one side, and, rushing to the +window, cut at me with his heavy weapon. I had let myself go, and +was hanging by the hands to the sill, when his blow fell. I was +conscious of a dull pain, my grip loosened, and I fell into the +garden below. + +"I was shaken but not hurt by the fall; so I picked myself up and +rushed off among the bushes as hard as I could run, for I +understood that I was far from being out of danger yet. Suddenly, +however, as I ran, a deadly dizziness and sickness came over me. +I glanced down at my hand, which was throbbing painfully, and +then, for the first time, saw that my thumb had been cut off and +that the blood was pouring from my wound. I endeavoured to tie my +handkerchief round it, but there came a sudden buzzing in my +ears, and next moment I fell in a dead faint among the +rose-bushes. + +"How long I remained unconscious I cannot tell. It must have been +a very long time, for the moon had sunk, and a bright morning was +breaking when I came to myself. My clothes were all sodden with +dew, and my coat-sleeve was drenched with blood from my wounded +thumb. The smarting of it recalled in an instant all the +particulars of my night's adventure, and I sprang to my feet with +the feeling that I might hardly yet be safe from my pursuers. But +to my astonishment, when I came to look round me, neither house +nor garden were to be seen. I had been lying in an angle of the +hedge close by the highroad, and just a little lower down was a +long building, which proved, upon my approaching it, to be the +very station at which I had arrived upon the previous night. Were +it not for the ugly wound upon my hand, all that had passed +during those dreadful hours might have been an evil dream. + +"Half dazed, I went into the station and asked about the morning +train. There would be one to Reading in less than an hour. The +same porter was on duty, I found, as had been there when I +arrived. I inquired of him whether he had ever heard of Colonel +Lysander Stark. The name was strange to him. Had he observed a +carriage the night before waiting for me? No, he had not. Was +there a police-station anywhere near? There was one about three +miles off. + +"It was too far for me to go, weak and ill as I was. I determined +to wait until I got back to town before telling my story to the +police. It was a little past six when I arrived, so I went first +to have my wound dressed, and then the doctor was kind enough to +bring me along here. I put the case into your hands and shall do +exactly what you advise." + +We both sat in silence for some little time after listening to +this extraordinary narrative. Then Sherlock Holmes pulled down +from the shelf one of the ponderous commonplace books in which he +placed his cuttings. + +"Here is an advertisement which will interest you," said he. "It +appeared in all the papers about a year ago. Listen to this: +'Lost, on the 9th inst., Mr. Jeremiah Hayling, aged +twenty-six, a hydraulic engineer. Left his lodgings at ten +o'clock at night, and has not been heard of since. Was +dressed in,' etc., etc. Ha! That represents the last time that +the colonel needed to have his machine overhauled, I fancy." + +"Good heavens!" cried my patient. "Then that explains what the +girl said." + +"Undoubtedly. It is quite clear that the colonel was a cool and +desperate man, who was absolutely determined that nothing should +stand in the way of his little game, like those out-and-out +pirates who will leave no survivor from a captured ship. Well, +every moment now is precious, so if you feel equal to it we shall +go down to Scotland Yard at once as a preliminary to starting for +Eyford." + +Some three hours or so afterwards we were all in the train +together, bound from Reading to the little Berkshire village. +There were Sherlock Holmes, the hydraulic engineer, Inspector +Bradstreet, of Scotland Yard, a plain-clothes man, and myself. +Bradstreet had spread an ordnance map of the county out upon the +seat and was busy with his compasses drawing a circle with Eyford +for its centre. + +"There you are," said he. "That circle is drawn at a radius of +ten miles from the village. The place we want must be somewhere +near that line. You said ten miles, I think, sir." + +"It was an hour's good drive." + +"And you think that they brought you back all that way when you +were unconscious?" + +"They must have done so. I have a confused memory, too, of having +been lifted and conveyed somewhere." + +"What I cannot understand," said I, "is why they should have +spared you when they found you lying fainting in the garden. +Perhaps the villain was softened by the woman's entreaties." + +"I hardly think that likely. I never saw a more inexorable face +in my life." + +"Oh, we shall soon clear up all that," said Bradstreet. "Well, I +have drawn my circle, and I only wish I knew at what point upon +it the folk that we are in search of are to be found." + +"I think I could lay my finger on it," said Holmes quietly. + +"Really, now!" cried the inspector, "you have formed your +opinion! Come, now, we shall see who agrees with you. I say it is +south, for the country is more deserted there." + +"And I say east," said my patient. + +"I am for west," remarked the plain-clothes man. "There are +several quiet little villages up there." + +"And I am for north," said I, "because there are no hills there, +and our friend says that he did not notice the carriage go up +any." + +"Come," cried the inspector, laughing; "it's a very pretty +diversity of opinion. We have boxed the compass among us. Who do +you give your casting vote to?" + +"You are all wrong." + +"But we can't all be." + +"Oh, yes, you can. This is my point." He placed his finger in the +centre of the circle. "This is where we shall find them." + +"But the twelve-mile drive?" gasped Hatherley. + +"Six out and six back. Nothing simpler. You say yourself that the +horse was fresh and glossy when you got in. How could it be that +if it had gone twelve miles over heavy roads?" + +"Indeed, it is a likely ruse enough," observed Bradstreet +thoughtfully. "Of course there can be no doubt as to the nature +of this gang." + +"None at all," said Holmes. "They are coiners on a large scale, +and have used the machine to form the amalgam which has taken the +place of silver." + +"We have known for some time that a clever gang was at work," +said the inspector. "They have been turning out half-crowns by +the thousand. We even traced them as far as Reading, but could +get no farther, for they had covered their traces in a way that +showed that they were very old hands. But now, thanks to this +lucky chance, I think that we have got them right enough." + +But the inspector was mistaken, for those criminals were not +destined to fall into the hands of justice. As we rolled into +Eyford Station we saw a gigantic column of smoke which streamed +up from behind a small clump of trees in the neighbourhood and +hung like an immense ostrich feather over the landscape. + +"A house on fire?" asked Bradstreet as the train steamed off +again on its way. + +"Yes, sir!" said the station-master. + +"When did it break out?" + +"I hear that it was during the night, sir, but it has got worse, +and the whole place is in a blaze." + +"Whose house is it?" + +"Dr. Becher's." + +"Tell me," broke in the engineer, "is Dr. Becher a German, very +thin, with a long, sharp nose?" + +The station-master laughed heartily. "No, sir, Dr. Becher is an +Englishman, and there isn't a man in the parish who has a +better-lined waistcoat. But he has a gentleman staying with him, +a patient, as I understand, who is a foreigner, and he looks as +if a little good Berkshire beef would do him no harm." + +The station-master had not finished his speech before we were all +hastening in the direction of the fire. The road topped a low +hill, and there was a great widespread whitewashed building in +front of us, spouting fire at every chink and window, while in +the garden in front three fire-engines were vainly striving to +keep the flames under. + +"That's it!" cried Hatherley, in intense excitement. "There is +the gravel-drive, and there are the rose-bushes where I lay. That +second window is the one that I jumped from." + +"Well, at least," said Holmes, "you have had your revenge upon +them. There can be no question that it was your oil-lamp which, +when it was crushed in the press, set fire to the wooden walls, +though no doubt they were too excited in the chase after you to +observe it at the time. Now keep your eyes open in this crowd for +your friends of last night, though I very much fear that they are +a good hundred miles off by now." + +And Holmes' fears came to be realised, for from that day to this +no word has ever been heard either of the beautiful woman, the +sinister German, or the morose Englishman. Early that morning a +peasant had met a cart containing several people and some very +bulky boxes driving rapidly in the direction of Reading, but +there all traces of the fugitives disappeared, and even Holmes' +ingenuity failed ever to discover the least clue as to their +whereabouts. + +The firemen had been much perturbed at the strange arrangements +which they had found within, and still more so by discovering a +newly severed human thumb upon a window-sill of the second floor. +About sunset, however, their efforts were at last successful, and +they subdued the flames, but not before the roof had fallen in, +and the whole place been reduced to such absolute ruin that, save +some twisted cylinders and iron piping, not a trace remained of +the machinery which had cost our unfortunate acquaintance so +dearly. Large masses of nickel and of tin were discovered stored +in an out-house, but no coins were to be found, which may have +explained the presence of those bulky boxes which have been +already referred to. + +How our hydraulic engineer had been conveyed from the garden to +the spot where he recovered his senses might have remained +forever a mystery were it not for the soft mould, which told us a +very plain tale. He had evidently been carried down by two +persons, one of whom had remarkably small feet and the other +unusually large ones. On the whole, it was most probable that the +silent Englishman, being less bold or less murderous than his +companion, had assisted the woman to bear the unconscious man out +of the way of danger. + +"Well," said our engineer ruefully as we took our seats to return +once more to London, "it has been a pretty business for me! I +have lost my thumb and I have lost a fifty-guinea fee, and what +have I gained?" + +"Experience," said Holmes, laughing. "Indirectly it may be of +value, you know; you have only to put it into words to gain the +reputation of being excellent company for the remainder of your +existence." + + + +X. THE ADVENTURE OF THE NOBLE BACHELOR + +The Lord St. Simon marriage, and its curious termination, have +long ceased to be a subject of interest in those exalted circles +in which the unfortunate bridegroom moves. Fresh scandals have +eclipsed it, and their more piquant details have drawn the +gossips away from this four-year-old drama. As I have reason to +believe, however, that the full facts have never been revealed to +the general public, and as my friend Sherlock Holmes had a +considerable share in clearing the matter up, I feel that no +memoir of him would be complete without some little sketch of +this remarkable episode. + +It was a few weeks before my own marriage, during the days when I +was still sharing rooms with Holmes in Baker Street, that he came +home from an afternoon stroll to find a letter on the table +waiting for him. I had remained indoors all day, for the weather +had taken a sudden turn to rain, with high autumnal winds, and +the Jezail bullet which I had brought back in one of my limbs as +a relic of my Afghan campaign throbbed with dull persistence. +With my body in one easy-chair and my legs upon another, I had +surrounded myself with a cloud of newspapers until at last, +saturated with the news of the day, I tossed them all aside and +lay listless, watching the huge crest and monogram upon the +envelope upon the table and wondering lazily who my friend's +noble correspondent could be. + +"Here is a very fashionable epistle," I remarked as he entered. +"Your morning letters, if I remember right, were from a +fish-monger and a tide-waiter." + +"Yes, my correspondence has certainly the charm of variety," he +answered, smiling, "and the humbler are usually the more +interesting. This looks like one of those unwelcome social +summonses which call upon a man either to be bored or to lie." + +He broke the seal and glanced over the contents. + +"Oh, come, it may prove to be something of interest, after all." + +"Not social, then?" + +"No, distinctly professional." + +"And from a noble client?" + +"One of the highest in England." + +"My dear fellow, I congratulate you." + +"I assure you, Watson, without affectation, that the status of my +client is a matter of less moment to me than the interest of his +case. It is just possible, however, that that also may not be +wanting in this new investigation. You have been reading the +papers diligently of late, have you not?" + +"It looks like it," said I ruefully, pointing to a huge bundle in +the corner. "I have had nothing else to do." + +"It is fortunate, for you will perhaps be able to post me up. I +read nothing except the criminal news and the agony column. The +latter is always instructive. But if you have followed recent +events so closely you must have read about Lord St. Simon and his +wedding?" + +"Oh, yes, with the deepest interest." + +"That is well. The letter which I hold in my hand is from Lord +St. Simon. I will read it to you, and in return you must turn +over these papers and let me have whatever bears upon the matter. +This is what he says: + +"'MY DEAR MR. SHERLOCK HOLMES:--Lord Backwater tells me that I +may place implicit reliance upon your judgment and discretion. I +have determined, therefore, to call upon you and to consult you +in reference to the very painful event which has occurred in +connection with my wedding. Mr. Lestrade, of Scotland Yard, is +acting already in the matter, but he assures me that he sees no +objection to your co-operation, and that he even thinks that +it might be of some assistance. I will call at four o'clock in +the afternoon, and, should you have any other engagement at that +time, I hope that you will postpone it, as this matter is of +paramount importance. Yours faithfully, ST. SIMON.' + +"It is dated from Grosvenor Mansions, written with a quill pen, +and the noble lord has had the misfortune to get a smear of ink +upon the outer side of his right little finger," remarked Holmes +as he folded up the epistle. + +"He says four o'clock. It is three now. He will be here in an +hour." + +"Then I have just time, with your assistance, to get clear upon +the subject. Turn over those papers and arrange the extracts in +their order of time, while I take a glance as to who our client +is." He picked a red-covered volume from a line of books of +reference beside the mantelpiece. "Here he is," said he, sitting +down and flattening it out upon his knee. "'Lord Robert Walsingham +de Vere St. Simon, second son of the Duke of Balmoral.' Hum! 'Arms: +Azure, three caltrops in chief over a fess sable. Born in 1846.' +He's forty-one years of age, which is mature for marriage. Was +Under-Secretary for the colonies in a late administration. The +Duke, his father, was at one time Secretary for Foreign Affairs. +They inherit Plantagenet blood by direct descent, and Tudor on +the distaff side. Ha! Well, there is nothing very instructive in +all this. I think that I must turn to you Watson, for something +more solid." + +"I have very little difficulty in finding what I want," said I, +"for the facts are quite recent, and the matter struck me as +remarkable. I feared to refer them to you, however, as I knew +that you had an inquiry on hand and that you disliked the +intrusion of other matters." + +"Oh, you mean the little problem of the Grosvenor Square +furniture van. That is quite cleared up now--though, indeed, it +was obvious from the first. Pray give me the results of your +newspaper selections." + +"Here is the first notice which I can find. It is in the personal +column of the Morning Post, and dates, as you see, some weeks +back: 'A marriage has been arranged,' it says, 'and will, if +rumour is correct, very shortly take place, between Lord Robert +St. Simon, second son of the Duke of Balmoral, and Miss Hatty +Doran, the only daughter of Aloysius Doran. Esq., of San +Francisco, Cal., U.S.A.' That is all." + +"Terse and to the point," remarked Holmes, stretching his long, +thin legs towards the fire. + +"There was a paragraph amplifying this in one of the society +papers of the same week. Ah, here it is: 'There will soon be a +call for protection in the marriage market, for the present +free-trade principle appears to tell heavily against our home +product. One by one the management of the noble houses of Great +Britain is passing into the hands of our fair cousins from across +the Atlantic. An important addition has been made during the last +week to the list of the prizes which have been borne away by +these charming invaders. Lord St. Simon, who has shown himself +for over twenty years proof against the little god's arrows, has +now definitely announced his approaching marriage with Miss Hatty +Doran, the fascinating daughter of a California millionaire. Miss +Doran, whose graceful figure and striking face attracted much +attention at the Westbury House festivities, is an only child, +and it is currently reported that her dowry will run to +considerably over the six figures, with expectancies for the +future. As it is an open secret that the Duke of Balmoral has +been compelled to sell his pictures within the last few years, +and as Lord St. Simon has no property of his own save the small +estate of Birchmoor, it is obvious that the Californian heiress +is not the only gainer by an alliance which will enable her to +make the easy and common transition from a Republican lady to a +British peeress.'" + +"Anything else?" asked Holmes, yawning. + +"Oh, yes; plenty. Then there is another note in the Morning Post +to say that the marriage would be an absolutely quiet one, that it +would be at St. George's, Hanover Square, that only half a dozen +intimate friends would be invited, and that the party would +return to the furnished house at Lancaster Gate which has been +taken by Mr. Aloysius Doran. Two days later--that is, on +Wednesday last--there is a curt announcement that the wedding had +taken place, and that the honeymoon would be passed at Lord +Backwater's place, near Petersfield. Those are all the notices +which appeared before the disappearance of the bride." + +"Before the what?" asked Holmes with a start. + +"The vanishing of the lady." + +"When did she vanish, then?" + +"At the wedding breakfast." + +"Indeed. This is more interesting than it promised to be; quite +dramatic, in fact." + +"Yes; it struck me as being a little out of the common." + +"They often vanish before the ceremony, and occasionally during +the honeymoon; but I cannot call to mind anything quite so prompt +as this. Pray let me have the details." + +"I warn you that they are very incomplete." + +"Perhaps we may make them less so." + +"Such as they are, they are set forth in a single article of a +morning paper of yesterday, which I will read to you. It is +headed, 'Singular Occurrence at a Fashionable Wedding': + +"'The family of Lord Robert St. Simon has been thrown into the +greatest consternation by the strange and painful episodes which +have taken place in connection with his wedding. The ceremony, as +shortly announced in the papers of yesterday, occurred on the +previous morning; but it is only now that it has been possible to +confirm the strange rumours which have been so persistently +floating about. In spite of the attempts of the friends to hush +the matter up, so much public attention has now been drawn to it +that no good purpose can be served by affecting to disregard what +is a common subject for conversation. + +"'The ceremony, which was performed at St. George's, Hanover +Square, was a very quiet one, no one being present save the +father of the bride, Mr. Aloysius Doran, the Duchess of Balmoral, +Lord Backwater, Lord Eustace and Lady Clara St. Simon (the +younger brother and sister of the bridegroom), and Lady Alicia +Whittington. The whole party proceeded afterwards to the house of +Mr. Aloysius Doran, at Lancaster Gate, where breakfast had been +prepared. It appears that some little trouble was caused by a +woman, whose name has not been ascertained, who endeavoured to +force her way into the house after the bridal party, alleging +that she had some claim upon Lord St. Simon. It was only after a +painful and prolonged scene that she was ejected by the butler +and the footman. The bride, who had fortunately entered the house +before this unpleasant interruption, had sat down to breakfast +with the rest, when she complained of a sudden indisposition and +retired to her room. Her prolonged absence having caused some +comment, her father followed her, but learned from her maid that +she had only come up to her chamber for an instant, caught up an +ulster and bonnet, and hurried down to the passage. One of the +footmen declared that he had seen a lady leave the house thus +apparelled, but had refused to credit that it was his mistress, +believing her to be with the company. On ascertaining that his +daughter had disappeared, Mr. Aloysius Doran, in conjunction with +the bridegroom, instantly put themselves in communication with +the police, and very energetic inquiries are being made, which +will probably result in a speedy clearing up of this very +singular business. Up to a late hour last night, however, nothing +had transpired as to the whereabouts of the missing lady. There +are rumours of foul play in the matter, and it is said that the +police have caused the arrest of the woman who had caused the +original disturbance, in the belief that, from jealousy or some +other motive, she may have been concerned in the strange +disappearance of the bride.'" + +"And is that all?" + +"Only one little item in another of the morning papers, but it is +a suggestive one." + +"And it is--" + +"That Miss Flora Millar, the lady who had caused the disturbance, +has actually been arrested. It appears that she was formerly a +danseuse at the Allegro, and that she has known the bridegroom +for some years. There are no further particulars, and the whole +case is in your hands now--so far as it has been set forth in the +public press." + +"And an exceedingly interesting case it appears to be. I would +not have missed it for worlds. But there is a ring at the bell, +Watson, and as the clock makes it a few minutes after four, I +have no doubt that this will prove to be our noble client. Do not +dream of going, Watson, for I very much prefer having a witness, +if only as a check to my own memory." + +"Lord Robert St. Simon," announced our page-boy, throwing open +the door. A gentleman entered, with a pleasant, cultured face, +high-nosed and pale, with something perhaps of petulance about +the mouth, and with the steady, well-opened eye of a man whose +pleasant lot it had ever been to command and to be obeyed. His +manner was brisk, and yet his general appearance gave an undue +impression of age, for he had a slight forward stoop and a little +bend of the knees as he walked. His hair, too, as he swept off +his very curly-brimmed hat, was grizzled round the edges and thin +upon the top. As to his dress, it was careful to the verge of +foppishness, with high collar, black frock-coat, white waistcoat, +yellow gloves, patent-leather shoes, and light-coloured gaiters. +He advanced slowly into the room, turning his head from left to +right, and swinging in his right hand the cord which held his +golden eyeglasses. + +"Good-day, Lord St. Simon," said Holmes, rising and bowing. "Pray +take the basket-chair. This is my friend and colleague, Dr. +Watson. Draw up a little to the fire, and we will talk this +matter over." + +"A most painful matter to me, as you can most readily imagine, +Mr. Holmes. I have been cut to the quick. I understand that you +have already managed several delicate cases of this sort, sir, +though I presume that they were hardly from the same class of +society." + +"No, I am descending." + +"I beg pardon." + +"My last client of the sort was a king." + +"Oh, really! I had no idea. And which king?" + +"The King of Scandinavia." + +"What! Had he lost his wife?" + +"You can understand," said Holmes suavely, "that I extend to the +affairs of my other clients the same secrecy which I promise to +you in yours." + +"Of course! Very right! very right! I'm sure I beg pardon. As to +my own case, I am ready to give you any information which may +assist you in forming an opinion." + +"Thank you. I have already learned all that is in the public +prints, nothing more. I presume that I may take it as correct--this +article, for example, as to the disappearance of the bride." + +Lord St. Simon glanced over it. "Yes, it is correct, as far as it +goes." + +"But it needs a great deal of supplementing before anyone could +offer an opinion. I think that I may arrive at my facts most +directly by questioning you." + +"Pray do so." + +"When did you first meet Miss Hatty Doran?" + +"In San Francisco, a year ago." + +"You were travelling in the States?" + +"Yes." + +"Did you become engaged then?" + +"No." + +"But you were on a friendly footing?" + +"I was amused by her society, and she could see that I was +amused." + +"Her father is very rich?" + +"He is said to be the richest man on the Pacific slope." + +"And how did he make his money?" + +"In mining. He had nothing a few years ago. Then he struck gold, +invested it, and came up by leaps and bounds." + +"Now, what is your own impression as to the young lady's--your +wife's character?" + +The nobleman swung his glasses a little faster and stared down +into the fire. "You see, Mr. Holmes," said he, "my wife was +twenty before her father became a rich man. During that time she +ran free in a mining camp and wandered through woods or +mountains, so that her education has come from Nature rather than +from the schoolmaster. She is what we call in England a tomboy, +with a strong nature, wild and free, unfettered by any sort of +traditions. She is impetuous--volcanic, I was about to say. She +is swift in making up her mind and fearless in carrying out her +resolutions. On the other hand, I would not have given her the +name which I have the honour to bear"--he gave a little stately +cough--"had not I thought her to be at bottom a noble woman. I +believe that she is capable of heroic self-sacrifice and that +anything dishonourable would be repugnant to her." + +"Have you her photograph?" + +"I brought this with me." He opened a locket and showed us the +full face of a very lovely woman. It was not a photograph but an +ivory miniature, and the artist had brought out the full effect +of the lustrous black hair, the large dark eyes, and the +exquisite mouth. Holmes gazed long and earnestly at it. Then he +closed the locket and handed it back to Lord St. Simon. + +"The young lady came to London, then, and you renewed your +acquaintance?" + +"Yes, her father brought her over for this last London season. I +met her several times, became engaged to her, and have now +married her." + +"She brought, I understand, a considerable dowry?" + +"A fair dowry. Not more than is usual in my family." + +"And this, of course, remains to you, since the marriage is a +fait accompli?" + +"I really have made no inquiries on the subject." + +"Very naturally not. Did you see Miss Doran on the day before the +wedding?" + +"Yes." + +"Was she in good spirits?" + +"Never better. She kept talking of what we should do in our +future lives." + +"Indeed! That is very interesting. And on the morning of the +wedding?" + +"She was as bright as possible--at least until after the +ceremony." + +"And did you observe any change in her then?" + +"Well, to tell the truth, I saw then the first signs that I had +ever seen that her temper was just a little sharp. The incident +however, was too trivial to relate and can have no possible +bearing upon the case." + +"Pray let us have it, for all that." + +"Oh, it is childish. She dropped her bouquet as we went towards +the vestry. She was passing the front pew at the time, and it +fell over into the pew. There was a moment's delay, but the +gentleman in the pew handed it up to her again, and it did not +appear to be the worse for the fall. Yet when I spoke to her of +the matter, she answered me abruptly; and in the carriage, on our +way home, she seemed absurdly agitated over this trifling cause." + +"Indeed! You say that there was a gentleman in the pew. Some of +the general public were present, then?" + +"Oh, yes. It is impossible to exclude them when the church is +open." + +"This gentleman was not one of your wife's friends?" + +"No, no; I call him a gentleman by courtesy, but he was quite a +common-looking person. I hardly noticed his appearance. But +really I think that we are wandering rather far from the point." + +"Lady St. Simon, then, returned from the wedding in a less +cheerful frame of mind than she had gone to it. What did she do +on re-entering her father's house?" + +"I saw her in conversation with her maid." + +"And who is her maid?" + +"Alice is her name. She is an American and came from California +with her." + +"A confidential servant?" + +"A little too much so. It seemed to me that her mistress allowed +her to take great liberties. Still, of course, in America they +look upon these things in a different way." + +"How long did she speak to this Alice?" + +"Oh, a few minutes. I had something else to think of." + +"You did not overhear what they said?" + +"Lady St. Simon said something about 'jumping a claim.' She was +accustomed to use slang of the kind. I have no idea what she +meant." + +"American slang is very expressive sometimes. And what did your +wife do when she finished speaking to her maid?" + +"She walked into the breakfast-room." + +"On your arm?" + +"No, alone. She was very independent in little matters like that. +Then, after we had sat down for ten minutes or so, she rose +hurriedly, muttered some words of apology, and left the room. She +never came back." + +"But this maid, Alice, as I understand, deposes that she went to +her room, covered her bride's dress with a long ulster, put on a +bonnet, and went out." + +"Quite so. And she was afterwards seen walking into Hyde Park in +company with Flora Millar, a woman who is now in custody, and who +had already made a disturbance at Mr. Doran's house that +morning." + +"Ah, yes. I should like a few particulars as to this young lady, +and your relations to her." + +Lord St. Simon shrugged his shoulders and raised his eyebrows. +"We have been on a friendly footing for some years--I may say on +a very friendly footing. She used to be at the Allegro. I have +not treated her ungenerously, and she had no just cause of +complaint against me, but you know what women are, Mr. Holmes. +Flora was a dear little thing, but exceedingly hot-headed and +devotedly attached to me. She wrote me dreadful letters when she +heard that I was about to be married, and, to tell the truth, the +reason why I had the marriage celebrated so quietly was that I +feared lest there might be a scandal in the church. She came to +Mr. Doran's door just after we returned, and she endeavoured to +push her way in, uttering very abusive expressions towards my +wife, and even threatening her, but I had foreseen the +possibility of something of the sort, and I had two police +fellows there in private clothes, who soon pushed her out again. +She was quiet when she saw that there was no good in making a +row." + +"Did your wife hear all this?" + +"No, thank goodness, she did not." + +"And she was seen walking with this very woman afterwards?" + +"Yes. That is what Mr. Lestrade, of Scotland Yard, looks upon as +so serious. It is thought that Flora decoyed my wife out and laid +some terrible trap for her." + +"Well, it is a possible supposition." + +"You think so, too?" + +"I did not say a probable one. But you do not yourself look upon +this as likely?" + +"I do not think Flora would hurt a fly." + +"Still, jealousy is a strange transformer of characters. Pray +what is your own theory as to what took place?" + +"Well, really, I came to seek a theory, not to propound one. I +have given you all the facts. Since you ask me, however, I may +say that it has occurred to me as possible that the excitement of +this affair, the consciousness that she had made so immense a +social stride, had the effect of causing some little nervous +disturbance in my wife." + +"In short, that she had become suddenly deranged?" + +"Well, really, when I consider that she has turned her back--I +will not say upon me, but upon so much that many have aspired to +without success--I can hardly explain it in any other fashion." + +"Well, certainly that is also a conceivable hypothesis," said +Holmes, smiling. "And now, Lord St. Simon, I think that I have +nearly all my data. May I ask whether you were seated at the +breakfast-table so that you could see out of the window?" + +"We could see the other side of the road and the Park." + +"Quite so. Then I do not think that I need to detain you longer. +I shall communicate with you." + +"Should you be fortunate enough to solve this problem," said our +client, rising. + +"I have solved it." + +"Eh? What was that?" + +"I say that I have solved it." + +"Where, then, is my wife?" + +"That is a detail which I shall speedily supply." + +Lord St. Simon shook his head. "I am afraid that it will take +wiser heads than yours or mine," he remarked, and bowing in a +stately, old-fashioned manner he departed. + +"It is very good of Lord St. Simon to honour my head by putting +it on a level with his own," said Sherlock Holmes, laughing. "I +think that I shall have a whisky and soda and a cigar after all +this cross-questioning. I had formed my conclusions as to the +case before our client came into the room." + +"My dear Holmes!" + +"I have notes of several similar cases, though none, as I +remarked before, which were quite as prompt. My whole examination +served to turn my conjecture into a certainty. Circumstantial +evidence is occasionally very convincing, as when you find a +trout in the milk, to quote Thoreau's example." + +"But I have heard all that you have heard." + +"Without, however, the knowledge of pre-existing cases which +serves me so well. There was a parallel instance in Aberdeen some +years back, and something on very much the same lines at Munich +the year after the Franco-Prussian War. It is one of these +cases--but, hullo, here is Lestrade! Good-afternoon, Lestrade! +You will find an extra tumbler upon the sideboard, and there are +cigars in the box." + +The official detective was attired in a pea-jacket and cravat, +which gave him a decidedly nautical appearance, and he carried a +black canvas bag in his hand. With a short greeting he seated +himself and lit the cigar which had been offered to him. + +"What's up, then?" asked Holmes with a twinkle in his eye. "You +look dissatisfied." + +"And I feel dissatisfied. It is this infernal St. Simon marriage +case. I can make neither head nor tail of the business." + +"Really! You surprise me." + +"Who ever heard of such a mixed affair? Every clue seems to slip +through my fingers. I have been at work upon it all day." + +"And very wet it seems to have made you," said Holmes laying his +hand upon the arm of the pea-jacket. + +"Yes, I have been dragging the Serpentine." + +"In heaven's name, what for?" + +"In search of the body of Lady St. Simon." + +Sherlock Holmes leaned back in his chair and laughed heartily. + +"Have you dragged the basin of Trafalgar Square fountain?" he +asked. + +"Why? What do you mean?" + +"Because you have just as good a chance of finding this lady in +the one as in the other." + +Lestrade shot an angry glance at my companion. "I suppose you +know all about it," he snarled. + +"Well, I have only just heard the facts, but my mind is made up." + +"Oh, indeed! Then you think that the Serpentine plays no part in +the matter?" + +"I think it very unlikely." + +"Then perhaps you will kindly explain how it is that we found +this in it?" He opened his bag as he spoke, and tumbled onto the +floor a wedding-dress of watered silk, a pair of white satin +shoes and a bride's wreath and veil, all discoloured and soaked +in water. "There," said he, putting a new wedding-ring upon the +top of the pile. "There is a little nut for you to crack, Master +Holmes." + +"Oh, indeed!" said my friend, blowing blue rings into the air. +"You dragged them from the Serpentine?" + +"No. They were found floating near the margin by a park-keeper. +They have been identified as her clothes, and it seemed to me +that if the clothes were there the body would not be far off." + +"By the same brilliant reasoning, every man's body is to be found +in the neighbourhood of his wardrobe. And pray what did you hope +to arrive at through this?" + +"At some evidence implicating Flora Millar in the disappearance." + +"I am afraid that you will find it difficult." + +"Are you, indeed, now?" cried Lestrade with some bitterness. "I +am afraid, Holmes, that you are not very practical with your +deductions and your inferences. You have made two blunders in as +many minutes. This dress does implicate Miss Flora Millar." + +"And how?" + +"In the dress is a pocket. In the pocket is a card-case. In the +card-case is a note. And here is the very note." He slapped it +down upon the table in front of him. "Listen to this: 'You will +see me when all is ready. Come at once. F.H.M.' Now my theory all +along has been that Lady St. Simon was decoyed away by Flora +Millar, and that she, with confederates, no doubt, was +responsible for her disappearance. Here, signed with her +initials, is the very note which was no doubt quietly slipped +into her hand at the door and which lured her within their +reach." + +"Very good, Lestrade," said Holmes, laughing. "You really are +very fine indeed. Let me see it." He took up the paper in a +listless way, but his attention instantly became riveted, and he +gave a little cry of satisfaction. "This is indeed important," +said he. + +"Ha! you find it so?" + +"Extremely so. I congratulate you warmly." + +Lestrade rose in his triumph and bent his head to look. "Why," he +shrieked, "you're looking at the wrong side!" + +"On the contrary, this is the right side." + +"The right side? You're mad! Here is the note written in pencil +over here." + +"And over here is what appears to be the fragment of a hotel +bill, which interests me deeply." + +"There's nothing in it. I looked at it before," said Lestrade. +"'Oct. 4th, rooms 8s., breakfast 2s. 6d., cocktail 1s., lunch 2s. +6d., glass sherry, 8d.' I see nothing in that." + +"Very likely not. It is most important, all the same. As to the +note, it is important also, or at least the initials are, so I +congratulate you again." + +"I've wasted time enough," said Lestrade, rising. "I believe in +hard work and not in sitting by the fire spinning fine theories. +Good-day, Mr. Holmes, and we shall see which gets to the bottom +of the matter first." He gathered up the garments, thrust them +into the bag, and made for the door. + +"Just one hint to you, Lestrade," drawled Holmes before his rival +vanished; "I will tell you the true solution of the matter. Lady +St. Simon is a myth. There is not, and there never has been, any +such person." + +Lestrade looked sadly at my companion. Then he turned to me, +tapped his forehead three times, shook his head solemnly, and +hurried away. + +He had hardly shut the door behind him when Holmes rose to put on +his overcoat. "There is something in what the fellow says about +outdoor work," he remarked, "so I think, Watson, that I must +leave you to your papers for a little." + +It was after five o'clock when Sherlock Holmes left me, but I had +no time to be lonely, for within an hour there arrived a +confectioner's man with a very large flat box. This he unpacked +with the help of a youth whom he had brought with him, and +presently, to my very great astonishment, a quite epicurean +little cold supper began to be laid out upon our humble +lodging-house mahogany. There were a couple of brace of cold +woodcock, a pheasant, a pt de foie gras pie with a group of +ancient and cobwebby bottles. Having laid out all these luxuries, +my two visitors vanished away, like the genii of the Arabian +Nights, with no explanation save that the things had been paid +for and were ordered to this address. + +Just before nine o'clock Sherlock Holmes stepped briskly into the +room. His features were gravely set, but there was a light in his +eye which made me think that he had not been disappointed in his +conclusions. + +"They have laid the supper, then," he said, rubbing his hands. + +"You seem to expect company. They have laid for five." + +"Yes, I fancy we may have some company dropping in," said he. "I +am surprised that Lord St. Simon has not already arrived. Ha! I +fancy that I hear his step now upon the stairs." + +It was indeed our visitor of the afternoon who came bustling in, +dangling his glasses more vigorously than ever, and with a very +perturbed expression upon his aristocratic features. + +"My messenger reached you, then?" asked Holmes. + +"Yes, and I confess that the contents startled me beyond measure. +Have you good authority for what you say?" + +"The best possible." + +Lord St. Simon sank into a chair and passed his hand over his +forehead. + +"What will the Duke say," he murmured, "when he hears that one of +the family has been subjected to such humiliation?" + +"It is the purest accident. I cannot allow that there is any +humiliation." + +"Ah, you look on these things from another standpoint." + +"I fail to see that anyone is to blame. I can hardly see how the +lady could have acted otherwise, though her abrupt method of +doing it was undoubtedly to be regretted. Having no mother, she +had no one to advise her at such a crisis." + +"It was a slight, sir, a public slight," said Lord St. Simon, +tapping his fingers upon the table. + +"You must make allowance for this poor girl, placed in so +unprecedented a position." + +"I will make no allowance. I am very angry indeed, and I have +been shamefully used." + +"I think that I heard a ring," said Holmes. "Yes, there are steps +on the landing. If I cannot persuade you to take a lenient view +of the matter, Lord St. Simon, I have brought an advocate here +who may be more successful." He opened the door and ushered in a +lady and gentleman. "Lord St. Simon," said he "allow me to +introduce you to Mr. and Mrs. Francis Hay Moulton. The lady, I +think, you have already met." + +At the sight of these newcomers our client had sprung from his +seat and stood very erect, with his eyes cast down and his hand +thrust into the breast of his frock-coat, a picture of offended +dignity. The lady had taken a quick step forward and had held out +her hand to him, but he still refused to raise his eyes. It was +as well for his resolution, perhaps, for her pleading face was +one which it was hard to resist. + +"You're angry, Robert," said she. "Well, I guess you have every +cause to be." + +"Pray make no apology to me," said Lord St. Simon bitterly. + +"Oh, yes, I know that I have treated you real bad and that I +should have spoken to you before I went; but I was kind of +rattled, and from the time when I saw Frank here again I just +didn't know what I was doing or saying. I only wonder I didn't +fall down and do a faint right there before the altar." + +"Perhaps, Mrs. Moulton, you would like my friend and me to leave +the room while you explain this matter?" + +"If I may give an opinion," remarked the strange gentleman, +"we've had just a little too much secrecy over this business +already. For my part, I should like all Europe and America to +hear the rights of it." He was a small, wiry, sunburnt man, +clean-shaven, with a sharp face and alert manner. + +"Then I'll tell our story right away," said the lady. "Frank here +and I met in '84, in McQuire's camp, near the Rockies, where pa +was working a claim. We were engaged to each other, Frank and I; +but then one day father struck a rich pocket and made a pile, +while poor Frank here had a claim that petered out and came to +nothing. The richer pa grew the poorer was Frank; so at last pa +wouldn't hear of our engagement lasting any longer, and he took +me away to 'Frisco. Frank wouldn't throw up his hand, though; so +he followed me there, and he saw me without pa knowing anything +about it. It would only have made him mad to know, so we just +fixed it all up for ourselves. Frank said that he would go and +make his pile, too, and never come back to claim me until he had +as much as pa. So then I promised to wait for him to the end of +time and pledged myself not to marry anyone else while he lived. +'Why shouldn't we be married right away, then,' said he, 'and +then I will feel sure of you; and I won't claim to be your +husband until I come back?' Well, we talked it over, and he had +fixed it all up so nicely, with a clergyman all ready in waiting, +that we just did it right there; and then Frank went off to seek +his fortune, and I went back to pa. + +"The next I heard of Frank was that he was in Montana, and then +he went prospecting in Arizona, and then I heard of him from New +Mexico. After that came a long newspaper story about how a +miners' camp had been attacked by Apache Indians, and there was +my Frank's name among the killed. I fainted dead away, and I was +very sick for months after. Pa thought I had a decline and took +me to half the doctors in 'Frisco. Not a word of news came for a +year and more, so that I never doubted that Frank was really +dead. Then Lord St. Simon came to 'Frisco, and we came to London, +and a marriage was arranged, and pa was very pleased, but I felt +all the time that no man on this earth would ever take the place +in my heart that had been given to my poor Frank. + +"Still, if I had married Lord St. Simon, of course I'd have done +my duty by him. We can't command our love, but we can our +actions. I went to the altar with him with the intention to make +him just as good a wife as it was in me to be. But you may +imagine what I felt when, just as I came to the altar rails, I +glanced back and saw Frank standing and looking at me out of the +first pew. I thought it was his ghost at first; but when I looked +again there he was still, with a kind of question in his eyes, as +if to ask me whether I were glad or sorry to see him. I wonder I +didn't drop. I know that everything was turning round, and the +words of the clergyman were just like the buzz of a bee in my +ear. I didn't know what to do. Should I stop the service and make +a scene in the church? I glanced at him again, and he seemed to +know what I was thinking, for he raised his finger to his lips to +tell me to be still. Then I saw him scribble on a piece of paper, +and I knew that he was writing me a note. As I passed his pew on +the way out I dropped my bouquet over to him, and he slipped the +note into my hand when he returned me the flowers. It was only a +line asking me to join him when he made the sign to me to do so. +Of course I never doubted for a moment that my first duty was now +to him, and I determined to do just whatever he might direct. + +"When I got back I told my maid, who had known him in California, +and had always been his friend. I ordered her to say nothing, but +to get a few things packed and my ulster ready. I know I ought to +have spoken to Lord St. Simon, but it was dreadful hard before +his mother and all those great people. I just made up my mind to +run away and explain afterwards. I hadn't been at the table ten +minutes before I saw Frank out of the window at the other side of +the road. He beckoned to me and then began walking into the Park. +I slipped out, put on my things, and followed him. Some woman +came talking something or other about Lord St. Simon to +me--seemed to me from the little I heard as if he had a little +secret of his own before marriage also--but I managed to get away +from her and soon overtook Frank. We got into a cab together, and +away we drove to some lodgings he had taken in Gordon Square, and +that was my true wedding after all those years of waiting. Frank +had been a prisoner among the Apaches, had escaped, came on to +'Frisco, found that I had given him up for dead and had gone to +England, followed me there, and had come upon me at last on the +very morning of my second wedding." + +"I saw it in a paper," explained the American. "It gave the name +and the church but not where the lady lived." + +"Then we had a talk as to what we should do, and Frank was all +for openness, but I was so ashamed of it all that I felt as if I +should like to vanish away and never see any of them again--just +sending a line to pa, perhaps, to show him that I was alive. It +was awful to me to think of all those lords and ladies sitting +round that breakfast-table and waiting for me to come back. So +Frank took my wedding-clothes and things and made a bundle of +them, so that I should not be traced, and dropped them away +somewhere where no one could find them. It is likely that we +should have gone on to Paris to-morrow, only that this good +gentleman, Mr. Holmes, came round to us this evening, though how +he found us is more than I can think, and he showed us very +clearly and kindly that I was wrong and that Frank was right, and +that we should be putting ourselves in the wrong if we were so +secret. Then he offered to give us a chance of talking to Lord +St. Simon alone, and so we came right away round to his rooms at +once. Now, Robert, you have heard it all, and I am very sorry if +I have given you pain, and I hope that you do not think very +meanly of me." + +Lord St. Simon had by no means relaxed his rigid attitude, but +had listened with a frowning brow and a compressed lip to this +long narrative. + +"Excuse me," he said, "but it is not my custom to discuss my most +intimate personal affairs in this public manner." + +"Then you won't forgive me? You won't shake hands before I go?" + +"Oh, certainly, if it would give you any pleasure." He put out +his hand and coldly grasped that which she extended to him. + +"I had hoped," suggested Holmes, "that you would have joined us +in a friendly supper." + +"I think that there you ask a little too much," responded his +Lordship. "I may be forced to acquiesce in these recent +developments, but I can hardly be expected to make merry over +them. I think that with your permission I will now wish you all a +very good-night." He included us all in a sweeping bow and +stalked out of the room. + +"Then I trust that you at least will honour me with your +company," said Sherlock Holmes. "It is always a joy to meet an +American, Mr. Moulton, for I am one of those who believe that the +folly of a monarch and the blundering of a minister in far-gone +years will not prevent our children from being some day citizens +of the same world-wide country under a flag which shall be a +quartering of the Union Jack with the Stars and Stripes." + +"The case has been an interesting one," remarked Holmes when our +visitors had left us, "because it serves to show very clearly how +simple the explanation may be of an affair which at first sight +seems to be almost inexplicable. Nothing could be more natural +than the sequence of events as narrated by this lady, and nothing +stranger than the result when viewed, for instance, by Mr. +Lestrade of Scotland Yard." + +"You were not yourself at fault at all, then?" + +"From the first, two facts were very obvious to me, the one that +the lady had been quite willing to undergo the wedding ceremony, +the other that she had repented of it within a few minutes of +returning home. Obviously something had occurred during the +morning, then, to cause her to change her mind. What could that +something be? She could not have spoken to anyone when she was +out, for she had been in the company of the bridegroom. Had she +seen someone, then? If she had, it must be someone from America +because she had spent so short a time in this country that she +could hardly have allowed anyone to acquire so deep an influence +over her that the mere sight of him would induce her to change +her plans so completely. You see we have already arrived, by a +process of exclusion, at the idea that she might have seen an +American. Then who could this American be, and why should he +possess so much influence over her? It might be a lover; it might +be a husband. Her young womanhood had, I knew, been spent in +rough scenes and under strange conditions. So far I had got +before I ever heard Lord St. Simon's narrative. When he told us +of a man in a pew, of the change in the bride's manner, of so +transparent a device for obtaining a note as the dropping of a +bouquet, of her resort to her confidential maid, and of her very +significant allusion to claim-jumping--which in miners' parlance +means taking possession of that which another person has a prior +claim to--the whole situation became absolutely clear. She had +gone off with a man, and the man was either a lover or was a +previous husband--the chances being in favour of the latter." + +"And how in the world did you find them?" + +"It might have been difficult, but friend Lestrade held +information in his hands the value of which he did not himself +know. The initials were, of course, of the highest importance, +but more valuable still was it to know that within a week he had +settled his bill at one of the most select London hotels." + +"How did you deduce the select?" + +"By the select prices. Eight shillings for a bed and eightpence +for a glass of sherry pointed to one of the most expensive +hotels. There are not many in London which charge at that rate. +In the second one which I visited in Northumberland Avenue, I +learned by an inspection of the book that Francis H. Moulton, an +American gentleman, had left only the day before, and on looking +over the entries against him, I came upon the very items which I +had seen in the duplicate bill. His letters were to be forwarded +to 226 Gordon Square; so thither I travelled, and being fortunate +enough to find the loving couple at home, I ventured to give them +some paternal advice and to point out to them that it would be +better in every way that they should make their position a little +clearer both to the general public and to Lord St. Simon in +particular. I invited them to meet him here, and, as you see, I +made him keep the appointment." + +"But with no very good result," I remarked. "His conduct was +certainly not very gracious." + +"Ah, Watson," said Holmes, smiling, "perhaps you would not be +very gracious either, if, after all the trouble of wooing and +wedding, you found yourself deprived in an instant of wife and of +fortune. I think that we may judge Lord St. Simon very mercifully +and thank our stars that we are never likely to find ourselves in +the same position. Draw your chair up and hand me my violin, for +the only problem we have still to solve is how to while away +these bleak autumnal evenings." + + + +XI. THE ADVENTURE OF THE BERYL CORONET + +"Holmes," said I as I stood one morning in our bow-window looking +down the street, "here is a madman coming along. It seems rather +sad that his relatives should allow him to come out alone." + +My friend rose lazily from his armchair and stood with his hands +in the pockets of his dressing-gown, looking over my shoulder. It +was a bright, crisp February morning, and the snow of the day +before still lay deep upon the ground, shimmering brightly in the +wintry sun. Down the centre of Baker Street it had been ploughed +into a brown crumbly band by the traffic, but at either side and +on the heaped-up edges of the foot-paths it still lay as white as +when it fell. The grey pavement had been cleaned and scraped, but +was still dangerously slippery, so that there were fewer +passengers than usual. Indeed, from the direction of the +Metropolitan Station no one was coming save the single gentleman +whose eccentric conduct had drawn my attention. + +He was a man of about fifty, tall, portly, and imposing, with a +massive, strongly marked face and a commanding figure. He was +dressed in a sombre yet rich style, in black frock-coat, shining +hat, neat brown gaiters, and well-cut pearl-grey trousers. Yet +his actions were in absurd contrast to the dignity of his dress +and features, for he was running hard, with occasional little +springs, such as a weary man gives who is little accustomed to +set any tax upon his legs. As he ran he jerked his hands up and +down, waggled his head, and writhed his face into the most +extraordinary contortions. + +"What on earth can be the matter with him?" I asked. "He is +looking up at the numbers of the houses." + +"I believe that he is coming here," said Holmes, rubbing his +hands. + +"Here?" + +"Yes; I rather think he is coming to consult me professionally. I +think that I recognise the symptoms. Ha! did I not tell you?" As +he spoke, the man, puffing and blowing, rushed at our door and +pulled at our bell until the whole house resounded with the +clanging. + +A few moments later he was in our room, still puffing, still +gesticulating, but with so fixed a look of grief and despair in +his eyes that our smiles were turned in an instant to horror and +pity. For a while he could not get his words out, but swayed his +body and plucked at his hair like one who has been driven to the +extreme limits of his reason. Then, suddenly springing to his +feet, he beat his head against the wall with such force that we +both rushed upon him and tore him away to the centre of the room. +Sherlock Holmes pushed him down into the easy-chair and, sitting +beside him, patted his hand and chatted with him in the easy, +soothing tones which he knew so well how to employ. + +"You have come to me to tell your story, have you not?" said he. +"You are fatigued with your haste. Pray wait until you have +recovered yourself, and then I shall be most happy to look into +any little problem which you may submit to me." + +The man sat for a minute or more with a heaving chest, fighting +against his emotion. Then he passed his handkerchief over his +brow, set his lips tight, and turned his face towards us. + +"No doubt you think me mad?" said he. + +"I see that you have had some great trouble," responded Holmes. + +"God knows I have!--a trouble which is enough to unseat my +reason, so sudden and so terrible is it. Public disgrace I might +have faced, although I am a man whose character has never yet +borne a stain. Private affliction also is the lot of every man; +but the two coming together, and in so frightful a form, have +been enough to shake my very soul. Besides, it is not I alone. +The very noblest in the land may suffer unless some way be found +out of this horrible affair." + +"Pray compose yourself, sir," said Holmes, "and let me have a +clear account of who you are and what it is that has befallen +you." + +"My name," answered our visitor, "is probably familiar to your +ears. I am Alexander Holder, of the banking firm of Holder & +Stevenson, of Threadneedle Street." + +The name was indeed well known to us as belonging to the senior +partner in the second largest private banking concern in the City +of London. What could have happened, then, to bring one of the +foremost citizens of London to this most pitiable pass? We +waited, all curiosity, until with another effort he braced +himself to tell his story. + +"I feel that time is of value," said he; "that is why I hastened +here when the police inspector suggested that I should secure +your co-operation. I came to Baker Street by the Underground and +hurried from there on foot, for the cabs go slowly through this +snow. That is why I was so out of breath, for I am a man who +takes very little exercise. I feel better now, and I will put the +facts before you as shortly and yet as clearly as I can. + +"It is, of course, well known to you that in a successful banking +business as much depends upon our being able to find remunerative +investments for our funds as upon our increasing our connection +and the number of our depositors. One of our most lucrative means +of laying out money is in the shape of loans, where the security +is unimpeachable. We have done a good deal in this direction +during the last few years, and there are many noble families to +whom we have advanced large sums upon the security of their +pictures, libraries, or plate. + +"Yesterday morning I was seated in my office at the bank when a +card was brought in to me by one of the clerks. I started when I +saw the name, for it was that of none other than--well, perhaps +even to you I had better say no more than that it was a name +which is a household word all over the earth--one of the highest, +noblest, most exalted names in England. I was overwhelmed by the +honour and attempted, when he entered, to say so, but he plunged +at once into business with the air of a man who wishes to hurry +quickly through a disagreeable task. + +"'Mr. Holder,' said he, 'I have been informed that you are in the +habit of advancing money.' + +"'The firm does so when the security is good.' I answered. + +"'It is absolutely essential to me,' said he, 'that I should have +50,000 pounds at once. I could, of course, borrow so trifling a +sum ten times over from my friends, but I much prefer to make it +a matter of business and to carry out that business myself. In my +position you can readily understand that it is unwise to place +one's self under obligations.' + +"'For how long, may I ask, do you want this sum?' I asked. + +"'Next Monday I have a large sum due to me, and I shall then most +certainly repay what you advance, with whatever interest you +think it right to charge. But it is very essential to me that the +money should be paid at once.' + +"'I should be happy to advance it without further parley from my +own private purse,' said I, 'were it not that the strain would be +rather more than it could bear. If, on the other hand, I am to do +it in the name of the firm, then in justice to my partner I must +insist that, even in your case, every businesslike precaution +should be taken.' + +"'I should much prefer to have it so,' said he, raising up a +square, black morocco case which he had laid beside his chair. +'You have doubtless heard of the Beryl Coronet?' + +"'One of the most precious public possessions of the empire,' +said I. + +"'Precisely.' He opened the case, and there, imbedded in soft, +flesh-coloured velvet, lay the magnificent piece of jewellery +which he had named. 'There are thirty-nine enormous beryls,' said +he, 'and the price of the gold chasing is incalculable. The +lowest estimate would put the worth of the coronet at double the +sum which I have asked. I am prepared to leave it with you as my +security.' + +"I took the precious case into my hands and looked in some +perplexity from it to my illustrious client. + +"'You doubt its value?' he asked. + +"'Not at all. I only doubt--' + +"'The propriety of my leaving it. You may set your mind at rest +about that. I should not dream of doing so were it not absolutely +certain that I should be able in four days to reclaim it. It is a +pure matter of form. Is the security sufficient?' + +"'Ample.' + +"'You understand, Mr. Holder, that I am giving you a strong proof +of the confidence which I have in you, founded upon all that I +have heard of you. I rely upon you not only to be discreet and to +refrain from all gossip upon the matter but, above all, to +preserve this coronet with every possible precaution because I +need not say that a great public scandal would be caused if any +harm were to befall it. Any injury to it would be almost as +serious as its complete loss, for there are no beryls in the +world to match these, and it would be impossible to replace them. +I leave it with you, however, with every confidence, and I shall +call for it in person on Monday morning.' + +"Seeing that my client was anxious to leave, I said no more but, +calling for my cashier, I ordered him to pay over fifty 1000 +pound notes. When I was alone once more, however, with the +precious case lying upon the table in front of me, I could not +but think with some misgivings of the immense responsibility +which it entailed upon me. There could be no doubt that, as it +was a national possession, a horrible scandal would ensue if any +misfortune should occur to it. I already regretted having ever +consented to take charge of it. However, it was too late to alter +the matter now, so I locked it up in my private safe and turned +once more to my work. + +"When evening came I felt that it would be an imprudence to leave +so precious a thing in the office behind me. Bankers' safes had +been forced before now, and why should not mine be? If so, how +terrible would be the position in which I should find myself! I +determined, therefore, that for the next few days I would always +carry the case backward and forward with me, so that it might +never be really out of my reach. With this intention, I called a +cab and drove out to my house at Streatham, carrying the jewel +with me. I did not breathe freely until I had taken it upstairs +and locked it in the bureau of my dressing-room. + +"And now a word as to my household, Mr. Holmes, for I wish you to +thoroughly understand the situation. My groom and my page sleep +out of the house, and may be set aside altogether. I have three +maid-servants who have been with me a number of years and whose +absolute reliability is quite above suspicion. Another, Lucy +Parr, the second waiting-maid, has only been in my service a few +months. She came with an excellent character, however, and has +always given me satisfaction. She is a very pretty girl and has +attracted admirers who have occasionally hung about the place. +That is the only drawback which we have found to her, but we +believe her to be a thoroughly good girl in every way. + +"So much for the servants. My family itself is so small that it +will not take me long to describe it. I am a widower and have an +only son, Arthur. He has been a disappointment to me, Mr. +Holmes--a grievous disappointment. I have no doubt that I am +myself to blame. People tell me that I have spoiled him. Very +likely I have. When my dear wife died I felt that he was all I +had to love. I could not bear to see the smile fade even for a +moment from his face. I have never denied him a wish. Perhaps it +would have been better for both of us had I been sterner, but I +meant it for the best. + +"It was naturally my intention that he should succeed me in my +business, but he was not of a business turn. He was wild, +wayward, and, to speak the truth, I could not trust him in the +handling of large sums of money. When he was young he became a +member of an aristocratic club, and there, having charming +manners, he was soon the intimate of a number of men with long +purses and expensive habits. He learned to play heavily at cards +and to squander money on the turf, until he had again and again +to come to me and implore me to give him an advance upon his +allowance, that he might settle his debts of honour. He tried +more than once to break away from the dangerous company which he +was keeping, but each time the influence of his friend, Sir +George Burnwell, was enough to draw him back again. + +"And, indeed, I could not wonder that such a man as Sir George +Burnwell should gain an influence over him, for he has frequently +brought him to my house, and I have found myself that I could +hardly resist the fascination of his manner. He is older than +Arthur, a man of the world to his finger-tips, one who had been +everywhere, seen everything, a brilliant talker, and a man of +great personal beauty. Yet when I think of him in cold blood, far +away from the glamour of his presence, I am convinced from his +cynical speech and the look which I have caught in his eyes that +he is one who should be deeply distrusted. So I think, and so, +too, thinks my little Mary, who has a woman's quick insight into +character. + +"And now there is only she to be described. She is my niece; but +when my brother died five years ago and left her alone in the +world I adopted her, and have looked upon her ever since as my +daughter. She is a sunbeam in my house--sweet, loving, beautiful, +a wonderful manager and housekeeper, yet as tender and quiet and +gentle as a woman could be. She is my right hand. I do not know +what I could do without her. In only one matter has she ever gone +against my wishes. Twice my boy has asked her to marry him, for +he loves her devotedly, but each time she has refused him. I +think that if anyone could have drawn him into the right path it +would have been she, and that his marriage might have changed his +whole life; but now, alas! it is too late--forever too late! + +"Now, Mr. Holmes, you know the people who live under my roof, and +I shall continue with my miserable story. + +"When we were taking coffee in the drawing-room that night after +dinner, I told Arthur and Mary my experience, and of the precious +treasure which we had under our roof, suppressing only the name +of my client. Lucy Parr, who had brought in the coffee, had, I am +sure, left the room; but I cannot swear that the door was closed. +Mary and Arthur were much interested and wished to see the famous +coronet, but I thought it better not to disturb it. + +"'Where have you put it?' asked Arthur. + +"'In my own bureau.' + +"'Well, I hope to goodness the house won't be burgled during the +night.' said he. + +"'It is locked up,' I answered. + +"'Oh, any old key will fit that bureau. When I was a youngster I +have opened it myself with the key of the box-room cupboard.' + +"He often had a wild way of talking, so that I thought little of +what he said. He followed me to my room, however, that night with +a very grave face. + +"'Look here, dad,' said he with his eyes cast down, 'can you let +me have 200 pounds?' + +"'No, I cannot!' I answered sharply. 'I have been far too +generous with you in money matters.' + +"'You have been very kind,' said he, 'but I must have this money, +or else I can never show my face inside the club again.' + +"'And a very good thing, too!' I cried. + +"'Yes, but you would not have me leave it a dishonoured man,' +said he. 'I could not bear the disgrace. I must raise the money +in some way, and if you will not let me have it, then I must try +other means.' + +"I was very angry, for this was the third demand during the +month. 'You shall not have a farthing from me,' I cried, on which +he bowed and left the room without another word. + +"When he was gone I unlocked my bureau, made sure that my +treasure was safe, and locked it again. Then I started to go +round the house to see that all was secure--a duty which I +usually leave to Mary but which I thought it well to perform +myself that night. As I came down the stairs I saw Mary herself +at the side window of the hall, which she closed and fastened as +I approached. + +"'Tell me, dad,' said she, looking, I thought, a little +disturbed, 'did you give Lucy, the maid, leave to go out +to-night?' + +"'Certainly not.' + +"'She came in just now by the back door. I have no doubt that she +has only been to the side gate to see someone, but I think that +it is hardly safe and should be stopped.' + +"'You must speak to her in the morning, or I will if you prefer +it. Are you sure that everything is fastened?' + +"'Quite sure, dad.' + +"'Then, good-night.' I kissed her and went up to my bedroom +again, where I was soon asleep. + +"I am endeavouring to tell you everything, Mr. Holmes, which may +have any bearing upon the case, but I beg that you will question +me upon any point which I do not make clear." + +"On the contrary, your statement is singularly lucid." + +"I come to a part of my story now in which I should wish to be +particularly so. I am not a very heavy sleeper, and the anxiety +in my mind tended, no doubt, to make me even less so than usual. +About two in the morning, then, I was awakened by some sound in +the house. It had ceased ere I was wide awake, but it had left an +impression behind it as though a window had gently closed +somewhere. I lay listening with all my ears. Suddenly, to my +horror, there was a distinct sound of footsteps moving softly in +the next room. I slipped out of bed, all palpitating with fear, +and peeped round the corner of my dressing-room door. + +"'Arthur!' I screamed, 'you villain! you thief! How dare you +touch that coronet?' + +"The gas was half up, as I had left it, and my unhappy boy, +dressed only in his shirt and trousers, was standing beside the +light, holding the coronet in his hands. He appeared to be +wrenching at it, or bending it with all his strength. At my cry +he dropped it from his grasp and turned as pale as death. I +snatched it up and examined it. One of the gold corners, with +three of the beryls in it, was missing. + +"'You blackguard!' I shouted, beside myself with rage. 'You have +destroyed it! You have dishonoured me forever! Where are the +jewels which you have stolen?' + +"'Stolen!' he cried. + +"'Yes, thief!' I roared, shaking him by the shoulder. + +"'There are none missing. There cannot be any missing,' said he. + +"'There are three missing. And you know where they are. Must I +call you a liar as well as a thief? Did I not see you trying to +tear off another piece?' + +"'You have called me names enough,' said he, 'I will not stand it +any longer. I shall not say another word about this business, +since you have chosen to insult me. I will leave your house in +the morning and make my own way in the world.' + +"'You shall leave it in the hands of the police!' I cried +half-mad with grief and rage. 'I shall have this matter probed to +the bottom.' + +"'You shall learn nothing from me,' said he with a passion such +as I should not have thought was in his nature. 'If you choose to +call the police, let the police find what they can.' + +"By this time the whole house was astir, for I had raised my +voice in my anger. Mary was the first to rush into my room, and, +at the sight of the coronet and of Arthur's face, she read the +whole story and, with a scream, fell down senseless on the +ground. I sent the house-maid for the police and put the +investigation into their hands at once. When the inspector and a +constable entered the house, Arthur, who had stood sullenly with +his arms folded, asked me whether it was my intention to charge +him with theft. I answered that it had ceased to be a private +matter, but had become a public one, since the ruined coronet was +national property. I was determined that the law should have its +way in everything. + +"'At least,' said he, 'you will not have me arrested at once. It +would be to your advantage as well as mine if I might leave the +house for five minutes.' + +"'That you may get away, or perhaps that you may conceal what you +have stolen,' said I. And then, realising the dreadful position +in which I was placed, I implored him to remember that not only +my honour but that of one who was far greater than I was at +stake; and that he threatened to raise a scandal which would +convulse the nation. He might avert it all if he would but tell +me what he had done with the three missing stones. + +"'You may as well face the matter,' said I; 'you have been caught +in the act, and no confession could make your guilt more heinous. +If you but make such reparation as is in your power, by telling +us where the beryls are, all shall be forgiven and forgotten.' + +"'Keep your forgiveness for those who ask for it,' he answered, +turning away from me with a sneer. I saw that he was too hardened +for any words of mine to influence him. There was but one way for +it. I called in the inspector and gave him into custody. A search +was made at once not only of his person but of his room and of +every portion of the house where he could possibly have concealed +the gems; but no trace of them could be found, nor would the +wretched boy open his mouth for all our persuasions and our +threats. This morning he was removed to a cell, and I, after +going through all the police formalities, have hurried round to +you to implore you to use your skill in unravelling the matter. +The police have openly confessed that they can at present make +nothing of it. You may go to any expense which you think +necessary. I have already offered a reward of 1000 pounds. My +God, what shall I do! I have lost my honour, my gems, and my son +in one night. Oh, what shall I do!" + +He put a hand on either side of his head and rocked himself to +and fro, droning to himself like a child whose grief has got +beyond words. + +Sherlock Holmes sat silent for some few minutes, with his brows +knitted and his eyes fixed upon the fire. + +"Do you receive much company?" he asked. + +"None save my partner with his family and an occasional friend of +Arthur's. Sir George Burnwell has been several times lately. No +one else, I think." + +"Do you go out much in society?" + +"Arthur does. Mary and I stay at home. We neither of us care for +it." + +"That is unusual in a young girl." + +"She is of a quiet nature. Besides, she is not so very young. She +is four-and-twenty." + +"This matter, from what you say, seems to have been a shock to +her also." + +"Terrible! She is even more affected than I." + +"You have neither of you any doubt as to your son's guilt?" + +"How can we have when I saw him with my own eyes with the coronet +in his hands." + +"I hardly consider that a conclusive proof. Was the remainder of +the coronet at all injured?" + +"Yes, it was twisted." + +"Do you not think, then, that he might have been trying to +straighten it?" + +"God bless you! You are doing what you can for him and for me. +But it is too heavy a task. What was he doing there at all? If +his purpose were innocent, why did he not say so?" + +"Precisely. And if it were guilty, why did he not invent a lie? +His silence appears to me to cut both ways. There are several +singular points about the case. What did the police think of the +noise which awoke you from your sleep?" + +"They considered that it might be caused by Arthur's closing his +bedroom door." + +"A likely story! As if a man bent on felony would slam his door +so as to wake a household. What did they say, then, of the +disappearance of these gems?" + +"They are still sounding the planking and probing the furniture +in the hope of finding them." + +"Have they thought of looking outside the house?" + +"Yes, they have shown extraordinary energy. The whole garden has +already been minutely examined." + +"Now, my dear sir," said Holmes, "is it not obvious to you now +that this matter really strikes very much deeper than either you +or the police were at first inclined to think? It appeared to you +to be a simple case; to me it seems exceedingly complex. Consider +what is involved by your theory. You suppose that your son came +down from his bed, went, at great risk, to your dressing-room, +opened your bureau, took out your coronet, broke off by main +force a small portion of it, went off to some other place, +concealed three gems out of the thirty-nine, with such skill that +nobody can find them, and then returned with the other thirty-six +into the room in which he exposed himself to the greatest danger +of being discovered. I ask you now, is such a theory tenable?" + +"But what other is there?" cried the banker with a gesture of +despair. "If his motives were innocent, why does he not explain +them?" + +"It is our task to find that out," replied Holmes; "so now, if +you please, Mr. Holder, we will set off for Streatham together, +and devote an hour to glancing a little more closely into +details." + +My friend insisted upon my accompanying them in their expedition, +which I was eager enough to do, for my curiosity and sympathy +were deeply stirred by the story to which we had listened. I +confess that the guilt of the banker's son appeared to me to be +as obvious as it did to his unhappy father, but still I had such +faith in Holmes' judgment that I felt that there must be some +grounds for hope as long as he was dissatisfied with the accepted +explanation. He hardly spoke a word the whole way out to the +southern suburb, but sat with his chin upon his breast and his +hat drawn over his eyes, sunk in the deepest thought. Our client +appeared to have taken fresh heart at the little glimpse of hope +which had been presented to him, and he even broke into a +desultory chat with me over his business affairs. A short railway +journey and a shorter walk brought us to Fairbank, the modest +residence of the great financier. + +Fairbank was a good-sized square house of white stone, standing +back a little from the road. A double carriage-sweep, with a +snow-clad lawn, stretched down in front to two large iron gates +which closed the entrance. On the right side was a small wooden +thicket, which led into a narrow path between two neat hedges +stretching from the road to the kitchen door, and forming the +tradesmen's entrance. On the left ran a lane which led to the +stables, and was not itself within the grounds at all, being a +public, though little used, thoroughfare. Holmes left us standing +at the door and walked slowly all round the house, across the +front, down the tradesmen's path, and so round by the garden +behind into the stable lane. So long was he that Mr. Holder and I +went into the dining-room and waited by the fire until he should +return. We were sitting there in silence when the door opened and +a young lady came in. She was rather above the middle height, +slim, with dark hair and eyes, which seemed the darker against +the absolute pallor of her skin. I do not think that I have ever +seen such deadly paleness in a woman's face. Her lips, too, were +bloodless, but her eyes were flushed with crying. As she swept +silently into the room she impressed me with a greater sense of +grief than the banker had done in the morning, and it was the +more striking in her as she was evidently a woman of strong +character, with immense capacity for self-restraint. Disregarding +my presence, she went straight to her uncle and passed her hand +over his head with a sweet womanly caress. + +"You have given orders that Arthur should be liberated, have you +not, dad?" she asked. + +"No, no, my girl, the matter must be probed to the bottom." + +"But I am so sure that he is innocent. You know what woman's +instincts are. I know that he has done no harm and that you will +be sorry for having acted so harshly." + +"Why is he silent, then, if he is innocent?" + +"Who knows? Perhaps because he was so angry that you should +suspect him." + +"How could I help suspecting him, when I actually saw him with +the coronet in his hand?" + +"Oh, but he had only picked it up to look at it. Oh, do, do take +my word for it that he is innocent. Let the matter drop and say +no more. It is so dreadful to think of our dear Arthur in +prison!" + +"I shall never let it drop until the gems are found--never, Mary! +Your affection for Arthur blinds you as to the awful consequences +to me. Far from hushing the thing up, I have brought a gentleman +down from London to inquire more deeply into it." + +"This gentleman?" she asked, facing round to me. + +"No, his friend. He wished us to leave him alone. He is round in +the stable lane now." + +"The stable lane?" She raised her dark eyebrows. "What can he +hope to find there? Ah! this, I suppose, is he. I trust, sir, +that you will succeed in proving, what I feel sure is the truth, +that my cousin Arthur is innocent of this crime." + +"I fully share your opinion, and I trust, with you, that we may +prove it," returned Holmes, going back to the mat to knock the +snow from his shoes. "I believe I have the honour of addressing +Miss Mary Holder. Might I ask you a question or two?" + +"Pray do, sir, if it may help to clear this horrible affair up." + +"You heard nothing yourself last night?" + +"Nothing, until my uncle here began to speak loudly. I heard +that, and I came down." + +"You shut up the windows and doors the night before. Did you +fasten all the windows?" + +"Yes." + +"Were they all fastened this morning?" + +"Yes." + +"You have a maid who has a sweetheart? I think that you remarked +to your uncle last night that she had been out to see him?" + +"Yes, and she was the girl who waited in the drawing-room, and +who may have heard uncle's remarks about the coronet." + +"I see. You infer that she may have gone out to tell her +sweetheart, and that the two may have planned the robbery." + +"But what is the good of all these vague theories," cried the +banker impatiently, "when I have told you that I saw Arthur with +the coronet in his hands?" + +"Wait a little, Mr. Holder. We must come back to that. About this +girl, Miss Holder. You saw her return by the kitchen door, I +presume?" + +"Yes; when I went to see if the door was fastened for the night I +met her slipping in. I saw the man, too, in the gloom." + +"Do you know him?" + +"Oh, yes! he is the green-grocer who brings our vegetables round. +His name is Francis Prosper." + +"He stood," said Holmes, "to the left of the door--that is to +say, farther up the path than is necessary to reach the door?" + +"Yes, he did." + +"And he is a man with a wooden leg?" + +Something like fear sprang up in the young lady's expressive +black eyes. "Why, you are like a magician," said she. "How do you +know that?" She smiled, but there was no answering smile in +Holmes' thin, eager face. + +"I should be very glad now to go upstairs," said he. "I shall +probably wish to go over the outside of the house again. Perhaps +I had better take a look at the lower windows before I go up." + +He walked swiftly round from one to the other, pausing only at +the large one which looked from the hall onto the stable lane. +This he opened and made a very careful examination of the sill +with his powerful magnifying lens. "Now we shall go upstairs," +said he at last. + +The banker's dressing-room was a plainly furnished little +chamber, with a grey carpet, a large bureau, and a long mirror. +Holmes went to the bureau first and looked hard at the lock. + +"Which key was used to open it?" he asked. + +"That which my son himself indicated--that of the cupboard of the +lumber-room." + +"Have you it here?" + +"That is it on the dressing-table." + +Sherlock Holmes took it up and opened the bureau. + +"It is a noiseless lock," said he. "It is no wonder that it did +not wake you. This case, I presume, contains the coronet. We must +have a look at it." He opened the case, and taking out the diadem +he laid it upon the table. It was a magnificent specimen of the +jeweller's art, and the thirty-six stones were the finest that I +have ever seen. At one side of the coronet was a cracked edge, +where a corner holding three gems had been torn away. + +"Now, Mr. Holder," said Holmes, "here is the corner which +corresponds to that which has been so unfortunately lost. Might I +beg that you will break it off." + +The banker recoiled in horror. "I should not dream of trying," +said he. + +"Then I will." Holmes suddenly bent his strength upon it, but +without result. "I feel it give a little," said he; "but, though +I am exceptionally strong in the fingers, it would take me all my +time to break it. An ordinary man could not do it. Now, what do +you think would happen if I did break it, Mr. Holder? There would +be a noise like a pistol shot. Do you tell me that all this +happened within a few yards of your bed and that you heard +nothing of it?" + +"I do not know what to think. It is all dark to me." + +"But perhaps it may grow lighter as we go. What do you think, +Miss Holder?" + +"I confess that I still share my uncle's perplexity." + +"Your son had no shoes or slippers on when you saw him?" + +"He had nothing on save only his trousers and shirt." + +"Thank you. We have certainly been favoured with extraordinary +luck during this inquiry, and it will be entirely our own fault +if we do not succeed in clearing the matter up. With your +permission, Mr. Holder, I shall now continue my investigations +outside." + +He went alone, at his own request, for he explained that any +unnecessary footmarks might make his task more difficult. For an +hour or more he was at work, returning at last with his feet +heavy with snow and his features as inscrutable as ever. + +"I think that I have seen now all that there is to see, Mr. +Holder," said he; "I can serve you best by returning to my +rooms." + +"But the gems, Mr. Holmes. Where are they?" + +"I cannot tell." + +The banker wrung his hands. "I shall never see them again!" he +cried. "And my son? You give me hopes?" + +"My opinion is in no way altered." + +"Then, for God's sake, what was this dark business which was +acted in my house last night?" + +"If you can call upon me at my Baker Street rooms to-morrow +morning between nine and ten I shall be happy to do what I can to +make it clearer. I understand that you give me carte blanche to +act for you, provided only that I get back the gems, and that you +place no limit on the sum I may draw." + +"I would give my fortune to have them back." + +"Very good. I shall look into the matter between this and then. +Good-bye; it is just possible that I may have to come over here +again before evening." + +It was obvious to me that my companion's mind was now made up +about the case, although what his conclusions were was more than +I could even dimly imagine. Several times during our homeward +journey I endeavoured to sound him upon the point, but he always +glided away to some other topic, until at last I gave it over in +despair. It was not yet three when we found ourselves in our +rooms once more. He hurried to his chamber and was down again in +a few minutes dressed as a common loafer. With his collar turned +up, his shiny, seedy coat, his red cravat, and his worn boots, he +was a perfect sample of the class. + +"I think that this should do," said he, glancing into the glass +above the fireplace. "I only wish that you could come with me, +Watson, but I fear that it won't do. I may be on the trail in +this matter, or I may be following a will-o'-the-wisp, but I +shall soon know which it is. I hope that I may be back in a few +hours." He cut a slice of beef from the joint upon the sideboard, +sandwiched it between two rounds of bread, and thrusting this +rude meal into his pocket he started off upon his expedition. + +I had just finished my tea when he returned, evidently in +excellent spirits, swinging an old elastic-sided boot in his +hand. He chucked it down into a corner and helped himself to a +cup of tea. + +"I only looked in as I passed," said he. "I am going right on." + +"Where to?" + +"Oh, to the other side of the West End. It may be some time +before I get back. Don't wait up for me in case I should be +late." + +"How are you getting on?" + +"Oh, so so. Nothing to complain of. I have been out to Streatham +since I saw you last, but I did not call at the house. It is a +very sweet little problem, and I would not have missed it for a +good deal. However, I must not sit gossiping here, but must get +these disreputable clothes off and return to my highly +respectable self." + +I could see by his manner that he had stronger reasons for +satisfaction than his words alone would imply. His eyes twinkled, +and there was even a touch of colour upon his sallow cheeks. He +hastened upstairs, and a few minutes later I heard the slam of +the hall door, which told me that he was off once more upon his +congenial hunt. + +I waited until midnight, but there was no sign of his return, so +I retired to my room. It was no uncommon thing for him to be away +for days and nights on end when he was hot upon a scent, so that +his lateness caused me no surprise. I do not know at what hour he +came in, but when I came down to breakfast in the morning there +he was with a cup of coffee in one hand and the paper in the +other, as fresh and trim as possible. + +"You will excuse my beginning without you, Watson," said he, "but +you remember that our client has rather an early appointment this +morning." + +"Why, it is after nine now," I answered. "I should not be +surprised if that were he. I thought I heard a ring." + +It was, indeed, our friend the financier. I was shocked by the +change which had come over him, for his face which was naturally +of a broad and massive mould, was now pinched and fallen in, +while his hair seemed to me at least a shade whiter. He entered +with a weariness and lethargy which was even more painful than +his violence of the morning before, and he dropped heavily into +the armchair which I pushed forward for him. + +"I do not know what I have done to be so severely tried," said +he. "Only two days ago I was a happy and prosperous man, without +a care in the world. Now I am left to a lonely and dishonoured +age. One sorrow comes close upon the heels of another. My niece, +Mary, has deserted me." + +"Deserted you?" + +"Yes. Her bed this morning had not been slept in, her room was +empty, and a note for me lay upon the hall table. I had said to +her last night, in sorrow and not in anger, that if she had +married my boy all might have been well with him. Perhaps it was +thoughtless of me to say so. It is to that remark that she refers +in this note: + +"'MY DEAREST UNCLE:--I feel that I have brought trouble upon you, +and that if I had acted differently this terrible misfortune +might never have occurred. I cannot, with this thought in my +mind, ever again be happy under your roof, and I feel that I must +leave you forever. Do not worry about my future, for that is +provided for; and, above all, do not search for me, for it will +be fruitless labour and an ill-service to me. In life or in +death, I am ever your loving,--MARY.' + +"What could she mean by that note, Mr. Holmes? Do you think it +points to suicide?" + +"No, no, nothing of the kind. It is perhaps the best possible +solution. I trust, Mr. Holder, that you are nearing the end of +your troubles." + +"Ha! You say so! You have heard something, Mr. Holmes; you have +learned something! Where are the gems?" + +"You would not think 1000 pounds apiece an excessive sum for +them?" + +"I would pay ten." + +"That would be unnecessary. Three thousand will cover the matter. +And there is a little reward, I fancy. Have you your check-book? +Here is a pen. Better make it out for 4000 pounds." + +With a dazed face the banker made out the required check. Holmes +walked over to his desk, took out a little triangular piece of +gold with three gems in it, and threw it down upon the table. + +With a shriek of joy our client clutched it up. + +"You have it!" he gasped. "I am saved! I am saved!" + +The reaction of joy was as passionate as his grief had been, and +he hugged his recovered gems to his bosom. + +"There is one other thing you owe, Mr. Holder," said Sherlock +Holmes rather sternly. + +"Owe!" He caught up a pen. "Name the sum, and I will pay it." + +"No, the debt is not to me. You owe a very humble apology to that +noble lad, your son, who has carried himself in this matter as I +should be proud to see my own son do, should I ever chance to +have one." + +"Then it was not Arthur who took them?" + +"I told you yesterday, and I repeat to-day, that it was not." + +"You are sure of it! Then let us hurry to him at once to let him +know that the truth is known." + +"He knows it already. When I had cleared it all up I had an +interview with him, and finding that he would not tell me the +story, I told it to him, on which he had to confess that I was +right and to add the very few details which were not yet quite +clear to me. Your news of this morning, however, may open his +lips." + +"For heaven's sake, tell me, then, what is this extraordinary +mystery!" + +"I will do so, and I will show you the steps by which I reached +it. And let me say to you, first, that which it is hardest for me +to say and for you to hear: there has been an understanding +between Sir George Burnwell and your niece Mary. They have now +fled together." + +"My Mary? Impossible!" + +"It is unfortunately more than possible; it is certain. Neither +you nor your son knew the true character of this man when you +admitted him into your family circle. He is one of the most +dangerous men in England--a ruined gambler, an absolutely +desperate villain, a man without heart or conscience. Your niece +knew nothing of such men. When he breathed his vows to her, as he +had done to a hundred before her, she flattered herself that she +alone had touched his heart. The devil knows best what he said, +but at least she became his tool and was in the habit of seeing +him nearly every evening." + +"I cannot, and I will not, believe it!" cried the banker with an +ashen face. + +"I will tell you, then, what occurred in your house last night. +Your niece, when you had, as she thought, gone to your room, +slipped down and talked to her lover through the window which +leads into the stable lane. His footmarks had pressed right +through the snow, so long had he stood there. She told him of the +coronet. His wicked lust for gold kindled at the news, and he +bent her to his will. I have no doubt that she loved you, but +there are women in whom the love of a lover extinguishes all +other loves, and I think that she must have been one. She had +hardly listened to his instructions when she saw you coming +downstairs, on which she closed the window rapidly and told you +about one of the servants' escapade with her wooden-legged lover, +which was all perfectly true. + +"Your boy, Arthur, went to bed after his interview with you but +he slept badly on account of his uneasiness about his club debts. +In the middle of the night he heard a soft tread pass his door, +so he rose and, looking out, was surprised to see his cousin +walking very stealthily along the passage until she disappeared +into your dressing-room. Petrified with astonishment, the lad +slipped on some clothes and waited there in the dark to see what +would come of this strange affair. Presently she emerged from the +room again, and in the light of the passage-lamp your son saw +that she carried the precious coronet in her hands. She passed +down the stairs, and he, thrilling with horror, ran along and +slipped behind the curtain near your door, whence he could see +what passed in the hall beneath. He saw her stealthily open the +window, hand out the coronet to someone in the gloom, and then +closing it once more hurry back to her room, passing quite close +to where he stood hid behind the curtain. + +"As long as she was on the scene he could not take any action +without a horrible exposure of the woman whom he loved. But the +instant that she was gone he realised how crushing a misfortune +this would be for you, and how all-important it was to set it +right. He rushed down, just as he was, in his bare feet, opened +the window, sprang out into the snow, and ran down the lane, +where he could see a dark figure in the moonlight. Sir George +Burnwell tried to get away, but Arthur caught him, and there was +a struggle between them, your lad tugging at one side of the +coronet, and his opponent at the other. In the scuffle, your son +struck Sir George and cut him over the eye. Then something +suddenly snapped, and your son, finding that he had the coronet +in his hands, rushed back, closed the window, ascended to your +room, and had just observed that the coronet had been twisted in +the struggle and was endeavouring to straighten it when you +appeared upon the scene." + +"Is it possible?" gasped the banker. + +"You then roused his anger by calling him names at a moment when +he felt that he had deserved your warmest thanks. He could not +explain the true state of affairs without betraying one who +certainly deserved little enough consideration at his hands. He +took the more chivalrous view, however, and preserved her +secret." + +"And that was why she shrieked and fainted when she saw the +coronet," cried Mr. Holder. "Oh, my God! what a blind fool I have +been! And his asking to be allowed to go out for five minutes! +The dear fellow wanted to see if the missing piece were at the +scene of the struggle. How cruelly I have misjudged him!" + +"When I arrived at the house," continued Holmes, "I at once went +very carefully round it to observe if there were any traces in +the snow which might help me. I knew that none had fallen since +the evening before, and also that there had been a strong frost +to preserve impressions. I passed along the tradesmen's path, but +found it all trampled down and indistinguishable. Just beyond it, +however, at the far side of the kitchen door, a woman had stood +and talked with a man, whose round impressions on one side showed +that he had a wooden leg. I could even tell that they had been +disturbed, for the woman had run back swiftly to the door, as was +shown by the deep toe and light heel marks, while Wooden-leg had +waited a little, and then had gone away. I thought at the time +that this might be the maid and her sweetheart, of whom you had +already spoken to me, and inquiry showed it was so. I passed +round the garden without seeing anything more than random tracks, +which I took to be the police; but when I got into the stable +lane a very long and complex story was written in the snow in +front of me. + +"There was a double line of tracks of a booted man, and a second +double line which I saw with delight belonged to a man with naked +feet. I was at once convinced from what you had told me that the +latter was your son. The first had walked both ways, but the +other had run swiftly, and as his tread was marked in places over +the depression of the boot, it was obvious that he had passed +after the other. I followed them up and found they led to the +hall window, where Boots had worn all the snow away while +waiting. Then I walked to the other end, which was a hundred +yards or more down the lane. I saw where Boots had faced round, +where the snow was cut up as though there had been a struggle, +and, finally, where a few drops of blood had fallen, to show me +that I was not mistaken. Boots had then run down the lane, and +another little smudge of blood showed that it was he who had been +hurt. When he came to the highroad at the other end, I found that +the pavement had been cleared, so there was an end to that clue. + +"On entering the house, however, I examined, as you remember, the +sill and framework of the hall window with my lens, and I could +at once see that someone had passed out. I could distinguish the +outline of an instep where the wet foot had been placed in coming +in. I was then beginning to be able to form an opinion as to what +had occurred. A man had waited outside the window; someone had +brought the gems; the deed had been overseen by your son; he had +pursued the thief; had struggled with him; they had each tugged +at the coronet, their united strength causing injuries which +neither alone could have effected. He had returned with the +prize, but had left a fragment in the grasp of his opponent. So +far I was clear. The question now was, who was the man and who +was it brought him the coronet? + +"It is an old maxim of mine that when you have excluded the +impossible, whatever remains, however improbable, must be the +truth. Now, I knew that it was not you who had brought it down, +so there only remained your niece and the maids. But if it were +the maids, why should your son allow himself to be accused in +their place? There could be no possible reason. As he loved his +cousin, however, there was an excellent explanation why he should +retain her secret--the more so as the secret was a disgraceful +one. When I remembered that you had seen her at that window, and +how she had fainted on seeing the coronet again, my conjecture +became a certainty. + +"And who could it be who was her confederate? A lover evidently, +for who else could outweigh the love and gratitude which she must +feel to you? I knew that you went out little, and that your +circle of friends was a very limited one. But among them was Sir +George Burnwell. I had heard of him before as being a man of evil +reputation among women. It must have been he who wore those boots +and retained the missing gems. Even though he knew that Arthur +had discovered him, he might still flatter himself that he was +safe, for the lad could not say a word without compromising his +own family. + +"Well, your own good sense will suggest what measures I took +next. I went in the shape of a loafer to Sir George's house, +managed to pick up an acquaintance with his valet, learned that +his master had cut his head the night before, and, finally, at +the expense of six shillings, made all sure by buying a pair of +his cast-off shoes. With these I journeyed down to Streatham and +saw that they exactly fitted the tracks." + +"I saw an ill-dressed vagabond in the lane yesterday evening," +said Mr. Holder. + +"Precisely. It was I. I found that I had my man, so I came home +and changed my clothes. It was a delicate part which I had to +play then, for I saw that a prosecution must be avoided to avert +scandal, and I knew that so astute a villain would see that our +hands were tied in the matter. I went and saw him. At first, of +course, he denied everything. But when I gave him every +particular that had occurred, he tried to bluster and took down a +life-preserver from the wall. I knew my man, however, and I +clapped a pistol to his head before he could strike. Then he +became a little more reasonable. I told him that we would give +him a price for the stones he held--1000 pounds apiece. That +brought out the first signs of grief that he had shown. 'Why, +dash it all!' said he, 'I've let them go at six hundred for the +three!' I soon managed to get the address of the receiver who had +them, on promising him that there would be no prosecution. Off I +set to him, and after much chaffering I got our stones at 1000 +pounds apiece. Then I looked in upon your son, told him that all +was right, and eventually got to my bed about two o'clock, after +what I may call a really hard day's work." + +"A day which has saved England from a great public scandal," said +the banker, rising. "Sir, I cannot find words to thank you, but +you shall not find me ungrateful for what you have done. Your +skill has indeed exceeded all that I have heard of it. And now I +must fly to my dear boy to apologise to him for the wrong which I +have done him. As to what you tell me of poor Mary, it goes to my +very heart. Not even your skill can inform me where she is now." + +"I think that we may safely say," returned Holmes, "that she is +wherever Sir George Burnwell is. It is equally certain, too, that +whatever her sins are, they will soon receive a more than +sufficient punishment." + + + +XII. THE ADVENTURE OF THE COPPER BEECHES + +"To the man who loves art for its own sake," remarked Sherlock +Holmes, tossing aside the advertisement sheet of the Daily +Telegraph, "it is frequently in its least important and lowliest +manifestations that the keenest pleasure is to be derived. It is +pleasant to me to observe, Watson, that you have so far grasped +this truth that in these little records of our cases which you +have been good enough to draw up, and, I am bound to say, +occasionally to embellish, you have given prominence not so much +to the many causes clbres and sensational trials in which I +have figured but rather to those incidents which may have been +trivial in themselves, but which have given room for those +faculties of deduction and of logical synthesis which I have made +my special province." + +"And yet," said I, smiling, "I cannot quite hold myself absolved +from the charge of sensationalism which has been urged against my +records." + +"You have erred, perhaps," he observed, taking up a glowing +cinder with the tongs and lighting with it the long cherry-wood +pipe which was wont to replace his clay when he was in a +disputatious rather than a meditative mood--"you have erred +perhaps in attempting to put colour and life into each of your +statements instead of confining yourself to the task of placing +upon record that severe reasoning from cause to effect which is +really the only notable feature about the thing." + +"It seems to me that I have done you full justice in the matter," +I remarked with some coldness, for I was repelled by the egotism +which I had more than once observed to be a strong factor in my +friend's singular character. + +"No, it is not selfishness or conceit," said he, answering, as +was his wont, my thoughts rather than my words. "If I claim full +justice for my art, it is because it is an impersonal thing--a +thing beyond myself. Crime is common. Logic is rare. Therefore it +is upon the logic rather than upon the crime that you should +dwell. You have degraded what should have been a course of +lectures into a series of tales." + +It was a cold morning of the early spring, and we sat after +breakfast on either side of a cheery fire in the old room at +Baker Street. A thick fog rolled down between the lines of +dun-coloured houses, and the opposing windows loomed like dark, +shapeless blurs through the heavy yellow wreaths. Our gas was lit +and shone on the white cloth and glimmer of china and metal, for +the table had not been cleared yet. Sherlock Holmes had been +silent all the morning, dipping continuously into the +advertisement columns of a succession of papers until at last, +having apparently given up his search, he had emerged in no very +sweet temper to lecture me upon my literary shortcomings. + +"At the same time," he remarked after a pause, during which he +had sat puffing at his long pipe and gazing down into the fire, +"you can hardly be open to a charge of sensationalism, for out of +these cases which you have been so kind as to interest yourself +in, a fair proportion do not treat of crime, in its legal sense, +at all. The small matter in which I endeavoured to help the King +of Bohemia, the singular experience of Miss Mary Sutherland, the +problem connected with the man with the twisted lip, and the +incident of the noble bachelor, were all matters which are +outside the pale of the law. But in avoiding the sensational, I +fear that you may have bordered on the trivial." + +"The end may have been so," I answered, "but the methods I hold +to have been novel and of interest." + +"Pshaw, my dear fellow, what do the public, the great unobservant +public, who could hardly tell a weaver by his tooth or a +compositor by his left thumb, care about the finer shades of +analysis and deduction! But, indeed, if you are trivial, I cannot +blame you, for the days of the great cases are past. Man, or at +least criminal man, has lost all enterprise and originality. As +to my own little practice, it seems to be degenerating into an +agency for recovering lost lead pencils and giving advice to +young ladies from boarding-schools. I think that I have touched +bottom at last, however. This note I had this morning marks my +zero-point, I fancy. Read it!" He tossed a crumpled letter across +to me. + +It was dated from Montague Place upon the preceding evening, and +ran thus: + +"DEAR MR. HOLMES:--I am very anxious to consult you as to whether +I should or should not accept a situation which has been offered +to me as governess. I shall call at half-past ten to-morrow if I +do not inconvenience you. Yours faithfully, + "VIOLET HUNTER." + +"Do you know the young lady?" I asked. + +"Not I." + +"It is half-past ten now." + +"Yes, and I have no doubt that is her ring." + +"It may turn out to be of more interest than you think. You +remember that the affair of the blue carbuncle, which appeared to +be a mere whim at first, developed into a serious investigation. +It may be so in this case, also." + +"Well, let us hope so. But our doubts will very soon be solved, +for here, unless I am much mistaken, is the person in question." + +As he spoke the door opened and a young lady entered the room. +She was plainly but neatly dressed, with a bright, quick face, +freckled like a plover's egg, and with the brisk manner of a +woman who has had her own way to make in the world. + +"You will excuse my troubling you, I am sure," said she, as my +companion rose to greet her, "but I have had a very strange +experience, and as I have no parents or relations of any sort +from whom I could ask advice, I thought that perhaps you would be +kind enough to tell me what I should do." + +"Pray take a seat, Miss Hunter. I shall be happy to do anything +that I can to serve you." + +I could see that Holmes was favourably impressed by the manner +and speech of his new client. He looked her over in his searching +fashion, and then composed himself, with his lids drooping and +his finger-tips together, to listen to her story. + +"I have been a governess for five years," said she, "in the +family of Colonel Spence Munro, but two months ago the colonel +received an appointment at Halifax, in Nova Scotia, and took his +children over to America with him, so that I found myself without +a situation. I advertised, and I answered advertisements, but +without success. At last the little money which I had saved began +to run short, and I was at my wit's end as to what I should do. + +"There is a well-known agency for governesses in the West End +called Westaway's, and there I used to call about once a week in +order to see whether anything had turned up which might suit me. +Westaway was the name of the founder of the business, but it is +really managed by Miss Stoper. She sits in her own little office, +and the ladies who are seeking employment wait in an anteroom, +and are then shown in one by one, when she consults her ledgers +and sees whether she has anything which would suit them. + +"Well, when I called last week I was shown into the little office +as usual, but I found that Miss Stoper was not alone. A +prodigiously stout man with a very smiling face and a great heavy +chin which rolled down in fold upon fold over his throat sat at +her elbow with a pair of glasses on his nose, looking very +earnestly at the ladies who entered. As I came in he gave quite a +jump in his chair and turned quickly to Miss Stoper. + +"'That will do,' said he; 'I could not ask for anything better. +Capital! capital!' He seemed quite enthusiastic and rubbed his +hands together in the most genial fashion. He was such a +comfortable-looking man that it was quite a pleasure to look at +him. + +"'You are looking for a situation, miss?' he asked. + +"'Yes, sir.' + +"'As governess?' + +"'Yes, sir.' + +"'And what salary do you ask?' + +"'I had 4 pounds a month in my last place with Colonel Spence +Munro.' + +"'Oh, tut, tut! sweating--rank sweating!' he cried, throwing his +fat hands out into the air like a man who is in a boiling +passion. 'How could anyone offer so pitiful a sum to a lady with +such attractions and accomplishments?' + +"'My accomplishments, sir, may be less than you imagine,' said I. +'A little French, a little German, music, and drawing--' + +"'Tut, tut!' he cried. 'This is all quite beside the question. +The point is, have you or have you not the bearing and deportment +of a lady? There it is in a nutshell. If you have not, you are +not fitted for the rearing of a child who may some day play a +considerable part in the history of the country. But if you have +why, then, how could any gentleman ask you to condescend to +accept anything under the three figures? Your salary with me, +madam, would commence at 100 pounds a year.' + +"You may imagine, Mr. Holmes, that to me, destitute as I was, +such an offer seemed almost too good to be true. The gentleman, +however, seeing perhaps the look of incredulity upon my face, +opened a pocket-book and took out a note. + +"'It is also my custom,' said he, smiling in the most pleasant +fashion until his eyes were just two little shining slits amid +the white creases of his face, 'to advance to my young ladies +half their salary beforehand, so that they may meet any little +expenses of their journey and their wardrobe.' + +"It seemed to me that I had never met so fascinating and so +thoughtful a man. As I was already in debt to my tradesmen, the +advance was a great convenience, and yet there was something +unnatural about the whole transaction which made me wish to know +a little more before I quite committed myself. + +"'May I ask where you live, sir?' said I. + +"'Hampshire. Charming rural place. The Copper Beeches, five miles +on the far side of Winchester. It is the most lovely country, my +dear young lady, and the dearest old country-house.' + +"'And my duties, sir? I should be glad to know what they would +be.' + +"'One child--one dear little romper just six years old. Oh, if +you could see him killing cockroaches with a slipper! Smack! +smack! smack! Three gone before you could wink!' He leaned back +in his chair and laughed his eyes into his head again. + +"I was a little startled at the nature of the child's amusement, +but the father's laughter made me think that perhaps he was +joking. + +"'My sole duties, then,' I asked, 'are to take charge of a single +child?' + +"'No, no, not the sole, not the sole, my dear young lady,' he +cried. 'Your duty would be, as I am sure your good sense would +suggest, to obey any little commands my wife might give, provided +always that they were such commands as a lady might with +propriety obey. You see no difficulty, heh?' + +"'I should be happy to make myself useful.' + +"'Quite so. In dress now, for example. We are faddy people, you +know--faddy but kind-hearted. If you were asked to wear any dress +which we might give you, you would not object to our little whim. +Heh?' + +"'No,' said I, considerably astonished at his words. + +"'Or to sit here, or sit there, that would not be offensive to +you?' + +"'Oh, no.' + +"'Or to cut your hair quite short before you come to us?' + +"I could hardly believe my ears. As you may observe, Mr. Holmes, +my hair is somewhat luxuriant, and of a rather peculiar tint of +chestnut. It has been considered artistic. I could not dream of +sacrificing it in this offhand fashion. + +"'I am afraid that that is quite impossible,' said I. He had been +watching me eagerly out of his small eyes, and I could see a +shadow pass over his face as I spoke. + +"'I am afraid that it is quite essential,' said he. 'It is a +little fancy of my wife's, and ladies' fancies, you know, madam, +ladies' fancies must be consulted. And so you won't cut your +hair?' + +"'No, sir, I really could not,' I answered firmly. + +"'Ah, very well; then that quite settles the matter. It is a +pity, because in other respects you would really have done very +nicely. In that case, Miss Stoper, I had best inspect a few more +of your young ladies.' + +"The manageress had sat all this while busy with her papers +without a word to either of us, but she glanced at me now with so +much annoyance upon her face that I could not help suspecting +that she had lost a handsome commission through my refusal. + +"'Do you desire your name to be kept upon the books?' she asked. + +"'If you please, Miss Stoper.' + +"'Well, really, it seems rather useless, since you refuse the +most excellent offers in this fashion,' said she sharply. 'You +can hardly expect us to exert ourselves to find another such +opening for you. Good-day to you, Miss Hunter.' She struck a gong +upon the table, and I was shown out by the page. + +"Well, Mr. Holmes, when I got back to my lodgings and found +little enough in the cupboard, and two or three bills upon the +table, I began to ask myself whether I had not done a very +foolish thing. After all, if these people had strange fads and +expected obedience on the most extraordinary matters, they were +at least ready to pay for their eccentricity. Very few +governesses in England are getting 100 pounds a year. Besides, +what use was my hair to me? Many people are improved by wearing +it short and perhaps I should be among the number. Next day I was +inclined to think that I had made a mistake, and by the day after +I was sure of it. I had almost overcome my pride so far as to go +back to the agency and inquire whether the place was still open +when I received this letter from the gentleman himself. I have it +here and I will read it to you: + + "'The Copper Beeches, near Winchester. +"'DEAR MISS HUNTER:--Miss Stoper has very kindly given me your +address, and I write from here to ask you whether you have +reconsidered your decision. My wife is very anxious that you +should come, for she has been much attracted by my description of +you. We are willing to give 30 pounds a quarter, or 120 pounds a +year, so as to recompense you for any little inconvenience which +our fads may cause you. They are not very exacting, after all. My +wife is fond of a particular shade of electric blue and would +like you to wear such a dress indoors in the morning. You need +not, however, go to the expense of purchasing one, as we have one +belonging to my dear daughter Alice (now in Philadelphia), which +would, I should think, fit you very well. Then, as to sitting +here or there, or amusing yourself in any manner indicated, that +need cause you no inconvenience. As regards your hair, it is no +doubt a pity, especially as I could not help remarking its beauty +during our short interview, but I am afraid that I must remain +firm upon this point, and I only hope that the increased salary +may recompense you for the loss. Your duties, as far as the child +is concerned, are very light. Now do try to come, and I shall +meet you with the dog-cart at Winchester. Let me know your train. +Yours faithfully, JEPHRO RUCASTLE.' + +"That is the letter which I have just received, Mr. Holmes, and +my mind is made up that I will accept it. I thought, however, +that before taking the final step I should like to submit the +whole matter to your consideration." + +"Well, Miss Hunter, if your mind is made up, that settles the +question," said Holmes, smiling. + +"But you would not advise me to refuse?" + +"I confess that it is not the situation which I should like to +see a sister of mine apply for." + +"What is the meaning of it all, Mr. Holmes?" + +"Ah, I have no data. I cannot tell. Perhaps you have yourself +formed some opinion?" + +"Well, there seems to me to be only one possible solution. Mr. +Rucastle seemed to be a very kind, good-natured man. Is it not +possible that his wife is a lunatic, that he desires to keep the +matter quiet for fear she should be taken to an asylum, and that +he humours her fancies in every way in order to prevent an +outbreak?" + +"That is a possible solution--in fact, as matters stand, it is +the most probable one. But in any case it does not seem to be a +nice household for a young lady." + +"But the money, Mr. Holmes, the money!" + +"Well, yes, of course the pay is good--too good. That is what +makes me uneasy. Why should they give you 120 pounds a year, when +they could have their pick for 40 pounds? There must be some +strong reason behind." + +"I thought that if I told you the circumstances you would +understand afterwards if I wanted your help. I should feel so +much stronger if I felt that you were at the back of me." + +"Oh, you may carry that feeling away with you. I assure you that +your little problem promises to be the most interesting which has +come my way for some months. There is something distinctly novel +about some of the features. If you should find yourself in doubt +or in danger--" + +"Danger! What danger do you foresee?" + +Holmes shook his head gravely. "It would cease to be a danger if +we could define it," said he. "But at any time, day or night, a +telegram would bring me down to your help." + +"That is enough." She rose briskly from her chair with the +anxiety all swept from her face. "I shall go down to Hampshire +quite easy in my mind now. I shall write to Mr. Rucastle at once, +sacrifice my poor hair to-night, and start for Winchester +to-morrow." With a few grateful words to Holmes she bade us both +good-night and bustled off upon her way. + +"At least," said I as we heard her quick, firm steps descending +the stairs, "she seems to be a young lady who is very well able +to take care of herself." + +"And she would need to be," said Holmes gravely. "I am much +mistaken if we do not hear from her before many days are past." + +It was not very long before my friend's prediction was fulfilled. +A fortnight went by, during which I frequently found my thoughts +turning in her direction and wondering what strange side-alley of +human experience this lonely woman had strayed into. The unusual +salary, the curious conditions, the light duties, all pointed to +something abnormal, though whether a fad or a plot, or whether +the man were a philanthropist or a villain, it was quite beyond +my powers to determine. As to Holmes, I observed that he sat +frequently for half an hour on end, with knitted brows and an +abstracted air, but he swept the matter away with a wave of his +hand when I mentioned it. "Data! data! data!" he cried +impatiently. "I can't make bricks without clay." And yet he would +always wind up by muttering that no sister of his should ever +have accepted such a situation. + +The telegram which we eventually received came late one night +just as I was thinking of turning in and Holmes was settling down +to one of those all-night chemical researches which he frequently +indulged in, when I would leave him stooping over a retort and a +test-tube at night and find him in the same position when I came +down to breakfast in the morning. He opened the yellow envelope, +and then, glancing at the message, threw it across to me. + +"Just look up the trains in Bradshaw," said he, and turned back +to his chemical studies. + +The summons was a brief and urgent one. + +"Please be at the Black Swan Hotel at Winchester at midday +to-morrow," it said. "Do come! I am at my wit's end. HUNTER." + +"Will you come with me?" asked Holmes, glancing up. + +"I should wish to." + +"Just look it up, then." + +"There is a train at half-past nine," said I, glancing over my +Bradshaw. "It is due at Winchester at 11:30." + +"That will do very nicely. Then perhaps I had better postpone my +analysis of the acetones, as we may need to be at our best in the +morning." + +By eleven o'clock the next day we were well upon our way to the +old English capital. Holmes had been buried in the morning papers +all the way down, but after we had passed the Hampshire border he +threw them down and began to admire the scenery. It was an ideal +spring day, a light blue sky, flecked with little fleecy white +clouds drifting across from west to east. The sun was shining +very brightly, and yet there was an exhilarating nip in the air, +which set an edge to a man's energy. All over the countryside, +away to the rolling hills around Aldershot, the little red and +grey roofs of the farm-steadings peeped out from amid the light +green of the new foliage. + +"Are they not fresh and beautiful?" I cried with all the +enthusiasm of a man fresh from the fogs of Baker Street. + +But Holmes shook his head gravely. + +"Do you know, Watson," said he, "that it is one of the curses of +a mind with a turn like mine that I must look at everything with +reference to my own special subject. You look at these scattered +houses, and you are impressed by their beauty. I look at them, +and the only thought which comes to me is a feeling of their +isolation and of the impunity with which crime may be committed +there." + +"Good heavens!" I cried. "Who would associate crime with these +dear old homesteads?" + +"They always fill me with a certain horror. It is my belief, +Watson, founded upon my experience, that the lowest and vilest +alleys in London do not present a more dreadful record of sin +than does the smiling and beautiful countryside." + +"You horrify me!" + +"But the reason is very obvious. The pressure of public opinion +can do in the town what the law cannot accomplish. There is no +lane so vile that the scream of a tortured child, or the thud of +a drunkard's blow, does not beget sympathy and indignation among +the neighbours, and then the whole machinery of justice is ever +so close that a word of complaint can set it going, and there is +but a step between the crime and the dock. But look at these +lonely houses, each in its own fields, filled for the most part +with poor ignorant folk who know little of the law. Think of the +deeds of hellish cruelty, the hidden wickedness which may go on, +year in, year out, in such places, and none the wiser. Had this +lady who appeals to us for help gone to live in Winchester, I +should never have had a fear for her. It is the five miles of +country which makes the danger. Still, it is clear that she is +not personally threatened." + +"No. If she can come to Winchester to meet us she can get away." + +"Quite so. She has her freedom." + +"What CAN be the matter, then? Can you suggest no explanation?" + +"I have devised seven separate explanations, each of which would +cover the facts as far as we know them. But which of these is +correct can only be determined by the fresh information which we +shall no doubt find waiting for us. Well, there is the tower of +the cathedral, and we shall soon learn all that Miss Hunter has +to tell." + +The Black Swan is an inn of repute in the High Street, at no +distance from the station, and there we found the young lady +waiting for us. She had engaged a sitting-room, and our lunch +awaited us upon the table. + +"I am so delighted that you have come," she said earnestly. "It +is so very kind of you both; but indeed I do not know what I +should do. Your advice will be altogether invaluable to me." + +"Pray tell us what has happened to you." + +"I will do so, and I must be quick, for I have promised Mr. +Rucastle to be back before three. I got his leave to come into +town this morning, though he little knew for what purpose." + +"Let us have everything in its due order." Holmes thrust his long +thin legs out towards the fire and composed himself to listen. + +"In the first place, I may say that I have met, on the whole, +with no actual ill-treatment from Mr. and Mrs. Rucastle. It is +only fair to them to say that. But I cannot understand them, and +I am not easy in my mind about them." + +"What can you not understand?" + +"Their reasons for their conduct. But you shall have it all just +as it occurred. When I came down, Mr. Rucastle met me here and +drove me in his dog-cart to the Copper Beeches. It is, as he +said, beautifully situated, but it is not beautiful in itself, +for it is a large square block of a house, whitewashed, but all +stained and streaked with damp and bad weather. There are grounds +round it, woods on three sides, and on the fourth a field which +slopes down to the Southampton highroad, which curves past about +a hundred yards from the front door. This ground in front belongs +to the house, but the woods all round are part of Lord +Southerton's preserves. A clump of copper beeches immediately in +front of the hall door has given its name to the place. + +"I was driven over by my employer, who was as amiable as ever, +and was introduced by him that evening to his wife and the child. +There was no truth, Mr. Holmes, in the conjecture which seemed to +us to be probable in your rooms at Baker Street. Mrs. Rucastle is +not mad. I found her to be a silent, pale-faced woman, much +younger than her husband, not more than thirty, I should think, +while he can hardly be less than forty-five. From their +conversation I have gathered that they have been married about +seven years, that he was a widower, and that his only child by +the first wife was the daughter who has gone to Philadelphia. Mr. +Rucastle told me in private that the reason why she had left them +was that she had an unreasoning aversion to her stepmother. As +the daughter could not have been less than twenty, I can quite +imagine that her position must have been uncomfortable with her +father's young wife. + +"Mrs. Rucastle seemed to me to be colourless in mind as well as +in feature. She impressed me neither favourably nor the reverse. +She was a nonentity. It was easy to see that she was passionately +devoted both to her husband and to her little son. Her light grey +eyes wandered continually from one to the other, noting every +little want and forestalling it if possible. He was kind to her +also in his bluff, boisterous fashion, and on the whole they +seemed to be a happy couple. And yet she had some secret sorrow, +this woman. She would often be lost in deep thought, with the +saddest look upon her face. More than once I have surprised her +in tears. I have thought sometimes that it was the disposition of +her child which weighed upon her mind, for I have never met so +utterly spoiled and so ill-natured a little creature. He is small +for his age, with a head which is quite disproportionately large. +His whole life appears to be spent in an alternation between +savage fits of passion and gloomy intervals of sulking. Giving +pain to any creature weaker than himself seems to be his one idea +of amusement, and he shows quite remarkable talent in planning +the capture of mice, little birds, and insects. But I would +rather not talk about the creature, Mr. Holmes, and, indeed, he +has little to do with my story." + +"I am glad of all details," remarked my friend, "whether they +seem to you to be relevant or not." + +"I shall try not to miss anything of importance. The one +unpleasant thing about the house, which struck me at once, was +the appearance and conduct of the servants. There are only two, a +man and his wife. Toller, for that is his name, is a rough, +uncouth man, with grizzled hair and whiskers, and a perpetual +smell of drink. Twice since I have been with them he has been +quite drunk, and yet Mr. Rucastle seemed to take no notice of it. +His wife is a very tall and strong woman with a sour face, as +silent as Mrs. Rucastle and much less amiable. They are a most +unpleasant couple, but fortunately I spend most of my time in the +nursery and my own room, which are next to each other in one +corner of the building. + +"For two days after my arrival at the Copper Beeches my life was +very quiet; on the third, Mrs. Rucastle came down just after +breakfast and whispered something to her husband. + +"'Oh, yes,' said he, turning to me, 'we are very much obliged to +you, Miss Hunter, for falling in with our whims so far as to cut +your hair. I assure you that it has not detracted in the tiniest +iota from your appearance. We shall now see how the electric-blue +dress will become you. You will find it laid out upon the bed in +your room, and if you would be so good as to put it on we should +both be extremely obliged.' + +"The dress which I found waiting for me was of a peculiar shade +of blue. It was of excellent material, a sort of beige, but it +bore unmistakable signs of having been worn before. It could not +have been a better fit if I had been measured for it. Both Mr. +and Mrs. Rucastle expressed a delight at the look of it, which +seemed quite exaggerated in its vehemence. They were waiting for +me in the drawing-room, which is a very large room, stretching +along the entire front of the house, with three long windows +reaching down to the floor. A chair had been placed close to the +central window, with its back turned towards it. In this I was +asked to sit, and then Mr. Rucastle, walking up and down on the +other side of the room, began to tell me a series of the funniest +stories that I have ever listened to. You cannot imagine how +comical he was, and I laughed until I was quite weary. Mrs. +Rucastle, however, who has evidently no sense of humour, never so +much as smiled, but sat with her hands in her lap, and a sad, +anxious look upon her face. After an hour or so, Mr. Rucastle +suddenly remarked that it was time to commence the duties of the +day, and that I might change my dress and go to little Edward in +the nursery. + +"Two days later this same performance was gone through under +exactly similar circumstances. Again I changed my dress, again I +sat in the window, and again I laughed very heartily at the funny +stories of which my employer had an immense rpertoire, and which +he told inimitably. Then he handed me a yellow-backed novel, and +moving my chair a little sideways, that my own shadow might not +fall upon the page, he begged me to read aloud to him. I read for +about ten minutes, beginning in the heart of a chapter, and then +suddenly, in the middle of a sentence, he ordered me to cease and +to change my dress. + +"You can easily imagine, Mr. Holmes, how curious I became as to +what the meaning of this extraordinary performance could possibly +be. They were always very careful, I observed, to turn my face +away from the window, so that I became consumed with the desire +to see what was going on behind my back. At first it seemed to be +impossible, but I soon devised a means. My hand-mirror had been +broken, so a happy thought seized me, and I concealed a piece of +the glass in my handkerchief. On the next occasion, in the midst +of my laughter, I put my handkerchief up to my eyes, and was able +with a little management to see all that there was behind me. I +confess that I was disappointed. There was nothing. At least that +was my first impression. At the second glance, however, I +perceived that there was a man standing in the Southampton Road, +a small bearded man in a grey suit, who seemed to be looking in +my direction. The road is an important highway, and there are +usually people there. This man, however, was leaning against the +railings which bordered our field and was looking earnestly up. I +lowered my handkerchief and glanced at Mrs. Rucastle to find her +eyes fixed upon me with a most searching gaze. She said nothing, +but I am convinced that she had divined that I had a mirror in my +hand and had seen what was behind me. She rose at once. + +"'Jephro,' said she, 'there is an impertinent fellow upon the +road there who stares up at Miss Hunter.' + +"'No friend of yours, Miss Hunter?' he asked. + +"'No, I know no one in these parts.' + +"'Dear me! How very impertinent! Kindly turn round and motion to +him to go away.' + +"'Surely it would be better to take no notice.' + +"'No, no, we should have him loitering here always. Kindly turn +round and wave him away like that.' + +"I did as I was told, and at the same instant Mrs. Rucastle drew +down the blind. That was a week ago, and from that time I have +not sat again in the window, nor have I worn the blue dress, nor +seen the man in the road." + +"Pray continue," said Holmes. "Your narrative promises to be a +most interesting one." + +"You will find it rather disconnected, I fear, and there may +prove to be little relation between the different incidents of +which I speak. On the very first day that I was at the Copper +Beeches, Mr. Rucastle took me to a small outhouse which stands +near the kitchen door. As we approached it I heard the sharp +rattling of a chain, and the sound as of a large animal moving +about. + +"'Look in here!' said Mr. Rucastle, showing me a slit between two +planks. 'Is he not a beauty?' + +"I looked through and was conscious of two glowing eyes, and of a +vague figure huddled up in the darkness. + +"'Don't be frightened,' said my employer, laughing at the start +which I had given. 'It's only Carlo, my mastiff. I call him mine, +but really old Toller, my groom, is the only man who can do +anything with him. We feed him once a day, and not too much then, +so that he is always as keen as mustard. Toller lets him loose +every night, and God help the trespasser whom he lays his fangs +upon. For goodness' sake don't you ever on any pretext set your +foot over the threshold at night, for it's as much as your life +is worth.' + +"The warning was no idle one, for two nights later I happened to +look out of my bedroom window about two o'clock in the morning. +It was a beautiful moonlight night, and the lawn in front of the +house was silvered over and almost as bright as day. I was +standing, rapt in the peaceful beauty of the scene, when I was +aware that something was moving under the shadow of the copper +beeches. As it emerged into the moonshine I saw what it was. It +was a giant dog, as large as a calf, tawny tinted, with hanging +jowl, black muzzle, and huge projecting bones. It walked slowly +across the lawn and vanished into the shadow upon the other side. +That dreadful sentinel sent a chill to my heart which I do not +think that any burglar could have done. + +"And now I have a very strange experience to tell you. I had, as +you know, cut off my hair in London, and I had placed it in a +great coil at the bottom of my trunk. One evening, after the +child was in bed, I began to amuse myself by examining the +furniture of my room and by rearranging my own little things. +There was an old chest of drawers in the room, the two upper ones +empty and open, the lower one locked. I had filled the first two +with my linen, and as I had still much to pack away I was +naturally annoyed at not having the use of the third drawer. It +struck me that it might have been fastened by a mere oversight, +so I took out my bunch of keys and tried to open it. The very +first key fitted to perfection, and I drew the drawer open. There +was only one thing in it, but I am sure that you would never +guess what it was. It was my coil of hair. + +"I took it up and examined it. It was of the same peculiar tint, +and the same thickness. But then the impossibility of the thing +obtruded itself upon me. How could my hair have been locked in +the drawer? With trembling hands I undid my trunk, turned out the +contents, and drew from the bottom my own hair. I laid the two +tresses together, and I assure you that they were identical. Was +it not extraordinary? Puzzle as I would, I could make nothing at +all of what it meant. I returned the strange hair to the drawer, +and I said nothing of the matter to the Rucastles as I felt that +I had put myself in the wrong by opening a drawer which they had +locked. + +"I am naturally observant, as you may have remarked, Mr. Holmes, +and I soon had a pretty good plan of the whole house in my head. +There was one wing, however, which appeared not to be inhabited +at all. A door which faced that which led into the quarters of +the Tollers opened into this suite, but it was invariably locked. +One day, however, as I ascended the stair, I met Mr. Rucastle +coming out through this door, his keys in his hand, and a look on +his face which made him a very different person to the round, +jovial man to whom I was accustomed. His cheeks were red, his +brow was all crinkled with anger, and the veins stood out at his +temples with passion. He locked the door and hurried past me +without a word or a look. + +"This aroused my curiosity, so when I went out for a walk in the +grounds with my charge, I strolled round to the side from which I +could see the windows of this part of the house. There were four +of them in a row, three of which were simply dirty, while the +fourth was shuttered up. They were evidently all deserted. As I +strolled up and down, glancing at them occasionally, Mr. Rucastle +came out to me, looking as merry and jovial as ever. + +"'Ah!' said he, 'you must not think me rude if I passed you +without a word, my dear young lady. I was preoccupied with +business matters.' + +"I assured him that I was not offended. 'By the way,' said I, +'you seem to have quite a suite of spare rooms up there, and one +of them has the shutters up.' + +"He looked surprised and, as it seemed to me, a little startled +at my remark. + +"'Photography is one of my hobbies,' said he. 'I have made my +dark room up there. But, dear me! what an observant young lady we +have come upon. Who would have believed it? Who would have ever +believed it?' He spoke in a jesting tone, but there was no jest +in his eyes as he looked at me. I read suspicion there and +annoyance, but no jest. + +"Well, Mr. Holmes, from the moment that I understood that there +was something about that suite of rooms which I was not to know, +I was all on fire to go over them. It was not mere curiosity, +though I have my share of that. It was more a feeling of duty--a +feeling that some good might come from my penetrating to this +place. They talk of woman's instinct; perhaps it was woman's +instinct which gave me that feeling. At any rate, it was there, +and I was keenly on the lookout for any chance to pass the +forbidden door. + +"It was only yesterday that the chance came. I may tell you that, +besides Mr. Rucastle, both Toller and his wife find something to +do in these deserted rooms, and I once saw him carrying a large +black linen bag with him through the door. Recently he has been +drinking hard, and yesterday evening he was very drunk; and when +I came upstairs there was the key in the door. I have no doubt at +all that he had left it there. Mr. and Mrs. Rucastle were both +downstairs, and the child was with them, so that I had an +admirable opportunity. I turned the key gently in the lock, +opened the door, and slipped through. + +"There was a little passage in front of me, unpapered and +uncarpeted, which turned at a right angle at the farther end. +Round this corner were three doors in a line, the first and third +of which were open. They each led into an empty room, dusty and +cheerless, with two windows in the one and one in the other, so +thick with dirt that the evening light glimmered dimly through +them. The centre door was closed, and across the outside of it +had been fastened one of the broad bars of an iron bed, padlocked +at one end to a ring in the wall, and fastened at the other with +stout cord. The door itself was locked as well, and the key was +not there. This barricaded door corresponded clearly with the +shuttered window outside, and yet I could see by the glimmer from +beneath it that the room was not in darkness. Evidently there was +a skylight which let in light from above. As I stood in the +passage gazing at the sinister door and wondering what secret it +might veil, I suddenly heard the sound of steps within the room +and saw a shadow pass backward and forward against the little +slit of dim light which shone out from under the door. A mad, +unreasoning terror rose up in me at the sight, Mr. Holmes. My +overstrung nerves failed me suddenly, and I turned and ran--ran +as though some dreadful hand were behind me clutching at the +skirt of my dress. I rushed down the passage, through the door, +and straight into the arms of Mr. Rucastle, who was waiting +outside. + +"'So,' said he, smiling, 'it was you, then. I thought that it +must be when I saw the door open.' + +"'Oh, I am so frightened!' I panted. + +"'My dear young lady! my dear young lady!'--you cannot think how +caressing and soothing his manner was--'and what has frightened +you, my dear young lady?' + +"But his voice was just a little too coaxing. He overdid it. I +was keenly on my guard against him. + +"'I was foolish enough to go into the empty wing,' I answered. +'But it is so lonely and eerie in this dim light that I was +frightened and ran out again. Oh, it is so dreadfully still in +there!' + +"'Only that?' said he, looking at me keenly. + +"'Why, what did you think?' I asked. + +"'Why do you think that I lock this door?' + +"'I am sure that I do not know.' + +"'It is to keep people out who have no business there. Do you +see?' He was still smiling in the most amiable manner. + +"'I am sure if I had known--' + +"'Well, then, you know now. And if you ever put your foot over +that threshold again'--here in an instant the smile hardened into +a grin of rage, and he glared down at me with the face of a +demon--'I'll throw you to the mastiff.' + +"I was so terrified that I do not know what I did. I suppose that +I must have rushed past him into my room. I remember nothing +until I found myself lying on my bed trembling all over. Then I +thought of you, Mr. Holmes. I could not live there longer without +some advice. I was frightened of the house, of the man, of the +woman, of the servants, even of the child. They were all horrible +to me. If I could only bring you down all would be well. Of +course I might have fled from the house, but my curiosity was +almost as strong as my fears. My mind was soon made up. I would +send you a wire. I put on my hat and cloak, went down to the +office, which is about half a mile from the house, and then +returned, feeling very much easier. A horrible doubt came into my +mind as I approached the door lest the dog might be loose, but I +remembered that Toller had drunk himself into a state of +insensibility that evening, and I knew that he was the only one +in the household who had any influence with the savage creature, +or who would venture to set him free. I slipped in in safety and +lay awake half the night in my joy at the thought of seeing you. +I had no difficulty in getting leave to come into Winchester this +morning, but I must be back before three o'clock, for Mr. and +Mrs. Rucastle are going on a visit, and will be away all the +evening, so that I must look after the child. Now I have told you +all my adventures, Mr. Holmes, and I should be very glad if you +could tell me what it all means, and, above all, what I should +do." + +Holmes and I had listened spellbound to this extraordinary story. +My friend rose now and paced up and down the room, his hands in +his pockets, and an expression of the most profound gravity upon +his face. + +"Is Toller still drunk?" he asked. + +"Yes. I heard his wife tell Mrs. Rucastle that she could do +nothing with him." + +"That is well. And the Rucastles go out to-night?" + +"Yes." + +"Is there a cellar with a good strong lock?" + +"Yes, the wine-cellar." + +"You seem to me to have acted all through this matter like a very +brave and sensible girl, Miss Hunter. Do you think that you could +perform one more feat? I should not ask it of you if I did not +think you a quite exceptional woman." + +"I will try. What is it?" + +"We shall be at the Copper Beeches by seven o'clock, my friend +and I. The Rucastles will be gone by that time, and Toller will, +we hope, be incapable. There only remains Mrs. Toller, who might +give the alarm. If you could send her into the cellar on some +errand, and then turn the key upon her, you would facilitate +matters immensely." + +"I will do it." + +"Excellent! We shall then look thoroughly into the affair. Of +course there is only one feasible explanation. You have been +brought there to personate someone, and the real person is +imprisoned in this chamber. That is obvious. As to who this +prisoner is, I have no doubt that it is the daughter, Miss Alice +Rucastle, if I remember right, who was said to have gone to +America. You were chosen, doubtless, as resembling her in height, +figure, and the colour of your hair. Hers had been cut off, very +possibly in some illness through which she has passed, and so, of +course, yours had to be sacrificed also. By a curious chance you +came upon her tresses. The man in the road was undoubtedly some +friend of hers--possibly her fianc--and no doubt, as you wore +the girl's dress and were so like her, he was convinced from your +laughter, whenever he saw you, and afterwards from your gesture, +that Miss Rucastle was perfectly happy, and that she no longer +desired his attentions. The dog is let loose at night to prevent +him from endeavouring to communicate with her. So much is fairly +clear. The most serious point in the case is the disposition of +the child." + +"What on earth has that to do with it?" I ejaculated. + +"My dear Watson, you as a medical man are continually gaining +light as to the tendencies of a child by the study of the +parents. Don't you see that the converse is equally valid. I have +frequently gained my first real insight into the character of +parents by studying their children. This child's disposition is +abnormally cruel, merely for cruelty's sake, and whether he +derives this from his smiling father, as I should suspect, or +from his mother, it bodes evil for the poor girl who is in their +power." + +"I am sure that you are right, Mr. Holmes," cried our client. "A +thousand things come back to me which make me certain that you +have hit it. Oh, let us lose not an instant in bringing help to +this poor creature." + +"We must be circumspect, for we are dealing with a very cunning +man. We can do nothing until seven o'clock. At that hour we shall +be with you, and it will not be long before we solve the +mystery." + +We were as good as our word, for it was just seven when we +reached the Copper Beeches, having put up our trap at a wayside +public-house. The group of trees, with their dark leaves shining +like burnished metal in the light of the setting sun, were +sufficient to mark the house even had Miss Hunter not been +standing smiling on the door-step. + +"Have you managed it?" asked Holmes. + +A loud thudding noise came from somewhere downstairs. "That is +Mrs. Toller in the cellar," said she. "Her husband lies snoring +on the kitchen rug. Here are his keys, which are the duplicates +of Mr. Rucastle's." + +"You have done well indeed!" cried Holmes with enthusiasm. "Now +lead the way, and we shall soon see the end of this black +business." + +We passed up the stair, unlocked the door, followed on down a +passage, and found ourselves in front of the barricade which Miss +Hunter had described. Holmes cut the cord and removed the +transverse bar. Then he tried the various keys in the lock, but +without success. No sound came from within, and at the silence +Holmes' face clouded over. + +"I trust that we are not too late," said he. "I think, Miss +Hunter, that we had better go in without you. Now, Watson, put +your shoulder to it, and we shall see whether we cannot make our +way in." + +It was an old rickety door and gave at once before our united +strength. Together we rushed into the room. It was empty. There +was no furniture save a little pallet bed, a small table, and a +basketful of linen. The skylight above was open, and the prisoner +gone. + +"There has been some villainy here," said Holmes; "this beauty +has guessed Miss Hunter's intentions and has carried his victim +off." + +"But how?" + +"Through the skylight. We shall soon see how he managed it." He +swung himself up onto the roof. "Ah, yes," he cried, "here's the +end of a long light ladder against the eaves. That is how he did +it." + +"But it is impossible," said Miss Hunter; "the ladder was not +there when the Rucastles went away." + +"He has come back and done it. I tell you that he is a clever and +dangerous man. I should not be very much surprised if this were +he whose step I hear now upon the stair. I think, Watson, that it +would be as well for you to have your pistol ready." + +The words were hardly out of his mouth before a man appeared at +the door of the room, a very fat and burly man, with a heavy +stick in his hand. Miss Hunter screamed and shrunk against the +wall at the sight of him, but Sherlock Holmes sprang forward and +confronted him. + +"You villain!" said he, "where's your daughter?" + +The fat man cast his eyes round, and then up at the open +skylight. + +"It is for me to ask you that," he shrieked, "you thieves! Spies +and thieves! I have caught you, have I? You are in my power. I'll +serve you!" He turned and clattered down the stairs as hard as he +could go. + +"He's gone for the dog!" cried Miss Hunter. + +"I have my revolver," said I. + +"Better close the front door," cried Holmes, and we all rushed +down the stairs together. We had hardly reached the hall when we +heard the baying of a hound, and then a scream of agony, with a +horrible worrying sound which it was dreadful to listen to. An +elderly man with a red face and shaking limbs came staggering out +at a side door. + +"My God!" he cried. "Someone has loosed the dog. It's not been +fed for two days. Quick, quick, or it'll be too late!" + +Holmes and I rushed out and round the angle of the house, with +Toller hurrying behind us. There was the huge famished brute, its +black muzzle buried in Rucastle's throat, while he writhed and +screamed upon the ground. Running up, I blew its brains out, and +it fell over with its keen white teeth still meeting in the great +creases of his neck. With much labour we separated them and +carried him, living but horribly mangled, into the house. We laid +him upon the drawing-room sofa, and having dispatched the sobered +Toller to bear the news to his wife, I did what I could to +relieve his pain. We were all assembled round him when the door +opened, and a tall, gaunt woman entered the room. + +"Mrs. Toller!" cried Miss Hunter. + +"Yes, miss. Mr. Rucastle let me out when he came back before he +went up to you. Ah, miss, it is a pity you didn't let me know +what you were planning, for I would have told you that your pains +were wasted." + +"Ha!" said Holmes, looking keenly at her. "It is clear that Mrs. +Toller knows more about this matter than anyone else." + +"Yes, sir, I do, and I am ready enough to tell what I know." + +"Then, pray, sit down, and let us hear it for there are several +points on which I must confess that I am still in the dark." + +"I will soon make it clear to you," said she; "and I'd have done +so before now if I could ha' got out from the cellar. If there's +police-court business over this, you'll remember that I was the +one that stood your friend, and that I was Miss Alice's friend +too. + +"She was never happy at home, Miss Alice wasn't, from the time +that her father married again. She was slighted like and had no +say in anything, but it never really became bad for her until +after she met Mr. Fowler at a friend's house. As well as I could +learn, Miss Alice had rights of her own by will, but she was so +quiet and patient, she was, that she never said a word about them +but just left everything in Mr. Rucastle's hands. He knew he was +safe with her; but when there was a chance of a husband coming +forward, who would ask for all that the law would give him, then +her father thought it time to put a stop on it. He wanted her to +sign a paper, so that whether she married or not, he could use +her money. When she wouldn't do it, he kept on worrying her until +she got brain-fever, and for six weeks was at death's door. Then +she got better at last, all worn to a shadow, and with her +beautiful hair cut off; but that didn't make no change in her +young man, and he stuck to her as true as man could be." + +"Ah," said Holmes, "I think that what you have been good enough +to tell us makes the matter fairly clear, and that I can deduce +all that remains. Mr. Rucastle then, I presume, took to this +system of imprisonment?" + +"Yes, sir." + +"And brought Miss Hunter down from London in order to get rid of +the disagreeable persistence of Mr. Fowler." + +"That was it, sir." + +"But Mr. Fowler being a persevering man, as a good seaman should +be, blockaded the house, and having met you succeeded by certain +arguments, metallic or otherwise, in convincing you that your +interests were the same as his." + +"Mr. Fowler was a very kind-spoken, free-handed gentleman," said +Mrs. Toller serenely. + +"And in this way he managed that your good man should have no +want of drink, and that a ladder should be ready at the moment +when your master had gone out." + +"You have it, sir, just as it happened." + +"I am sure we owe you an apology, Mrs. Toller," said Holmes, "for +you have certainly cleared up everything which puzzled us. And +here comes the country surgeon and Mrs. Rucastle, so I think, +Watson, that we had best escort Miss Hunter back to Winchester, +as it seems to me that our locus standi now is rather a +questionable one." + +And thus was solved the mystery of the sinister house with the +copper beeches in front of the door. Mr. Rucastle survived, but +was always a broken man, kept alive solely through the care of +his devoted wife. They still live with their old servants, who +probably know so much of Rucastle's past life that he finds it +difficult to part from them. Mr. Fowler and Miss Rucastle were +married, by special license, in Southampton the day after their +flight, and he is now the holder of a government appointment in +the island of Mauritius. As to Miss Violet Hunter, my friend +Holmes, rather to my disappointment, manifested no further +interest in her when once she had ceased to be the centre of one +of his problems, and she is now the head of a private school at +Walsall, where I believe that she has met with considerable success. + + + + + + + + + +End of the Project Gutenberg EBook of The Adventures of Sherlock Holmes, by +Arthur Conan Doyle + +*** END OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES *** + +***** This file should be named 1661-8.txt or 1661-8.zip ***** +This and all associated files of various formats will be found in: + http://www.gutenberg.org/1/6/6/1661/ + +Produced by an anonymous Project Gutenberg volunteer and Jose Menendez + +Updated editions will replace the previous one--the old editions +will be renamed. + +Creating the works from public domain print editions means that no +one owns a United States copyright in these works, so the Foundation +(and you!) can copy and distribute it in the United States without +permission and without paying copyright royalties. Special rules, +set forth in the General Terms of Use part of this license, apply to +copying and distributing Project Gutenberg-tm electronic works to +protect the PROJECT GUTENBERG-tm concept and trademark. Project +Gutenberg is a registered trademark, and may not be used if you +charge for the eBooks, unless you receive specific permission. If you +do not charge anything for copies of this eBook, complying with the +rules is very easy. You may use this eBook for nearly any purpose +such as creation of derivative works, reports, performances and +research. They may be modified and printed and given away--you may do +practically ANYTHING with public domain eBooks. Redistribution is +subject to the trademark license, especially commercial +redistribution. + + + +*** START: FULL LICENSE *** + +THE FULL PROJECT GUTENBERG LICENSE +PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK + +To protect the Project Gutenberg-tm mission of promoting the free +distribution of electronic works, by using or distributing this work +(or any other work associated in any way with the phrase "Project +Gutenberg"), you agree to comply with all the terms of the Full Project +Gutenberg-tm License (available with this file or online at +http://gutenberg.net/license). + + +Section 1. General Terms of Use and Redistributing Project Gutenberg-tm +electronic works + +1.A. By reading or using any part of this Project Gutenberg-tm +electronic work, you indicate that you have read, understand, agree to +and accept all the terms of this license and intellectual property +(trademark/copyright) agreement. If you do not agree to abide by all +the terms of this agreement, you must cease using and return or destroy +all copies of Project Gutenberg-tm electronic works in your possession. +If you paid a fee for obtaining a copy of or access to a Project +Gutenberg-tm electronic work and you do not agree to be bound by the +terms of this agreement, you may obtain a refund from the person or +entity to whom you paid the fee as set forth in paragraph 1.E.8. + +1.B. "Project Gutenberg" is a registered trademark. It may only be +used on or associated in any way with an electronic work by people who +agree to be bound by the terms of this agreement. There are a few +things that you can do with most Project Gutenberg-tm electronic works +even without complying with the full terms of this agreement. See +paragraph 1.C below. There are a lot of things you can do with Project +Gutenberg-tm electronic works if you follow the terms of this agreement +and help preserve free future access to Project Gutenberg-tm electronic +works. See paragraph 1.E below. + +1.C. The Project Gutenberg Literary Archive Foundation ("the Foundation" +or PGLAF), owns a compilation copyright in the collection of Project +Gutenberg-tm electronic works. Nearly all the individual works in the +collection are in the public domain in the United States. If an +individual work is in the public domain in the United States and you are +located in the United States, we do not claim a right to prevent you from +copying, distributing, performing, displaying or creating derivative +works based on the work as long as all references to Project Gutenberg +are removed. Of course, we hope that you will support the Project +Gutenberg-tm mission of promoting free access to electronic works by +freely sharing Project Gutenberg-tm works in compliance with the terms of +this agreement for keeping the Project Gutenberg-tm name associated with +the work. You can easily comply with the terms of this agreement by +keeping this work in the same format with its attached full Project +Gutenberg-tm License when you share it without charge with others. + +1.D. The copyright laws of the place where you are located also govern +what you can do with this work. Copyright laws in most countries are in +a constant state of change. If you are outside the United States, check +the laws of your country in addition to the terms of this agreement +before downloading, copying, displaying, performing, distributing or +creating derivative works based on this work or any other Project +Gutenberg-tm work. The Foundation makes no representations concerning +the copyright status of any work in any country outside the United +States. + +1.E. Unless you have removed all references to Project Gutenberg: + +1.E.1. The following sentence, with active links to, or other immediate +access to, the full Project Gutenberg-tm License must appear prominently +whenever any copy of a Project Gutenberg-tm work (any work on which the +phrase "Project Gutenberg" appears, or with which the phrase "Project +Gutenberg" is associated) is accessed, displayed, performed, viewed, +copied or distributed: + +This eBook is for the use of anyone anywhere at no cost and with +almost no restrictions whatsoever. You may copy it, give it away or +re-use it under the terms of the Project Gutenberg License included +with this eBook or online at www.gutenberg.net + +1.E.2. If an individual Project Gutenberg-tm electronic work is derived +from the public domain (does not contain a notice indicating that it is +posted with permission of the copyright holder), the work can be copied +and distributed to anyone in the United States without paying any fees +or charges. If you are redistributing or providing access to a work +with the phrase "Project Gutenberg" associated with or appearing on the +work, you must comply either with the requirements of paragraphs 1.E.1 +through 1.E.7 or obtain permission for the use of the work and the +Project Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or +1.E.9. + +1.E.3. If an individual Project Gutenberg-tm electronic work is posted +with the permission of the copyright holder, your use and distribution +must comply with both paragraphs 1.E.1 through 1.E.7 and any additional +terms imposed by the copyright holder. Additional terms will be linked +to the Project Gutenberg-tm License for all works posted with the +permission of the copyright holder found at the beginning of this work. + +1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm +License terms from this work, or any files containing a part of this +work or any other work associated with Project Gutenberg-tm. + +1.E.5. Do not copy, display, perform, distribute or redistribute this +electronic work, or any part of this electronic work, without +prominently displaying the sentence set forth in paragraph 1.E.1 with +active links or immediate access to the full terms of the Project +Gutenberg-tm License. + +1.E.6. You may convert to and distribute this work in any binary, +compressed, marked up, nonproprietary or proprietary form, including any +word processing or hypertext form. However, if you provide access to or +distribute copies of a Project Gutenberg-tm work in a format other than +"Plain Vanilla ASCII" or other format used in the official version +posted on the official Project Gutenberg-tm web site (www.gutenberg.net), +you must, at no additional cost, fee or expense to the user, provide a +copy, a means of exporting a copy, or a means of obtaining a copy upon +request, of the work in its original "Plain Vanilla ASCII" or other +form. Any alternate format must include the full Project Gutenberg-tm +License as specified in paragraph 1.E.1. + +1.E.7. Do not charge a fee for access to, viewing, displaying, +performing, copying or distributing any Project Gutenberg-tm works +unless you comply with paragraph 1.E.8 or 1.E.9. + +1.E.8. You may charge a reasonable fee for copies of or providing +access to or distributing Project Gutenberg-tm electronic works provided +that + +- You pay a royalty fee of 20% of the gross profits you derive from + the use of Project Gutenberg-tm works calculated using the method + you already use to calculate your applicable taxes. The fee is + owed to the owner of the Project Gutenberg-tm trademark, but he + has agreed to donate royalties under this paragraph to the + Project Gutenberg Literary Archive Foundation. Royalty payments + must be paid within 60 days following each date on which you + prepare (or are legally required to prepare) your periodic tax + returns. Royalty payments should be clearly marked as such and + sent to the Project Gutenberg Literary Archive Foundation at the + address specified in Section 4, "Information about donations to + the Project Gutenberg Literary Archive Foundation." + +- You provide a full refund of any money paid by a user who notifies + you in writing (or by e-mail) within 30 days of receipt that s/he + does not agree to the terms of the full Project Gutenberg-tm + License. You must require such a user to return or + destroy all copies of the works possessed in a physical medium + and discontinue all use of and all access to other copies of + Project Gutenberg-tm works. + +- You provide, in accordance with paragraph 1.F.3, a full refund of any + money paid for a work or a replacement copy, if a defect in the + electronic work is discovered and reported to you within 90 days + of receipt of the work. + +- You comply with all other terms of this agreement for free + distribution of Project Gutenberg-tm works. + +1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm +electronic work or group of works on different terms than are set +forth in this agreement, you must obtain permission in writing from +both the Project Gutenberg Literary Archive Foundation and Michael +Hart, the owner of the Project Gutenberg-tm trademark. Contact the +Foundation as set forth in Section 3 below. + +1.F. + +1.F.1. Project Gutenberg volunteers and employees expend considerable +effort to identify, do copyright research on, transcribe and proofread +public domain works in creating the Project Gutenberg-tm +collection. Despite these efforts, Project Gutenberg-tm electronic +works, and the medium on which they may be stored, may contain +"Defects," such as, but not limited to, incomplete, inaccurate or +corrupt data, transcription errors, a copyright or other intellectual +property infringement, a defective or damaged disk or other medium, a +computer virus, or computer codes that damage or cannot be read by +your equipment. + +1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the "Right +of Replacement or Refund" described in paragraph 1.F.3, the Project +Gutenberg Literary Archive Foundation, the owner of the Project +Gutenberg-tm trademark, and any other party distributing a Project +Gutenberg-tm electronic work under this agreement, disclaim all +liability to you for damages, costs and expenses, including legal +fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT +LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE +PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE +TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE +LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR +INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH +DAMAGE. + +1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a +defect in this electronic work within 90 days of receiving it, you can +receive a refund of the money (if any) you paid for it by sending a +written explanation to the person you received the work from. If you +received the work on a physical medium, you must return the medium with +your written explanation. The person or entity that provided you with +the defective work may elect to provide a replacement copy in lieu of a +refund. If you received the work electronically, the person or entity +providing it to you may choose to give you a second opportunity to +receive the work electronically in lieu of a refund. If the second copy +is also defective, you may demand a refund in writing without further +opportunities to fix the problem. + +1.F.4. Except for the limited right of replacement or refund set forth +in paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER +WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +WARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE. + +1.F.5. Some states do not allow disclaimers of certain implied +warranties or the exclusion or limitation of certain types of damages. +If any disclaimer or limitation set forth in this agreement violates the +law of the state applicable to this agreement, the agreement shall be +interpreted to make the maximum disclaimer or limitation permitted by +the applicable state law. The invalidity or unenforceability of any +provision of this agreement shall not void the remaining provisions. + +1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the +trademark owner, any agent or employee of the Foundation, anyone +providing copies of Project Gutenberg-tm electronic works in accordance +with this agreement, and any volunteers associated with the production, +promotion and distribution of Project Gutenberg-tm electronic works, +harmless from all liability, costs and expenses, including legal fees, +that arise directly or indirectly from any of the following which you do +or cause to occur: (a) distribution of this or any Project Gutenberg-tm +work, (b) alteration, modification, or additions or deletions to any +Project Gutenberg-tm work, and (c) any Defect you cause. + + +Section 2. Information about the Mission of Project Gutenberg-tm + +Project Gutenberg-tm is synonymous with the free distribution of +electronic works in formats readable by the widest variety of computers +including obsolete, old, middle-aged and new computers. It exists +because of the efforts of hundreds of volunteers and donations from +people in all walks of life. + +Volunteers and financial support to provide volunteers with the +assistance they need are critical to reaching Project Gutenberg-tm's +goals and ensuring that the Project Gutenberg-tm collection will +remain freely available for generations to come. In 2001, the Project +Gutenberg Literary Archive Foundation was created to provide a secure +and permanent future for Project Gutenberg-tm and future generations. +To learn more about the Project Gutenberg Literary Archive Foundation +and how your efforts and donations can help, see Sections 3 and 4 +and the Foundation web page at http://www.pglaf.org. + + +Section 3. Information about the Project Gutenberg Literary Archive +Foundation + +The Project Gutenberg Literary Archive Foundation is a non profit +501(c)(3) educational corporation organized under the laws of the +state of Mississippi and granted tax exempt status by the Internal +Revenue Service. The Foundation's EIN or federal tax identification +number is 64-6221541. Its 501(c)(3) letter is posted at +http://pglaf.org/fundraising. Contributions to the Project Gutenberg +Literary Archive Foundation are tax deductible to the full extent +permitted by U.S. federal laws and your state's laws. + +The Foundation's principal office is located at 4557 Melan Dr. S. +Fairbanks, AK, 99712., but its volunteers and employees are scattered +throughout numerous locations. Its business office is located at +809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email +business@pglaf.org. Email contact links and up to date contact +information can be found at the Foundation's web site and official +page at http://pglaf.org + +For additional contact information: + Dr. Gregory B. Newby + Chief Executive and Director + gbnewby@pglaf.org + + +Section 4. Information about Donations to the Project Gutenberg +Literary Archive Foundation + +Project Gutenberg-tm depends upon and cannot survive without wide +spread public support and donations to carry out its mission of +increasing the number of public domain and licensed works that can be +freely distributed in machine readable form accessible by the widest +array of equipment including outdated equipment. Many small donations +($1 to $5,000) are particularly important to maintaining tax exempt +status with the IRS. + +The Foundation is committed to complying with the laws regulating +charities and charitable donations in all 50 states of the United +States. Compliance requirements are not uniform and it takes a +considerable effort, much paperwork and many fees to meet and keep up +with these requirements. We do not solicit donations in locations +where we have not received written confirmation of compliance. To +SEND DONATIONS or determine the status of compliance for any +particular state visit http://pglaf.org + +While we cannot and do not solicit contributions from states where we +have not met the solicitation requirements, we know of no prohibition +against accepting unsolicited donations from donors in such states who +approach us with offers to donate. + +International donations are gratefully accepted, but we cannot make +any statements concerning tax treatment of donations received from +outside the United States. U.S. laws alone swamp our small staff. + +Please check the Project Gutenberg Web pages for current donation +methods and addresses. Donations are accepted in a number of other +ways including including checks, online payments and credit card +donations. To donate, please visit: http://pglaf.org/donate + + +Section 5. General Information About Project Gutenberg-tm electronic +works. + +Professor Michael S. Hart is the originator of the Project Gutenberg-tm +concept of a library of electronic works that could be freely shared +with anyone. For thirty years, he produced and distributed Project +Gutenberg-tm eBooks with only a loose network of volunteer support. + + +Project Gutenberg-tm eBooks are often created from several printed +editions, all of which are confirmed as Public Domain in the U.S. +unless a copyright notice is included. Thus, we do not necessarily +keep eBooks in compliance with any particular paper edition. + + +Most people start at our Web site which has the main PG search facility: + + http://www.gutenberg.net + +This Web site includes information about Project Gutenberg-tm, +including how to make donations to the Project Gutenberg Literary +Archive Foundation, how to help produce our new eBooks, and how to +subscribe to our email newsletter to hear about new eBooks. diff --git a/students/Boundb3/Session 04/sherlock_small.txt b/students/Boundb3/Session 04/sherlock_small.txt new file mode 100644 index 0000000..47644c4 --- /dev/null +++ b/students/Boundb3/Session 04/sherlock_small.txt @@ -0,0 +1,16 @@ +One night--it was on the twentieth of March, 1888--I was +returning from a journey to a patient (for I had now returned to +civil practice), when my way led me through Baker Street. As I +passed the well-remembered door, which must always be associated +in my mind with my wooing, and with the dark incidents of the +Study in Scarlet, I was seized with a keen desire to see Holmes +again, and to know how he was employing his extraordinary powers. +His rooms were brilliantly lit, and, even as I looked up, I saw +his tall, spare figure pass twice in a dark silhouette against +the blind. He was pacing the room swiftly, eagerly, with his head +sunk upon his chest and his hands clasped behind him. To me, who +knew his every mood and habit, his attitude and manner told their +own story. He was at work again. He had risen out of his +drug-created dreams and was hot upon the scent of some new +problem. I rang the bell and was shown up to the chamber which +had formerly been in part my own. \ No newline at end of file diff --git a/students/Boundb3/Session 04/test.py b/students/Boundb3/Session 04/test.py new file mode 100644 index 0000000..88b04bf --- /dev/null +++ b/students/Boundb3/Session 04/test.py @@ -0,0 +1,39 @@ + +#play with string print format +print(1234567890112345678901234567890) +a= "abcd\te\tfghij\tklmno\tpqrstu\tvvw\txyz" +b= "ab\tcdefgh\tij\tklmnopqrs\ttu\tvvwx\tyz" +print(a) +print(a.expandtabs()) +print(a.expandtabs(tabsize=12)) +print(a.expandtabs(tabsize=14)) +print(b.expandtabs(tabsize=14)) +print(a.rstrip("z")) + + +# this is extracted from intro Python 20116a added examples for session 5 +def print_me( nums ): + formatter = "the first %d numbers are: " + ", ".join( ["%i"] * len(nums) ) + print ("formatter: ", formatter) + print (formatter%(( len(nums), ) + nums)) + +print_me( (2,3,4,5,6) ) + +#this did not work either - from format_test.py in session 04 examples +#or all on one line +#def print_msg(t): + # print ("the first %i numbers are: " + ", ".join(["%i"] * len(t)) ) % ((len(t),) + t) + +#print_msg((56,67,34,23)) + +tpl1 = (3,4,5,6,7,8,9,1) +playformat = "i went to the store %d times per week and %d every day: " + " , ".join(["%i"]*len(tpl1)) +print("playformat:", playformat) +print(playformat%((len(tpl1),(len(tpl1)/2),)+ tpl1)) + +list1 = ["hi", "iwent", "to", "the" ] +a= "this is a pen: " +b= "this is not a .." +print("a.join(b) looks like this: ", a.join(b)) +print("this is a join: ", "*".join(list1)) +print (" ".join(list1)) \ No newline at end of file diff --git a/students/Boundb3/Session02 b/students/Boundb3/Session02 new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/students/Boundb3/Session02 @@ -0,0 +1 @@ + diff --git a/students/Boundb3/Session05/Lab_keyword_arguements_S06.py b/students/Boundb3/Session05/Lab_keyword_arguements_S06.py new file mode 100644 index 0000000..7997192 --- /dev/null +++ b/students/Boundb3/Session05/Lab_keyword_arguements_S06.py @@ -0,0 +1,55 @@ +# 2-24-2016 +#session06 keyword arguments lab + +#1: write a function that 4 operational parameters with defaults + +def pic_color(**kwargs): #b3 notes later: I think you could also input defined arguements in here too, but not sure + print("fore color is {fore_color} and back color is always {back_color}. The link is {link}, but if you used it, it is {visited_color}.".format(**d)) + + +d={"fore_color" : "gold", "back_color" : "silver", "link" : "orange", "visited_color": "purple"} +#check type +print(type(d)) +#check key and values +for k,v in d.items(): + print (k, v) +#send to function +pic_color() #b3 -important** do not pass in an object (object d) when you call the def: put the object **d in the format string!! + + +''' see new 1b below - you can define when you call the function''' + + +#2a - challenge - use positional (no defaults) and defaults + +def pic_color_positional(*args,**kwargs): + print("fore color is {} and back color is always {}. The link is {link}, but if you used it, it is {visited_color} ".format(*t,**newd)) #defined here + +t= ("black", "white") +newd = {"link" : "green", "visited_color": "skyblue"} + +pic_color_positional() #not defined when called + +#!!!!!!!!!!!!this more likely - defining the arguements when you call the function, not when it is in the function like 2a + +#2b - challenge - use positional (no defaults) and defaults + +def pic_color_positional(*args,**kwargs): + print("fore color is {} and back color is always {}. The link is {link}, but if you used it, it is {visited_color} ".format(*args,**kwargs)) #not defined the data here + +t= ("black", "white") +newd = {"link" : "green", "visited_color": "skyblue"} + +pic_color_positional(*t,**newd) #here defined what data to use when called the function + + +#1b: write a function that 4 operational parameters with defaults + +def pic_color(**kwargs): + print("fore color is {fore_color} and back color is always {back_color}. The link is {link}, but if you used it, it is {visited_color}.".format(**kwargs)) + + +d={"fore_color" : "gold", "back_color" : "silver", "link" : "orange", "visited_color": "purple"} + +#send to function +pic_color(**d) #b3 -important** do not pass in an object (object d) when you call the def: put the object **d in the format string!! \ No newline at end of file diff --git a/students/Boundb3/Session05/Map_lambda_play.py b/students/Boundb3/Session05/Map_lambda_play.py new file mode 100644 index 0000000..97ab13b --- /dev/null +++ b/students/Boundb3/Session05/Map_lambda_play.py @@ -0,0 +1,12 @@ + +z= 3 + +f = lambda x, y : (x+y)*z +print(f(2,3)) + + +fl = [lambda x,y: x*y, lambda x,y: x-y] +res = fl[1](4,5) +print(res) + + diff --git a/students/Boundb3/Session05/Play_class.py b/students/Boundb3/Session05/Play_class.py new file mode 100644 index 0000000..5684fc5 --- /dev/null +++ b/students/Boundb3/Session05/Play_class.py @@ -0,0 +1,45 @@ +import math + +class Circle: + color = "red" + + + def __init__(self,diameter): + self.diameter = diameter + self.area = self.get_area(diameter) + + def grow(self,factor=2): + self.diameter = self.diameter * factor + return self.diameter + + def get_area(self,diameter): + self.area = math.pi *(diameter/2)**2 + return self.area + +class Point: + color = "red" + size = 4 + + def __init__(self,x,y): + self.x = x + self.y = y + + def get_color(self): + return self.color + + +#p1 = Point (3,4) +#print (p1.x, p1.get_color()) + +c1= Circle(4) + +print("diameter: ",c1.diameter) +print("area: ",c1.area) + +print("c1 growth ", c1.grow(5)) +print("c1 new diameter: ", c1.diameter) +#c1=Circle(c1.diameter) +print("area: ,",c1.get_area(c1.diameter)) + +if isinstance(c1,Circle): + print("true {}, is a {}".format(c1,Circle)) \ No newline at end of file diff --git a/students/Boundb3/Session05/Score_flowerpower_s06HW.py b/students/Boundb3/Session05/Score_flowerpower_s06HW.py new file mode 100644 index 0000000..fe5a220 --- /dev/null +++ b/students/Boundb3/Session05/Score_flowerpower_s06HW.py @@ -0,0 +1,70 @@ +""" +start 2-24-16 B3 - alternative exercise to trapazoid + +Goal : Practice passing functions as arguments to other functions +Scenario: +-------- +You are a game designer working on a scoring system. You have several different categories of weapons: +hand weapons, guns, and flower power weapons. In each of these categories of weapon there is a small, a medium and a large weapon. +Your task is to write a scoring function that takes two arguments and returns an integer which represets the score value of the specified size of the specified weapon. + +The first argument to the scoring function is itself a function that represents the cagetory of weapon, +be it a hand weapon, a gun or a weapon of the dreaded flower power variety. + +The second argument to the scoring function is one of three strings: small, medium or large. + +The score for weapons across the various categories follow the fibonacci scale such that acceptance +tests for the scoring function follow the following pattern. + +.. code-block:: python + + def test_scoring(): + assert score(hand_weapon, 'small') == 1 + assert score(hand_weapon, 'medium') == 2 + assert score(hand_weapon, 'large') == 3 + assert score(gun, 'small') == 5 + assert score(gun, 'medium') == 8 + assert score(gun, 'large') == 13 + assert score(flower_power, 'small') == 21 + assert score(flower_power, 'medium') == 34 + assert score(flower_power, 'large') == 55 + + +Your task is to fill out the following functions. + +code-block:: python +#!!!!!! with Rick: change d to SWITCH in title, +2nd: add a default value to the switch dict, so default of zero, and then do something with the zero + + +""" +# b3 notes 2-24-2016 +# see python file test_Score_flowerpower_s06HW.py for the assertions for this file. +# test the assertions via the command line in get bash +# test by typing in: py.test +# note: must be in the same directory - this file, __name__ == main, and the test file w assets, and also the git bash command line folder + +# later try to simplify the code by having the weapon functions return a call to the fibinochi function??? + + +def hand_weapon(weapon_size): + d= {"small": 1, "medium": 2, "large": 3} #using switchdict functionality from session06 notes + score = d.get(weapon_size) + return score + +def gun(weapon_size): + d= {"small": 5, "medium": 8, "large": 13} + score = d.get(weapon_size) + return score + +def flower_power(weapon_size): + d= {"small": 21, "medium": 34, "large": 55} + score = d.get(weapon_size) + return score + + +def score(weapon_type, weapon_size): + print("weapon_type is" , weapon_type(weapon_size)) #for testing assets to see where it failed + score_val = weapon_type(weapon_size) + return score_val + diff --git a/students/Boundb3/Session05/arg_test.py b/students/Boundb3/Session05/arg_test.py new file mode 100644 index 0000000..a0da629 --- /dev/null +++ b/students/Boundb3/Session05/arg_test.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python + +# this is super cool way to get the absolute path to the current file as a string in a list! + +import sys + +print(sys.argv) diff --git a/students/Boundb3/Session05/arguements.py b/students/Boundb3/Session05/arguements.py new file mode 100644 index 0000000..4ff0362 --- /dev/null +++ b/students/Boundb3/Session05/arguements.py @@ -0,0 +1,46 @@ +""" +from class notes session 6: + +Function arguments in variables +function arguments are really just + +a tuple (positional arguments) +a dict (keyword arguments) +def f(x, y, w=0, h=0): + print("position: {}, {} -- shape: {}, {}".format(x, y, w, h)) + +position = (3,4) +size = {'h': 10, 'w': 20} + +!!!!!!!!!!!!!!!!!!!! notice the * and ** below : one * for tuple items, and ** for values from a dictionary !!!!!!! + +>>> f(*position, **size) +position: 3, 4 -- shape: 20, 10 +Function parameters in variables +You can also pull the parameters out in the function as a tuple and a dict: + +def f(*args, **kwargs): + print("the positional arguments are:", args) + print("the keyword arguments are:", kwargs) + +In [389]: f(2, 3, this=5, that=7) +the positional arguments are: (2, 3) +the keyword arguments are: {'this': 5, 'that': 7} +This can be very powerful... + +Passing a dict to str.format() +Now that you know that keyword args are really a dict, you know how this nifty trick works: + +The string format() method takes keyword arguments: + +In [24]: "My name is {first} {last}".format(last="Barker", first="Chris") +Out[24]: 'My name is Chris Barker' +Build a dict of the keys and values: + +In [25]: d = {"last":"Barker", "first":"Chris"} +And pass to format()``with ``** + +In [26]: "My name is {first} {last}".format(**d) +Out[26]: 'My name is Chris Barker' + +""" diff --git a/students/Boundb3/Session05/cigar_party.py b/students/Boundb3/Session05/cigar_party.py new file mode 100644 index 0000000..4ef83bf --- /dev/null +++ b/students/Boundb3/Session05/cigar_party.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. +Return True if the party with the given values is successful, +or False otherwise. +""" + +# b3 - ok - written this function to pass the tests. +# run (from the command line) the command "py.test" in the directory that the file and test file reside in +# this will print out the results in the command line window when you have an error - and then you can return to the code to fix / de-bug the program + +print ("this is a test") +def cigar_party(cigars, is_weekend): + print(cigars, "and ", is_weekend, "made it to the def cigar_party function") + if 40 <= cigars <= 60 and is_weekend == False: #b3 - I had these in "quotes" like "False" and the assert tests failed, so I was able to know to keep working at it to fix it. Note to self: Assert testing works to find errors!! + return True + elif cigars >= 40 and is_weekend == True: #b3 - I had mistakenly put quotes here too + return True + else: + return False + +''' +cigar = 40 +is_weekend = False + +x = cigar_party(cigar, is_weekend) +print(x) +''' \ No newline at end of file diff --git a/students/Boundb3/Session05/codingbat.py b/students/Boundb3/Session05/codingbat.py new file mode 100644 index 0000000..96834b9 --- /dev/null +++ b/students/Boundb3/Session05/codingbat.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +#copy from example file - I have not done anything here. Not sure what to do + +""" +Examples from: http://codingbat.com + +Put here so we can write unit tests for them ourselves +""" + +# Python > Warmup-1 > sleep_in + + +def sleep_in(weekday, vacation): + if vacation is True: + return True + elif weekday is False: + return True + else: + return False + + +def sumdouble(a, b): + if a == b: + return (a + b) * 2 + else: + return(a + b) + diff --git a/students/Boundb3/Session05/comprehension_play.py b/students/Boundb3/Session05/comprehension_play.py new file mode 100644 index 0000000..f45b6f7 --- /dev/null +++ b/students/Boundb3/Session05/comprehension_play.py @@ -0,0 +1,13 @@ +#list: +y = [x*3 for x in [3,6,9,12]] +print(y) + +#set + +y = {x**2 for x in [3,-3,6,9,12]} +print(y) + +# dictionary + +y = {x: "this_%x is : "%x*3 for x in [3,6,9,12]} +print(y) diff --git a/students/Boundb3/Session05/file_to_copy_any_kind_process.xlsx b/students/Boundb3/Session05/file_to_copy_any_kind_process.xlsx new file mode 100644 index 0000000..b05a9c3 Binary files /dev/null and b/students/Boundb3/Session05/file_to_copy_any_kind_process.xlsx differ diff --git a/students/Boundb3/Session05/file_writing_Session5.py b/students/Boundb3/Session05/file_writing_Session5.py new file mode 100644 index 0000000..4d54fa4 --- /dev/null +++ b/students/Boundb3/Session05/file_writing_Session5.py @@ -0,0 +1,78 @@ +# from session 5 notes - play with lesson to get practice with concept + +import io + +with open('output.txt', 'w') as f: + for i in range(10): + f.write("this is line: %i\n"%i) + f.write("\tI am king\n") + +with open("output.txt",mode = "r+") as f: + count = 0 + for i in range(0,5): + readfile = f.readline() + print (readfile) + + #f.seek(2+count) # can make the pointer go where I want and then read line again + #print (f.read()) #reads the whole file + + count += 2 + print("***that was line {:^20} \n". format(i)) + for i in range(0,2): + readfile = f.readline() + print (readfile) + +print("boolean: ", f.closed) + + +import io +f2= io.StringIO() +f2.write("here is a sentence \n and here is another \n another\n another") +f2.seek(5) +f2.read() +stuff = f2.getvalue() +print("stuff is:",stuff) +f2.close() + +# this is not working - this was from the file notes in session 5 +#import os +#a= os.getcwd() +#b= os.chdir(path) +#c= os.path.abspath() +#d = os.path.relpath() +#print(a) + + +import pathlib +pth = pathlib.Path("./") +print("this is pathlib.Path('./'): ",pth) +print("this is pth.is_dir():", pth.is_dir()) +print("pth.absolute(): ", pth.absolute()) +#write a program which prints the full path to all files int he current directory - one per line +for f in pth.iterdir(): + print("this is a file in the directory: ",f) + +#write a program that copies a file from a source to a destination +for name in pth.iterdir(): + name = str(name) + print("this is a file in the directory: ",name) + if name == "file_to_copy_any_kind_process.xlsx": + doc_name = "file_to_copy_any_kind_process.xlsx" + with open(doc_name,"rb") as f: + data_btyes = f.read() + print("data_btyes is:", data_btyes) + with open("newname.xlsx", "wb") as newf: # tried C:\Python_100a\IntroPython2016a\students\Boundb3\Session06\newname.xlsx, but it did not work to this new directory + newf.write(data_btyes) + print("copied file to: " ) # was not able to copy to another directory, but did make a copy of the file + else: + print("not this one:", name) + + + + +try: #This is something else I tried, but it is not working !!! + p = pathlib.Path('.') + list(p.glob('**/*.py')) +except Exception as e: + print(e) + diff --git a/students/Boundb3/Session05/lab_Files_student lang_sess05.py b/students/Boundb3/Session05/lab_Files_student lang_sess05.py new file mode 100644 index 0000000..fe28ab4 --- /dev/null +++ b/students/Boundb3/Session05/lab_Files_student lang_sess05.py @@ -0,0 +1,41 @@ +import pathlib +pth = pathlib.Path("./") +print(pth.absolute()) + +#C:\Python_100a\IntroPython2016a\examples\"students.txt" + +with open('C:\Python_100a\IntroPython2016a\examples\students.txt',mode = "r") as f: + file_content= f.read() + print(file_content) +print(f.closed) + +lang_dict ={} +name_list = [] +count = 0 + +with open ('C:\Python_100a\IntroPython2016a\examples\students.txt',mode = "r") as f: + for row in f.readlines(): + row = row.strip() + name,lang = row.split(":") + name_list.append(name) # not really needed, but seperate list of names - and we know there is only 1 name per row + languages_list = lang.split(",") #used to split the side of the row which are languages (1 of many), and add them to a variable - which happens to store them as a list + for item in languages_list: #cycle through the rows' language, and count the language per person per row and add to a dictionary + if item not in lang_dict: + lang_dict[item] = 1 + else: + lang_dict[item] = lang_dict[item] + 1 + + + count += 1 + print ("{:02d}: name is {} and lang is {}".format(count,name,lang)) +print("there are {} languages in all: {}".format (len(lang_dict),lang_dict)) +print("there are {} people in the class".format(len(name_list))) +print("most popular languages (in order are: ", sorted(lang_dict,key=lang_dict.get, reverse = True)) +for k, v in lang_dict.items(): + print("lang ={:<15}, count = {:>3}".format(k,v)) + +#try counter objects +import os,argparse +#cnt = Counter() # not working - counter() method not recognized - what lib do i need to import. 8.3.2: see https://docs.python.org/3.5/library/collections.html#collections.namedtuple + + diff --git a/students/Boundb3/Session05/map_play.py b/students/Boundb3/Session05/map_play.py new file mode 100644 index 0000000..04fe163 --- /dev/null +++ b/students/Boundb3/Session05/map_play.py @@ -0,0 +1,19 @@ + +#map play + +l = [5,10,15,20] + +fx = lambda x: 2*x + +res = map(fx,l) + +for x in res: + print(x) + +d={"spring":("happy yellow", "bright pink")} + # "midnight" : ("dark blue", "shadow black"), + #"neon" : ("electric orange", "blinding silver")} + +#fx2 = lambda args: "{} and {} make good colors".format(enumerate(args)) +fx2 = lambda args: "{} and {} make good colors".format(args["spring"][0],args["spring"][1]) +print(fx2(d)) diff --git a/students/Boundb3/Session05/newname.xlsx b/students/Boundb3/Session05/newname.xlsx new file mode 100644 index 0000000..b05a9c3 Binary files /dev/null and b/students/Boundb3/Session05/newname.xlsx differ diff --git a/students/Boundb3/Session05/output.txt b/students/Boundb3/Session05/output.txt new file mode 100644 index 0000000..1512681 --- /dev/null +++ b/students/Boundb3/Session05/output.txt @@ -0,0 +1,20 @@ +this is line: 0 + I am king +this is line: 1 + I am king +this is line: 2 + I am king +this is line: 3 + I am king +this is line: 4 + I am king +this is line: 5 + I am king +this is line: 6 + I am king +this is line: 7 + I am king +this is line: 8 + I am king +this is line: 9 + I am king diff --git a/students/Boundb3/Session05/play_functool.py b/students/Boundb3/Session05/play_functool.py new file mode 100644 index 0000000..3eaa261 --- /dev/null +++ b/students/Boundb3/Session05/play_functool.py @@ -0,0 +1,13 @@ + +import functools + +def greet(greeting,target): + return print("{}! {}".format(greeting,target)) + + + +greet = functools.partial(greet,"Hola") +greet("bob") +greet("steve") + + diff --git a/students/Boundb3/Session05/play_s06.py b/students/Boundb3/Session05/play_s06.py new file mode 100644 index 0000000..9a2e6ee --- /dev/null +++ b/students/Boundb3/Session05/play_s06.py @@ -0,0 +1,49 @@ +# an example for a "switch dict" +#You can do a dispatch table by putting functions as the value. see below + +arg_dict = {0:"zero", 1:"one", 2: "two"} +x = arg_dict.get(1, "nothing") +y = arg_dict.get(5, "nothing") +print("x is {} and y is {}".format(x,y)) + + +def print_me(): + print("made it to printme") + print("me") + +def print_that(): + print("made it to printthat") + print("that") + return "howdy z" + +def print_this(): + print("made it to printthis") + print("this") + +arg_dict2 = {0: print_me, 1:"One", 2: print_that} + +#this does not work, as all called functions execute if no "" and i only get a print string otherwise +z = arg_dict2.get(2, "nothing")() #!!!!! oh - need the extra object call parathesis in the get call -- *** here*** +print("z is" , z) + + +arg_dict2.get(2, "nothing")() + +''' +What would this be like if you used functions instead? Think of the possibilities. + +In [11]: def my_zero_func(): +return "I'm zero" + +In [12]: def my_one_func(): + return "I'm one" + +In [13]: switch_func_dict = { + 0: my_zero_func, + 1: my_one_func, +} + +In [14]: switch_func_dict.get(0)()#b <---look at this set of paranthesis!!!!! +Out[14]: "I'm zero" + +''' \ No newline at end of file diff --git a/students/Boundb3/Session05/switchdict_function_call_s06.py b/students/Boundb3/Session05/switchdict_function_call_s06.py new file mode 100644 index 0000000..b0e96b9 --- /dev/null +++ b/students/Boundb3/Session05/switchdict_function_call_s06.py @@ -0,0 +1,49 @@ +# an example for a "switch dict" +#You can do a dispatch table by putting functions as the value. see below + +arg_dict = {0:"zero", 1:"one", 2: "two"} +x = arg_dict.get(1, "nothing") +y = arg_dict.get(5, "nothing") +print("x is {} and y is {}".format(x,y)) + + +def print_me(): + print("made it to printme") + print("me") + +def print_that(): + print("made it to printthat") + print("that") + return "howdy z" + +def print_this(): + print("made it to printthis") + print("this") + +arg_dict2 = {0: print_me, 1:"One", 2: print_that} + +#this finally worked +z = arg_dict2.get(2, "nothing")() #<-- !!!!! oh - need the extra object call parathesis in the get call -- *** here*** +print("z is" , z) + + +arg_dict2.get(2, "nothing")() + +''' +What would this be like if you used functions instead? Think of the possibilities. + +In [11]: def my_zero_func(): +return "I'm zero" + +In [12]: def my_one_func(): + return "I'm one" + +In [13]: switch_func_dict = { + 0: my_zero_func, + 1: my_one_func, +} + +In [14]: switch_func_dict.get(0)()#b <---look at this set of paranthesis!!!!! +Out[14]: "I'm zero" + +''' diff --git a/students/Boundb3/Session05/test_Score_flowerpower_so6HW.py b/students/Boundb3/Session05/test_Score_flowerpower_so6HW.py new file mode 100644 index 0000000..3580e32 --- /dev/null +++ b/students/Boundb3/Session05/test_Score_flowerpower_so6HW.py @@ -0,0 +1,28 @@ +''' +This is the test file for HW Score_flowerpower_s06HW + +start 2-24-16 B3 - alternative exercise to trapazoid + +Goal : Practice passing functions as arguments to other functions +''' + + +import pytest # I guess this is not necessary + +from Score_flowerpower_s06HW import score +from Score_flowerpower_s06HW import hand_weapon +from Score_flowerpower_s06HW import gun +from Score_flowerpower_s06HW import flower_power + +def test_scoring(): + assert score(hand_weapon, 'small') == 1 + assert score(hand_weapon, 'medium') == 2 + assert score(hand_weapon, 'large') == 3 +def test_scoring2(): + assert score(gun, 'small') == 5 + assert score(gun, 'medium') == 8 + assert score(gun, 'large') == 13 +def test_scoring3(): + assert score(flower_power, 'small') == 21 + assert score(flower_power, 'medium') == 34 + assert score(flower_power, 'large') == 55 diff --git a/students/Boundb3/Session05/test_Session05.py b/students/Boundb3/Session05/test_Session05.py new file mode 100644 index 0000000..d3cb606 --- /dev/null +++ b/students/Boundb3/Session05/test_Session05.py @@ -0,0 +1,4 @@ + +print("this is a test") + + diff --git a/students/Boundb3/Session05/test_cigar_party.py b/students/Boundb3/Session05/test_cigar_party.py new file mode 100644 index 0000000..16afc42 --- /dev/null +++ b/students/Boundb3/Session05/test_cigar_party.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. +Return True if the party with the given values is successful, +or False otherwise. +""" + + +# you can change this import to test different versions +from cigar_party import cigar_party +# from cigar_party import cigar_party2 as cigar_party +# from cigar_party import cigar_party3 as cigar_party + + + +def test_1(): + assert cigar_party(30, False) is False + +print("\tevaluate test # 1: ", cigar_party(30, False), "<--should be False") + +def test_2(): + assert cigar_party(50, False) is True +print("\tevaluate test # 2: ", cigar_party(50, False), "<--should be T") + +def test_3(): + assert cigar_party(70, True) is True +print("\tevaluate test # 3: ", cigar_party(70, True), "<--should be T") + +def test_4(): + assert cigar_party(30, True) is False +print("\tevaluate test # 4: ", cigar_party(30, True), "<--should be F") + +def test_5(): + assert cigar_party(50, True) is True +print("\tevaluate test # 5: ", cigar_party(50, True), "<--should be T") + +def test_6(): + assert cigar_party(60, False) is True +print("\tevaluate test # 6: ", cigar_party(60, False), "<--should be T") + +def test_7(): + assert cigar_party(61, False) is False +print("\tevaluate test # 7: ", cigar_party(61, False), "<--should be F") + +def test_8(): + assert cigar_party(40, False) is True +print("\tevaluate test # 8: ", cigar_party(40, False), "<--should be T") + +def test_9(): + assert cigar_party(39, False) is False +print("\tevaluate test # 9: ", cigar_party(39, False), "<--should be F") + +def test_10(): + assert cigar_party(40, True) is True +print("\tevaluate test # 10: ", cigar_party(40, True), "<--should be T") + +def test_11(): + assert cigar_party(39, True) is False + +print("\tevaluate test # 11: ", cigar_party(39, True)) # this results in False - which is correct - from the file +#however, when I look at the py.test results in the command line, I get None = False and the test fails. Why? \ No newline at end of file diff --git a/students/Boundb3/Session05/test_codingbat.py b/students/Boundb3/Session05/test_codingbat.py new file mode 100644 index 0000000..c3a859d --- /dev/null +++ b/students/Boundb3/Session05/test_codingbat.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +""" +test file for codingbat module + +This version can be run with nose or py.test +""" + +#be sure to inpurt the modules you want to test by the file name and the module +from codingbat import sleep_in +from codingbat import sumdouble + + +def test_false_false(): + assert sleep_in(False, False) is True + + +def test_true_false(): + assert not (sleep_in(True, False)) is True + + +def test_false_true(): + assert sleep_in(False, True) is True + + +def test_true_true(): + assert sleep_in(True, True) is True + + +def test_sumdouble1(): + assert sumdouble(1, 2) == 3 + + +def test_sumdouble2(): + assert sumdouble(3, 2) == 5 + + +def test_sumdouble3(): + assert sumdouble(2, 2) == 8 diff --git a/students/Boundb3/Session05/test_pytest_parameter.py b/students/Boundb3/Session05/test_pytest_parameter.py new file mode 100644 index 0000000..9b01ee6 --- /dev/null +++ b/students/Boundb3/Session05/test_pytest_parameter.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +""" +pytest example of a parameterized test + +NOTE: there is a failure in here! can you fix it? #b3 - i think this should be no space between thisthat result: +#"this that" to change to "thisthat" + +""" +import pytest + + +# a (really simple) function to test +def add(a, b): + """ + returns the sum of a and b + """ + return a + b + +# now some test data: + +test_data = [((2, 3), 5), + ((-3, 2), -1), + ((2, 0.5), 2.5), + (("this", "that"), "thisthat"), + (([1, 2, 3], [6, 7, 8]), [1, 2, 3, 6, 7, 8]), + ] + + +@pytest.mark.parametrize(("input", "result"), test_data) +def test_add(input, result): + assert add(*input) == result diff --git a/students/Boundb3/Session05/test_random_pytest.py b/students/Boundb3/Session05/test_random_pytest.py new file mode 100644 index 0000000..2404eae --- /dev/null +++ b/students/Boundb3/Session05/test_random_pytest.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +""" +port of the random unit tests from the python docs to py.test +""" + +import random +import pytest #B3 - be sure to import the pytest module and the random module + + + +seq = list(range(10)) + + +def test_shuffle(): + # make sure the shuffled sequence does not lose any elements + random.shuffle(seq) + seq.sort() # this will amke it fail, so we can see output - b3 - added this line back to pass the test + print("seq:", seq) # only see output if it fails - in the test mode, but if ran the def with a main, then would likely see the print - i think b3 + assert seq == list(range(10)) + + +def test_shuffle_immutable(): + pytest.raises(TypeError, random.shuffle, (1, 2, 3)) + + +def test_choice(): + element = random.choice(seq) + assert (element in seq) + + +def test_sample(): + for element in random.sample(seq, 5): + assert element in seq + + +def test_sample_too_large(): + with pytest.raises(ValueError): + random.sample(seq, 20) diff --git a/students/Boundb3/Session05/test_random_unitest.py b/students/Boundb3/Session05/test_random_unitest.py new file mode 100644 index 0000000..f825be5 --- /dev/null +++ b/students/Boundb3/Session05/test_random_unitest.py @@ -0,0 +1,30 @@ +import random +import unittest + + +class TestSequenceFunctions(unittest.TestCase): + + def setUp(self): + self.seq = list(range(10)) + + def test_shuffle(self): + # make sure the shuffled sequence does not lose any elements + random.shuffle(self.seq) + self.seq.sort() + self.assertEqual(self.seq, list(range(10))) + + # should raise an exception for an immutable sequence + self.assertRaises(TypeError, random.shuffle, (1, 2, 3)) + + def test_choice(self): + element = random.choice(self.seq) + self.assertTrue(element in self.seq) + + def test_sample(self): + with self.assertRaises(ValueError): + random.sample(self.seq, 20) + for element in random.sample(self.seq, 5): + self.assertTrue(element in self.seq) + +if __name__ == '__main__': + unittest.main() diff --git a/students/Boundb3/Session05/test_s08.py b/students/Boundb3/Session05/test_s08.py new file mode 100644 index 0000000..54dbdaf --- /dev/null +++ b/students/Boundb3/Session05/test_s08.py @@ -0,0 +1,89 @@ +#session 08 in class - 2/25/2016 + +# working on OO and class objects + +class A: + def hello(self): + print("Hi") + +class B(A): + def hello(self): + super().hello() #calls the super + print("there") + +b = B() +b.hello() + +# ANIMAL KINGDOM + +class Animal(object): # object is a master class + + def __init__(self): + pass + +class Mammal(Animal): + warm_blood = True # put here because it is a total class attribute + gestation_in_a_womb = True + def __init__(self): + pass + + +class Reptile(Animal): + warm_blood = False + gestation_in_a_womb = False + def __init__(self): + pass + +class Bird(Reptile): + warm_blood = True #over-wrote the super class attribute in Reptile: refer to that thing and put in a new definition in the child + + def __init__(self): + pass + +#creating an instance # need to be before it is called +my_mammal = Mammal() + +my_reptile = Reptile() + + +class Snake(Reptile): + + def __init__(self): + pass + + +class Dog(Mammal): + #chases cats is not a global class feature + + def __init__(self,chases_cats=True): + self.chases_cats = chases_cats # would go here - b/c true for most dogs, but not all, so + # this can be over-written (not a full class attribute) + pass + + def make_me_cold_blooded(self): + self.warm_blood = False + pass + + +class Cat(Mammal): + + def __init__(self, hates_dogs = True): + self.hates_dogs = hates_dogs # an individual individual object tracking characterisit , not a total cat thing + pass + + +print( my_mammal.warm_blood) +print( my_reptile.warm_blood) + +def main(): + pass + +if __name__ =='__main__': #usually see this in bottom of files + main() + +my_dog = Dog(chases_cats=False) +my_cat = Cat() + +print(dir(my_dog) + + diff --git a/students/Boundb3/Session06/Trap_try.py b/students/Boundb3/Session06/Trap_try.py new file mode 100644 index 0000000..aabd6a9 --- /dev/null +++ b/students/Boundb3/Session06/Trap_try.py @@ -0,0 +1,17 @@ + +def create_range(a,b,n): + ''' + a = start point + b = end point + n = number of intervals to create + ''' + # create list of x values from a to b + delta = float(b - a)/n + print("delta is:", delta, "n:", n) + return [a+ i * delta for i in range(n+1)] + +x = create_range(1,10,4) +print (x) + +my_vals2see = [1,2,3,4,5,6] +print(my_vals2see[1:-1]) \ No newline at end of file diff --git a/students/Boundb3/Session07/.ipynb_checkpoints/Session_08_with_classes-checkpoint.ipynb b/students/Boundb3/Session07/.ipynb_checkpoints/Session_08_with_classes-checkpoint.ipynb new file mode 100644 index 0000000..6e1e98f --- /dev/null +++ b/students/Boundb3/Session07/.ipynb_checkpoints/Session_08_with_classes-checkpoint.ipynb @@ -0,0 +1,154 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Session_08 - 2/25/2016" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# classes - OO" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class A:\n", + " def hello(self):\n", + " print(\"Hi\")\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class B(A):\n", + " def hello(self):\n", + " super().hello() #delegated work out to the parent\n", + " print(\"there\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "b = B()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hi\n", + "there\n" + ] + } + ], + "source": [ + "b.hello() # now it gets the super and its own there" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'hello']" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(A)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/Boundb3/Session07/Session_08_with_classes.ipynb b/students/Boundb3/Session07/Session_08_with_classes.ipynb new file mode 100644 index 0000000..6e1e98f --- /dev/null +++ b/students/Boundb3/Session07/Session_08_with_classes.ipynb @@ -0,0 +1,154 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Session_08 - 2/25/2016" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# classes - OO" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class A:\n", + " def hello(self):\n", + " print(\"Hi\")\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class B(A):\n", + " def hello(self):\n", + " super().hello() #delegated work out to the parent\n", + " print(\"there\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "b = B()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hi\n", + "there\n" + ] + } + ], + "source": [ + "b.hello() # now it gets the super and its own there" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'hello']" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(A)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.0" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/Boundb3/Session07/html_project/html_render.py b/students/Boundb3/Session07/html_project/html_render.py new file mode 100644 index 0000000..e051c53 --- /dev/null +++ b/students/Boundb3/Session07/html_project/html_render.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python + +""" +B3 version copy - start + +Python class example. + +""" + +# The start of it all: +# Fill it all in here. + +class Element(object): + #class attributes + tag = "element tag" + indent = " " + print("hi") + #content = [] + + + def __init__(self, content=None, **attributes): ###!!!could i have added the link attribute here?? + #store content + self.content = [] + + + # add an attributes dictionary + self.attributes = attributes + + #check for content + if content is not None: + self.content.append(content) + print("there was content in init. init appended content = {} to self = {} ".format(content,self.tag)) + print("\t\tcompleted init call for:", self.tag, "\n" ) + + def ToString(self): + return self.tag + #to over write the default __str__ + def __str__(self): + return self.ToString() + + + def append(self, new_content): + #add new string content to content list + print("\t\tcalling append function \n appending: appending {} to {} ".format(new_content, self.tag )) + if new_content is not "": + self.content.append(new_content) + + #new render tag method + def render_tag(self, current_ind): + # tag and then content for each class + attrs = "".join([' {} ="{}"'.format(key,val) for key, val in self.attributes.items()]) + #print("this is self.attributes from render_tag: ", self.attributes) + #indentation + tag + content + tag_str = "{}<{}{}>".format(current_ind, self.__str__(), attrs) + #print("from render_tag: current_ind is '{}' and tag strg is '{}'".format(current_ind, tag_str)) + return tag_str + + def render(self, file_out, current_ind= " default indent"): + print("entering rendering func ") + #print("this is current ind: ", current_ind) + #print("this is self.tag '{}' inside render func and this is self.__str__ '{}' : ".format(self.tag, self.__str__())) + + #now render will call the render tag menthod - instead of just a string defined tag + file_out.write(self.render_tag(current_ind)) # the problem here is that the current_ind attribute is carrying text of: html, or htmlbody inside the attribute!!! + + print("just finished call to render_tag") + file_out.write("\n") + + for con in self.content: + try: + #render it + print("\t--> con is: " , con) + file_out.write(current_ind + self.indent + con+"\n") #was: stuff_str.render(file_out) + except TypeError as e: + print("hit a snag: ", e, "con is: ", con) + con.render(file_out, current_ind + self.indent) # was: .write(str(stuff_str)) ### watch it if it is self.tag + + #write out closing tag + #was: + #stop at the closing html tag + #end_tag = "".format(self.tag) + #add that tag to the end of the file object + #file_out.write(end_tag) + file_out.write("{}\n".format(current_ind, self.tag)) + + + +class Body (Element): + tag = "body" + print("subclass tag = : ",tag) + pass + +class P (Element): + #print(super.tag) Why does this not work? (to print out the super's tag) + tag = "p" + print("subclass tag = : ",tag) + pass + +class Html (Element): + tag = "html" + print("subclass tag = : ",tag) + pass + +class Head (Element): + tag = "head" + + pass + +class OneLineTag (Element): + def render(self, file_out, current_ind= " default indent"): + print("entering OneLineTag rendering func ") + + #now render will call the render tag menthod + file_out.write(self.render_tag(current_ind)) + + #print("just finished call to render_tag") + #file_out.write("\n") # B3 - this is not needed in this render subclass + + for con in self.content: + try: + #render it + print("\t--> con is: " , con) + file_out.write(current_ind + self.indent + con ) #b-3 removed +"\n" from the write instructions to stay on the same line + except TypeError as e: + print("hit a snag: ", e, "con is: ", con) + con.render(file_out, current_ind + self.indent) # was: .write(str(stuff_str)) ### watch it if it is self.tag + + #write out closing tag + file_out.write("{}\n".format(current_ind, self.tag)) + +class Title (OneLineTag): + tag = "title" + pass + +class SelfClosingTag (Element): + def render(self, file_out, current_ind= " default indent"): + print("entering SelfClosingTag rendering func ") + #write out closing tag + file_out.write("{}<{} /> {}\n".format(current_ind, self.tag, self.attributes)) + +''' +#comment out this section + #now render will call the render tag menthod + #file_out.write(self.render_tag(current_ind)) + + #print("just finished call to render_tag") + #file_out.write("\n") # B3 - this is not needed in this render subclass + + for con in self.content: + try: + #render it + print("\t--> con is: " , con) + file_out.write(current_ind + self.indent + con) #b-3 removed +"\n" from the write instructions to stay on the same line + except TypeError as e: + print("hit a snag: ", e, "con is: ", con) + con.render(file_out, current_ind + self.indent) # was: .write(str(stuff_str)) ### watch it if it is self.tag +''' + +class Hr (SelfClosingTag): + tag = "hr" + pass + +class Br (SelfClosingTag): + tag = "br" + pass + +class A (Element): + tag = "a" + + + + def __init__(self, content=None, link="link",**attributes): + self.attributes = "href=" + contentstr = "href="https://github.com/+'"'+content+'">' + link + super().__init__(contentstr,**attributes) #!!! not quite right - needs the format: link + + #self.link = link + pass + +class Ul (Element): + tag = "ul" + +class Li (Element): + tag = "li" + +class H (OneLineTag): + tag = "header" + + def __init__(self,header,content = None,**attributes): + switchdict = {1:"h1",2:"h2",3:"h3"} + + self.header = switchdict[int(header)] + self.tag = self.header + super().__init__(content,**attributes) diff --git a/students/Boundb3/Session07/html_project/run_html_render.py b/students/Boundb3/Session07/html_project/run_html_render.py new file mode 100644 index 0000000..0eae206 --- /dev/null +++ b/students/Boundb3/Session07/html_project/run_html_render.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python + +""" +B3 copy +a simple script can run and test your html rendering classes. + +Uncomment the steps as you add to your rendering. + +""" + +from io import StringIO + +# importing the html_rendering code with a short name for easy typing. +import html_render as hr +# reloading in case you are running this in iPython +# -- we want to make sure the latest version is used +import importlib +importlib.reload(hr) + + +# writing the file out: +def render_page(page, filename): + """ + render the tree of elements + + This uses StringIO to render to memory, then dump to console and + write to file -- very handy! + """ + + f = StringIO() #b3 - here f is the string going into **memory (object f) + page.render(f, " ") # b3 - here is where we take object: "page" and execute func render. the f attribute is the output file in func render = so f is a memory locatoin (defined by StringIO) and writes to object: f in memory + + f.seek(0) #b3 - go back to start of f + + print("\nthis is f.read from func render_page:\n ",f.read()) #b3 - here it dumps to **console by reading f (from memory) + + f.seek(0) + open(filename, 'w').write(f.read()) #here is where it writes to a file - object f is read from memory and writen to the output file name.html given above + + +# Step 1 +######### +''' +page = hr.Element() #B3 - this starts an object using the Element class in file: html_render = page becomes a member of class Element + +page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text. \n") + +page.append("\nAnd here is another piece of text -- you should be able to add any number - like 423\n") + +print("b3test page: ", type(page), "page dot append is: ", page.append, "\n\n") + + +render_page(page, "test_html_output1.html") # B3- this is a function in this file: see above. it says print object: "page" to file: "in the quotes" +''' + +## Step 2 +# ########## +''' +page = hr.Html() + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) + +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output2.html") +''' +# # Step 3 +# ########## +''' +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output3.html") +''' +# # Step 4 +# ########## +''' +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +page.append(body) + +render_page(page, "test_html_output4.html") +''' + +# # Step 5 +# ######### +''' +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +page.append(body) + +render_page(page, "test_html_output5.html") +''' +# # Step 6 +# ######### + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +body.append("And this is a ") +body.append( hr.A("http://google.com/", "link") ) +body.append("to google") + +page.append(body) + +render_page(page, "test_html_output6.html") + +# # Step 7 +# ######### +''' +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append( hr.H(2, "PythonClass - Class 6 example") ) + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +list = hr.Ul(id="TheList", style="line-height:200%") + +list.append( hr.Li("The first item in a list") ) +list.append( hr.Li("This is the second item", style="color: red") ) + +item = hr.Li() +item.append("And this is a ") +item.append( hr.A("http://google.com/", "link") ) +item.append("to google") + +list.append(item) + +body.append(list) + +page.append(body) + +render_page(page, "test_html_output7.html") +''' +# # Step 8 +# ######## + +# page = hr.Html() + + +# head = hr.Head() +# head.append( hr.Meta(charset="UTF-8") ) +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append( hr.H(2, "PythonClass - Class 6 example") ) + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# list = hr.Ul(id="TheList", style="line-height:200%") + +# list.append( hr.Li("The first item in a list") ) +# list.append( hr.Li("This is the second item", style="color: red") ) + +# item = hr.Li() +# item.append("And this is a ") +# item.append( hr.A("http://google.com/", "link") ) +# item.append("to google") + +# list.append(item) + +# body.append(list) + +# page.append(body) + +# render_page(page, "test_html_output8.html") diff --git a/students/Boundb3/Session07/html_project/test_html_output1.html b/students/Boundb3/Session07/html_project/test_html_output1.html new file mode 100644 index 0000000..bc6fe17 --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output1.html @@ -0,0 +1,5 @@ + +Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text. + +And here is another piece of text -- you should be able to add any number - like 423 + \ No newline at end of file diff --git a/students/Boundb3/Session07/html_project/test_html_output2.html b/students/Boundb3/Session07/html_project/test_html_output2.html new file mode 100644 index 0000000..c304baa --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output2.html @@ -0,0 +1,10 @@ + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+

+ And here is another piece of text -- you should be able to add any number +

+ + diff --git a/students/Boundb3/Session07/html_project/test_html_output3.html b/students/Boundb3/Session07/html_project/test_html_output3.html new file mode 100644 index 0000000..45bdb05 --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output3.html @@ -0,0 +1,13 @@ + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+

+ And here is another piece of text -- you should be able to add any number +

+ + diff --git a/students/Boundb3/Session07/html_project/test_html_output4.html b/students/Boundb3/Session07/html_project/test_html_output4.html new file mode 100644 index 0000000..ed0313a --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output4.html @@ -0,0 +1,10 @@ + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+ + diff --git a/students/Boundb3/Session07/html_project/test_html_output5.html b/students/Boundb3/Session07/html_project/test_html_output5.html new file mode 100644 index 0000000..a19f7dc --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output5.html @@ -0,0 +1,11 @@ + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+
{} + + diff --git a/students/Boundb3/Session07/html_project/test_html_output6.html b/students/Boundb3/Session07/html_project/test_html_output6.html new file mode 100644 index 0000000..2ef6bd2 --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output6.html @@ -0,0 +1,16 @@ + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+
{} + And this is a + + href="http://google.com/">link + + to google + + diff --git a/students/Boundb3/Session07/html_project/test_html_output7.html b/students/Boundb3/Session07/html_project/test_html_output7.html new file mode 100644 index 0000000..fe66b13 --- /dev/null +++ b/students/Boundb3/Session07/html_project/test_html_output7.html @@ -0,0 +1,27 @@ + + + PythonClass = Revision 1087: + + +

PythonClass - Class 6 example

+

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+
{} + + + diff --git a/students/Boundb3/Session09/Sess_09_class_play.py b/students/Boundb3/Session09/Sess_09_class_play.py new file mode 100644 index 0000000..05fb743 --- /dev/null +++ b/students/Boundb3/Session09/Sess_09_class_play.py @@ -0,0 +1 @@ +# preperation for following along in class - session 9 diff --git a/students/Boundb3/Textfiles/Mail_List_status_W4.txt b/students/Boundb3/Textfiles/Mail_List_status_W4.txt new file mode 100644 index 0000000..bbedacd --- /dev/null +++ b/students/Boundb3/Textfiles/Mail_List_status_W4.txt @@ -0,0 +1,6 @@ +("Sally", "Wood", "Ms."): [50.00, 100.45, 75.25] +("Jim", "Nasium", "Mr."): [150.00, 10.00] +("Bill", "Fold", "Mr."): [45.00] +("Alice", "Wonder", "Mrs."): [10.00, 10.00, 25.00] +("Chuck", "Wheels", "Mr."): [25.00, 25,25 ] +("no", "one", "yet"): [] \ No newline at end of file diff --git a/students/Boundb3/Textfiles/students.txt b/students/Boundb3/Textfiles/students.txt new file mode 100644 index 0000000..fe6b413 --- /dev/null +++ b/students/Boundb3/Textfiles/students.txt @@ -0,0 +1,24 @@ +Bindhu, Krishna: +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: \ No newline at end of file diff --git a/students/Boundb3/practicetestfile b/students/Boundb3/practicetestfile new file mode 100644 index 0000000..f299898 --- /dev/null +++ b/students/Boundb3/practicetestfile @@ -0,0 +1,2 @@ +try this text +I like to try this text again This is last write for the day \ No newline at end of file diff --git a/students/Boundb3/students.txt b/students/Boundb3/students.txt new file mode 100644 index 0000000..4498763 --- /dev/null +++ b/students/Boundb3/students.txt @@ -0,0 +1,25 @@ +Bindhu, Krishna: English, C, C++, Verilog +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembly +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: Python, JAVA, VBA, SQL, English, Chinese +Riehle, Rick: English, Python, Clojure, C, C++, SQL, Fortran, Pascal, Perl, R, Octave, Bash, Basic, Assembly \ No newline at end of file diff --git a/students/BryanGlogowski/README.rst b/students/BryanGlogowski/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session01/README.rst b/students/BryanGlogowski/session01/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session02/README.rst b/students/BryanGlogowski/session02/README.rst new file mode 100644 index 0000000..107717a --- /dev/null +++ b/students/BryanGlogowski/session02/README.rst @@ -0,0 +1 @@ +# Homework for the 2nd week diff --git a/students/BryanGlogowski/session02/fizzbuzz.py b/students/BryanGlogowski/session02/fizzbuzz.py new file mode 100755 index 0000000..e42241c --- /dev/null +++ b/students/BryanGlogowski/session02/fizzbuzz.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 + +n = int(input('Please enter a number: ')) + +if n > 0: # could you also use a 'while n > 0' here? + for i in range(1,n+1): # or could you use the range function to specify numbers between 1 and 100? + s = '' + if i % 3 == 0: + s += 'Fizz' + if i % 5 == 0: + s += 'Buzz' + if len(s) > 0: # what if i is divisible by both 3 and 5, for example 15? + print(s) + else: + print(i) +else: + print('Sorry, but "{}" is not a natural number!'.format(n)) + diff --git a/students/BryanGlogowski/session02/moneycount.py b/students/BryanGlogowski/session02/moneycount.py new file mode 100755 index 0000000..04ec614 --- /dev/null +++ b/students/BryanGlogowski/session02/moneycount.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 + +total = 0 + +print("Please input the number of...") + +pennies = int(input(" " * 4 + "pennies: ")) +total += pennies + +nickels = int(input(" " * 4 + "nickels: ")) +total += nickels * 5 + +dimes = int(input(" " * 4 + "dimes: ")) +total += dimes * 10 + +quarters = int(input(" " * 4 + "quarters: ")) +total += quarters * 25 + +if total == 100: + print("Congratulations! You have exactly $1!") +elif total > 100: + print("Sorry, you have too many coins to make exactly $1") +else: + print("Sorry, you only have {}¢".format(total)) + + diff --git a/students/BryanGlogowski/session02/print_grid.py b/students/BryanGlogowski/session02/print_grid.py new file mode 100755 index 0000000..903fa77 --- /dev/null +++ b/students/BryanGlogowski/session02/print_grid.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 + +size = 11 + +print("Testing print_grid...") + +for row in range(0,size): + for col in range(0,size): + if col == 0 or col % int(size/2) == 0 or col == size - 1: + if row == 0 or row % int(size/2) == 0 or row == size - 1: + print("+", end=' ') + else: + print("|", end=' ') + else: + if row == 0 or row % int(size/2) == 0 or row == size - 1: + print("-", end=' ') + else: + print(" ", end=' ') + print() + +def print_grid(size): + size += 2 + for row in range(0,size): + for col in range(0,size): + if col == 0 or col % int(size/2) == 0 or col == size - 1: + if row == 0 or row % int(size/2) == 0 or row == size - 1: + print("+", end=' ') + else: + print("|", end=' ') + else: + if row == 0 or row % int(size/2) == 0 or row == size - 1: + print("-", end=' ') + else: + print(" ", end=' ') + print() + +def print_grid2(cols, rows): + line_length = (cols + 1) + (rows * cols) + for j in range(line_length): + if j == 0 or j % (rows+1) == 0: + for i in range(line_length): + if i == 0 or i % (rows+1) == 0: + print("+", end=' ') + else: + print("-", end=' ') + print() + else: + for i in range(line_length): + if i == 0 or i % (rows+1) == 0: + print("|", end=' ') + else: + print(" ", end=' ') + print() + + +print("Testing print_grid(3)...") +print_grid(3) +print() + +print("Testing print_grid(15)...") +print_grid(15) +print() + +print("Testing print_grid2(3,4)...") +print_grid2(3,4) +print() + +print("Testing print_grid2(5,3)...") +print_grid2(5,3) +print() + + + + diff --git a/students/BryanGlogowski/session02/series.py b/students/BryanGlogowski/session02/series.py new file mode 100755 index 0000000..3aca67f --- /dev/null +++ b/students/BryanGlogowski/session02/series.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 + +def fibonacci(n): + """Returns nth value in the Fibonacci sequence""" + if type(n) is not int: + return + elif n < 2: + return n + else: + return fibonacci(n - 1) + fibonacci(n - 2) + +def lucas(n): + """Returns nth value in the Lucas sequence""" + if type(n) is not int: + return + elif n == 0: + return 2 + elif n == 1: + return n + else: + return lucas(n - 1) + lucas(n - 2) + +def sum_series(n, a=0, b=1): + sum = 0 + if a == 0 and b == 1: + for i in range(0,n+1): + sum += fibonacci(i) + elif a == 2 and b == 1: + for i in range(0,n+1): + sum += lucas(i) + else: + return + return sum + + +# This compares the output of fibonacci() to known values +assert fibonacci(10) == 55 +assert fibonacci(20) == 6765 + +# This compares the output of lucas() to known values +assert lucas(10) == 123 +assert lucas(20) == 15127 + +# This tests sum_series() with Fibonacci numbers +assert sum_series(10) == 143 +assert sum_series(20) == 17710 + +# This tests sum_series() with Lucas numbers +assert sum_series(10,2,1) == 321 +assert sum_series(20,2,1) == 39602 + diff --git a/students/BryanGlogowski/session03/README.rst b/students/BryanGlogowski/session03/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session03/format_string.py b/students/BryanGlogowski/session03/format_string.py new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session03/list_lab.py b/students/BryanGlogowski/session03/list_lab.py new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session03/mailroom.py b/students/BryanGlogowski/session03/mailroom.py new file mode 100755 index 0000000..f8acf5b --- /dev/null +++ b/students/BryanGlogowski/session03/mailroom.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 + +# Initial Account Information: +donor_records = { + 'Scrooge McDuck': [ + 1000.00, + 2050.00, + 2500.00 + ], + 'Thurston Howell, III': [ + 100.00, + 250.00, + 300.00 + ], + 'Ri¢hie Ri¢h': [ + 10000.00, + 50000.00, + ], + 'Montgomery Brewster': [ + 40000000.00, + ], + 'Jed Clampett': [ + 1000000.00, + ], + 'C. Montgomery Burns': [ + 0.10, + 0.25, + 0.05, + ], +} + +def send_thank_you(name, amount): + """Prints out Thank You notes to donors""" + print("Dear, {}".format(name)) + print("Thank you so much for your donation of ${}!".format(amount)) + print("We very much appreciate all the support.") + +def create_report(accounts): + """Prints out a report of all the donations in the database""" + + donations = [] + + # Sum all the donations in all the accounts to sort donation amounts + for key in accounts: + donations.append(sum(accounts[key])) + + # Sort the accounts from least generous to most + donations.sort() + + # Print Headers + print("{:20}{:16}{:21}{:16}".format("Name", "Donations", "Ave. Amt.", "Total")) + print("{:20}{:16}{:21}{:16}".format("----", "---------", "---------", "-----")) + + # Iterate backwards through the sorted list + for i in donations[::-1]: + for key in accounts: + # Print accounts associated with the sorted amounts + # Fix: Assumes no two donors donated the exact amount + if i == sum(accounts[key]): + print("{:20}{:4d} ${:12.2f} ${:12.2f}".format(key, len(accounts[key]), sum(accounts[key]) / len(accounts[key]), i)) + +if __name__ == '__main__': + """Only run this if the script is called directly""" + is_working = True + while is_working: + print("Welcome! Would you like to:") + print("(S)end a Thank You?") + print("(C)reate a Report?") + print("E(x)it program.") + option = input("Type 's' for send, and 'c' for create: ") + if option.lower() == 's': + is_thanking = True + while is_thanking: + name = input("Enter the full name of the person to thank, or type 'list': ") + if name == 'list': + print("List of donors:") + for donor in donor_records.keys(): + print(" {}".format(donor)) + else: + if name not in donor_records: + donor_records[name] = [] + verifying_deposit = True + while verifying_deposit: + donation = input("Enter a donation amount: ") + try: + float(donation) + verifying_deposit = False + except ValueError: + print("Sorry, you entered an invalid amount.") + + donor_records[name].append(float(donation)) + send_thank_you(name, donation) + is_thanking = False + + elif option.lower() == 'c': + create_report(donor_records) + elif option.lower() == 'x': + is_working = False + else: + print("Sorry, I didn't undertsand your input.") + print("Please try again...") + + print("Have a nice day!") + + diff --git a/students/BryanGlogowski/session03/rot13.py b/students/BryanGlogowski/session03/rot13.py new file mode 100644 index 0000000..b7caf01 --- /dev/null +++ b/students/BryanGlogowski/session03/rot13.py @@ -0,0 +1,51 @@ +def char_map(): + import string + return string.ascii_lowercase + string.ascii_lowercase + +def add13(c): + chars = char_map() + counter = 0 + for l in chars: + if l == c: + position = counter + break + counter += 1 + return chars[counter + 13] + +def sub13(c): + chars = char_map() + counter = 51 + for l in chars[::-1]: + if l == c: + position = counter + break + counter -= 1 + return chars[counter - 13] + +def translate(s): + text = '' + for c in s: + if c == ' ': + text = text + ' ' + else: + if c.isupper(): + text = text + sub13(c.lower()).upper() + else: + text = text + sub13(c.lower()) + return text + +def encrypt(s): + text = '' + for c in s: + if c == ' ': + text = text + ' ' + else: + if c.isupper(): + text = text + add13(c.lower()).upper() + else: + text = text + add13(c.lower()) + return text + +if __name__ == '__main__': + assert translate('Zntargvp sebz bhgfvqr arne pbeare') == 'Magnetic from outside near corner' + assert encrypt('Magnetic from outside near corner') == 'Zntargvp sebz bhgfvqr arne pbeare' diff --git a/students/BryanGlogowski/session03/sequence_slicing.py b/students/BryanGlogowski/session03/sequence_slicing.py new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session04/README.rst b/students/BryanGlogowski/session04/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session04/dict_lab.py b/students/BryanGlogowski/session04/dict_lab.py new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session05/README.rst b/students/BryanGlogowski/session05/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session05/cp.py b/students/BryanGlogowski/session05/cp.py new file mode 100755 index 0000000..2e9013a --- /dev/null +++ b/students/BryanGlogowski/session05/cp.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +def copy_file(src, dest): + global f1, f2 + + try: + f1 = open(src, 'rb') + except FileNotFoundError: + print("could not read '{}'".format(src)) + return + + try: + f2 = open(dest, 'wb') + except IOError: + print("could not open '{}'".format(dest)) + return + + for line in f1.readlines(): + try: + f2.write(line) + except IOError: + print("could not write to '{}'".format(dest)) + return + + f1.close() + f2.close() + print("'{}' successfully copied to '{}'".format(src, dest)) + return + +copy_file('students.txt', 'foo.txt') + diff --git a/students/BryanGlogowski/session05/ls.py b/students/BryanGlogowski/session05/ls.py new file mode 100755 index 0000000..ec7e8b7 --- /dev/null +++ b/students/BryanGlogowski/session05/ls.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 + +import os + +def get_file_list(path): + """Returns a list of absolute paths""" + return [os.path.join(os.getcwd(),f) for f in os.listdir('.')] + +def print_list(files): + """Prints the items in a list""" + for file in files: + print(file) + +def list_all_files(path): + """Gets a list of files and prints them""" + print_list(get_file_list(path)) + +list_all_files('.') + diff --git a/students/BryanGlogowski/session05/mailroom.py b/students/BryanGlogowski/session05/mailroom.py new file mode 100755 index 0000000..f8acf5b --- /dev/null +++ b/students/BryanGlogowski/session05/mailroom.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 + +# Initial Account Information: +donor_records = { + 'Scrooge McDuck': [ + 1000.00, + 2050.00, + 2500.00 + ], + 'Thurston Howell, III': [ + 100.00, + 250.00, + 300.00 + ], + 'Ri¢hie Ri¢h': [ + 10000.00, + 50000.00, + ], + 'Montgomery Brewster': [ + 40000000.00, + ], + 'Jed Clampett': [ + 1000000.00, + ], + 'C. Montgomery Burns': [ + 0.10, + 0.25, + 0.05, + ], +} + +def send_thank_you(name, amount): + """Prints out Thank You notes to donors""" + print("Dear, {}".format(name)) + print("Thank you so much for your donation of ${}!".format(amount)) + print("We very much appreciate all the support.") + +def create_report(accounts): + """Prints out a report of all the donations in the database""" + + donations = [] + + # Sum all the donations in all the accounts to sort donation amounts + for key in accounts: + donations.append(sum(accounts[key])) + + # Sort the accounts from least generous to most + donations.sort() + + # Print Headers + print("{:20}{:16}{:21}{:16}".format("Name", "Donations", "Ave. Amt.", "Total")) + print("{:20}{:16}{:21}{:16}".format("----", "---------", "---------", "-----")) + + # Iterate backwards through the sorted list + for i in donations[::-1]: + for key in accounts: + # Print accounts associated with the sorted amounts + # Fix: Assumes no two donors donated the exact amount + if i == sum(accounts[key]): + print("{:20}{:4d} ${:12.2f} ${:12.2f}".format(key, len(accounts[key]), sum(accounts[key]) / len(accounts[key]), i)) + +if __name__ == '__main__': + """Only run this if the script is called directly""" + is_working = True + while is_working: + print("Welcome! Would you like to:") + print("(S)end a Thank You?") + print("(C)reate a Report?") + print("E(x)it program.") + option = input("Type 's' for send, and 'c' for create: ") + if option.lower() == 's': + is_thanking = True + while is_thanking: + name = input("Enter the full name of the person to thank, or type 'list': ") + if name == 'list': + print("List of donors:") + for donor in donor_records.keys(): + print(" {}".format(donor)) + else: + if name not in donor_records: + donor_records[name] = [] + verifying_deposit = True + while verifying_deposit: + donation = input("Enter a donation amount: ") + try: + float(donation) + verifying_deposit = False + except ValueError: + print("Sorry, you entered an invalid amount.") + + donor_records[name].append(float(donation)) + send_thank_you(name, donation) + is_thanking = False + + elif option.lower() == 'c': + create_report(donor_records) + elif option.lower() == 'x': + is_working = False + else: + print("Sorry, I didn't undertsand your input.") + print("Please try again...") + + print("Have a nice day!") + + diff --git a/students/BryanGlogowski/session05/students.txt b/students/BryanGlogowski/session05/students.txt new file mode 100644 index 0000000..1c83671 --- /dev/null +++ b/students/BryanGlogowski/session05/students.txt @@ -0,0 +1,24 @@ +Bindhu, Krishna: +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: diff --git a/students/BryanGlogowski/session06/README.rst b/students/BryanGlogowski/session06/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session06/cigar_party.py b/students/BryanGlogowski/session06/cigar_party.py new file mode 100755 index 0000000..71dead1 --- /dev/null +++ b/students/BryanGlogowski/session06/cigar_party.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + +def cigar_party(cigars, is_weekend): + return 40 <= cigars <= 60 or (is_weekend and cigars >= 40) diff --git a/students/BryanGlogowski/session06/test_cigar_party.py b/students/BryanGlogowski/session06/test_cigar_party.py new file mode 100755 index 0000000..260d5f4 --- /dev/null +++ b/students/BryanGlogowski/session06/test_cigar_party.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +# you can change this import to test different versions +from cigar_party import cigar_party +# from cigar_party import cigar_party2 as cigar_party +# from cigar_party import cigar_party3 as cigar_party + + +def test_1(): + assert cigar_party(30, False) is False + + +def test_2(): + assert cigar_party(50, False) is True + + +def test_3(): + assert cigar_party(70, True) is True + + +def test_4(): + assert cigar_party(30, True) is False + + +def test_5(): + assert cigar_party(50, True) is True + + +def test_6(): + assert cigar_party(60, False) is True + + +def test_7(): + assert cigar_party(61, False) is False + + +def test_8(): + assert cigar_party(40, False) is True + + +def test_9(): + assert cigar_party(39, False) is False + + +def test_10(): + assert cigar_party(40, True) is True + + +def test_11(): + assert cigar_party(39, True) is False diff --git a/students/BryanGlogowski/session06/trapezoidal.py b/students/BryanGlogowski/session06/trapezoidal.py new file mode 100755 index 0000000..8c62a33 --- /dev/null +++ b/students/BryanGlogowski/session06/trapezoidal.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 + +import math + +def trapz(fun, a, b): + + # Redefine range to do floating point + def frange(start, stop, step): + i = start + while i < stop: + yield i + i += step + + # Increase precision by always using floating point + area = 0.0 + step = (float(b) - float(a)) / 200.0 + + for i in frange(float(a),float(b),step): + area += ((fun(i) + fun(i+step)) / 2.0) * step + + return area + + +# Example functions +def l(x): + return 5.0 + +def s(x): + return math.sqrt(1+math.sin(x)**3) + +def t(x): + return math.tan(x) + +def st(x): + return math.tan(x) * math.sin(x) + +# Assert my answers are similar to a Trapezoidal Rule Calculator + +# ...with a specified precision: +precision = 5 + +print(round(trapz(s, 0, 10),precision)) +print(round(10.1810116595807,precision)) +assert round(trapz(s, 0, 10),precision) == round(10.1810116595807,precision) + +print(round(trapz(l, 0, 10),precision)) +print(round(50.0,precision)) +assert round(trapz(l, 0, 10),precision) == round(50.0,precision) + +print(round(trapz(t, 0, 10),precision)) +print(round(16.5054761640473,precision)) +assert round(trapz(t, 0, 10),precision) == round(16.5054761640473,precision) + +# More tests... +assert round(trapz(st, 0, 10),precision) == round(9.8923666153375,precision) +assert round(trapz(st, 10, 20),precision) == round(9.44777265586442,precision) +assert round(trapz(st, -10, 20),precision) == round(58.5233631220135,precision) +assert round(trapz(st, -10.2, 20.53),precision) == round(-0.409523489721687,precision) diff --git a/students/BryanGlogowski/session07/README.rst b/students/BryanGlogowski/session07/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session08/README.rst b/students/BryanGlogowski/session08/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session09/README.rst b/students/BryanGlogowski/session09/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/BryanGlogowski/session10/README.rst b/students/BryanGlogowski/session10/README.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/ChiHo/README.rst b/students/ChiHo/README.rst new file mode 100644 index 0000000..3231ecd --- /dev/null +++ b/students/ChiHo/README.rst @@ -0,0 +1,3 @@ +This is Chi's file. + +This is the second time testing. \ No newline at end of file diff --git a/students/ChiHo/lightning/Lightning Talk.pptx b/students/ChiHo/lightning/Lightning Talk.pptx new file mode 100644 index 0000000..03e6cdd Binary files /dev/null and b/students/ChiHo/lightning/Lightning Talk.pptx differ diff --git a/students/ChiHo/session02/fizz_buzz.py b/students/ChiHo/session02/fizz_buzz.py new file mode 100644 index 0000000..43dcf36 --- /dev/null +++ b/students/ChiHo/session02/fizz_buzz.py @@ -0,0 +1,50 @@ +# Week 2 - Lab #1: FizzBuzz +# Date: Thursday, January 28, 2016 +# Student: Chi Kin Ho + + +def fizz_buzz(n): + """ + This function takes a natural number, n. + It prints out the numbers from 1 to n, but it replaces numbers + divisible by 3 with "Fizz", numbers divisible by 5 with "Buzz". + Numbers divisible by both factors should display "FizzBuzz". + """ + + # for i in range(1, n+1): + # if i % 3 == 0: + # if i % 5 == 0: # divisible by 3 and 5 + # print('FizzBuzz') + # else: # divisible by 3 only + # print('Fizz') + # elif i % 5 == 0: # divisible by 5 only + # print('Buzz') + # else: # neither divisible by 3 nor divisible by 5 + # print(i) + + # Chi -- I can see that you're trying to be more efficient, but + # you're sacraficing readability for little performance gain. + # Readability counts because it helps in thinking about your code. + # Compare your code above to these minor revisions.... + + for i in range(1, n+1): + if i % 3 == 0 and i % 5 == 0: + print('FizzBuzz') + elif i % 5 == 0: + print('Buzz') + elif i % 3 == 0: + print('Fizz') + else: + print(i) + +if __name__ == '__main__': + # # Test Case 1: n = 1 + # fizz_buzz(1) + # # Test Case 2: n = 3 + # fizz_buzz(3) + # # Test case 3: n = 5 + # fizz_buzz(5) + # # Test case 4: n = 10 + # fizz_buzz(10) + # # Test case 5: n = 16 + fizz_buzz(16) diff --git a/students/ChiHo/session02/grid_printer.py b/students/ChiHo/session02/grid_printer.py new file mode 100644 index 0000000..5eb73fd --- /dev/null +++ b/students/ChiHo/session02/grid_printer.py @@ -0,0 +1,53 @@ +# Week 2 - Lab #3: Print Grid +# Date: Sunday, January 17, 2016 +# Student: Chi Kin Ho + + +def print_grid(n, m): + + """ + This function takes two natural number arguments, n and m. It prints a + grid with n by n squares where each square has the width of m characters. + """ + + # Initialize the grid before drawing. + grid = '' + for i in range(n): + # Draw a horizontal row of border. + grid += print_one_row_of_symbols(n, m, '+', '-') + # Draw m rows of vertical bars. + grid += print_one_row_of_symbols(n, m, '|', ' ') * m + # Draw the last horizontal row of border. + grid += print_one_row_of_symbols(n, m, '+', '-') + # Output the grid on the screen. + print(grid) + + +def print_one_row_of_symbols(n, m, outer_symbol, inner_symbol): + + """ + This function takes two natural number arguments, n and m, and two character arguments, + outer_symbol and inner_symbol. It prints one row of symbols with (n+1) outer_symbols + and m inner_symbols between two outer_symbols. + """ + + # Draw the first outer symbol in a row. + grid = outer_symbol + for i in range(n): + # Draw n inner symbols in the same row. + grid += inner_symbol * m + # Draw the outer symbol. + grid += outer_symbol + # Draw a new line. + grid += '\n' + return grid + + +# Test Case 1: 2 x 2 grid where each square has the width of 1. +print_grid(2, 1) +# Test Case 2: 2 x 2 grid where each square has the width of 7. +print_grid(2, 7) +# Test Case 3: 3 x 3 grid where each square has the width of 4. +print_grid(3, 4) +# Test Case 4: 5 x 5 grid where each square has the width of 3. +print_grid(5, 3) diff --git a/students/ChiHo/session02/money_counting.py b/students/ChiHo/session02/money_counting.py new file mode 100644 index 0000000..0c6a785 --- /dev/null +++ b/students/ChiHo/session02/money_counting.py @@ -0,0 +1,61 @@ +# Week 2 - Lab #2: MoneyCounting +# Date: Saturday, January 16, 2016 +# Student: Chi Kin Ho + + +def prompt_number_of_coins(prompt): + + """ + This function takes a prompt message of string. + It prompts the user for the number of coins and returns it. + """ + + # Obtain the number of coins from the user. + number_of_coins = input(prompt) + return number_of_coins + + +def money_counting(pennies, nickels, dimes, quarters): + + """ + This function determines whether a mix of coins can make EXACTLY + one dollar. Your program should prompt users to enter 4 integers: + the number of pennies, nickels, dimes, and quarters. If the total + value of the coins entered is equal to one dollar, the program + should congratulate users for winning the game. Otherwise, the + program should display a message indicating whether the amount + entered was more than or less than a dollar. + + """ + + # Check to ensure that pennies, nickels, dimes, and quarters are + # not negative. + if pennies < 0 or nickels < 0 or dimes < 0 or quarters < 0: + # Output an error message. + print('\nInput Error: Pennies, nickels, dimes, and quarters must be nonnegative.') + # Return and exit the function. + return None + + # Calculate the total value based on the number of pennies, nickels, + # dimes, and quarters. + total_value = 0.01*pennies + 0.05*nickels + 0.10*dimes + 0.25*quarters + if total_value == 1: # The total value is $1.00. + print('\nCongratulations, you win the game!') + elif total_value > 1: # The total value is greater than $1.00. + print('\nThe amount entered was more than a dollar.') + else: # The total value is less than $1.00. + print('\nThe amount entered was less than a dollar.') + + +# Prompt the number of pennies from the user. +number_of_pennies = prompt_number_of_coins('Enter the number of pennies: ') +# Prompt the number of nickels from the user. +number_of_nickels = prompt_number_of_coins('Enter the number of nickels: ') +# Prompt the number of dimes from the user. +number_of_dimes = prompt_number_of_coins('Enter the number of dimes: ') +# Prompt the number of quarteres from the user. +number_of_quarters = prompt_number_of_coins('Enter the number of quarters: ') + +# Calculate the total value of the coins, and display it on the screen. +money_counting(int(number_of_pennies), int(number_of_nickels), + int(number_of_dimes), int(number_of_quarters)) diff --git a/students/ChiHo/session02/series.py b/students/ChiHo/session02/series.py new file mode 100644 index 0000000..807c2ad --- /dev/null +++ b/students/ChiHo/session02/series.py @@ -0,0 +1,97 @@ +# Week 2 - Lab #4: Series +# Date: Monday, January 18, 2016 +# Student: Chi Kin Ho + + +def sum_series(n, *starting_values): + + """ + This function takes one required parameter, n, and two optional + parameters, *starting_values. The required parameter will determine + which element in the series to print. The two optional parameters + will have default values of 0 and 1 and will determine the first two + values for the series to be produced. + + Calling this function with no optional parameters will produce numbers + from the fibonacci series. Calling it with the optional arguments 2 and 1 + will produce values from the lucas numbers. Other values for the optional + parameters will produce other series. + + :param n: the term number, which starts from 0, 1, 2, ... + :param starting_values: the first and second optional starting values of the series + :return: the nth term of the sum sequence + """ + + if len(starting_values) == 0: # fibonacci sequence + return fibonacci(n) + elif len(starting_values) == 2: + if starting_values[0] == 2 and starting_values[1] == 1: # lucas sequence + return lucas(n) + else: # other series + if n == 0 or n == 1: + return starting_values[n] + else: + return sum_series(n-2, *starting_values) + sum_series(n-1, *starting_values) + else: + return None # Invalid number of starting_values + + +def fibonacci(n): + + """ + This function calculates and returns the nth term of the Fibonacci sequence + + :param n: the term number, which starts from 0, 1, 2, ... + :return: the nth term of the Fibonacci sequence + """ + + if n == 0 or n == 1: # base cases: when n == 0 or n == 1 + return n + else: # recursive step + return fibonacci(n-2) + fibonacci(n-1) + + +def lucas(n): + + """ + This function calculates and returns the nth term of the Lucas sequence + + :param n: the term number, which starts from 0, 1, 2, ... + :return: the nth term of the Lucas sequence + """ + + if n == 0: # base case: when n == 0 + return 2 + elif n == 1: # base case: when n == 1 + return 1 + else: # recursive step + return lucas(n-2) + lucas(n-1) + + +# Test Case 1: the 8th term of the Fibonacci sequence +f_series = '' +for i in range(8): + f_series += str(sum_series(i)) + if (i < 7): + f_series += ', ' +print(f_series) + +# Test Case 2: the 8th term of the Lucas sequence +l_series = '' +for i in range(8): + l_series += str(sum_series(i, 2, 1)) + if (i < 7): + l_series += ', ' +print(l_series) + +# Test Case 3: the 8th term of the sum series with the starting values of 5 and 10 +other_series = '' +for i in range(8): + other_series += str(sum_series(i, 5, 10)) + if (i < 7): + other_series += ', ' +print(other_series) + +# Test Case 4: Invalid number of starting values +print(sum_series(3, 4)) +print(sum_series(3, 4, 5, 6)) \ No newline at end of file diff --git a/students/ChiHo/session03/list_lab.py b/students/ChiHo/session03/list_lab.py new file mode 100644 index 0000000..e1e3895 --- /dev/null +++ b/students/ChiHo/session03/list_lab.py @@ -0,0 +1,148 @@ +# List Lab +# Student: Chi Kin Ho +# Date: Sunday, January 24, 2016 + +# When the script is run, it should accomplish the following four series of actions: + +# --------------------------------------------------------------------------------------------------------------------- +# Series 1 +# --------------------------------------------------------------------------------------------------------------------- + +# Create a list that contains "Apples", "Pears", "Oranges" and "Peaches". +fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] + +# Display the list. +print(fruit_list) + +# Ask the user for another fruit and add it to the end of the list. +fruit = input("Enter another fruit: ") +fruit_list.append(fruit) + +# Display the list. +print(fruit_list) + +# Ask the user for a number and display the number back to theuser and the fruit corresponding to that number +# (on a 1-is-first basis). +number = input("Enter a number: ") +print(number) +number = int(number) +if 1 <= number <= len(fruit_list): + print(fruit_list[number-1]) +else: + print("Error: number must be between 1 and", len(fruit_list)) + +# Add another fruit to the beginning of the list using "+" and display the list. +new_fruit_list = '' +if len(fruit_list) > 0: + # Convert the fruit list into string so that I can use the "+" operator to add a new fruit, + for i in range(len(fruit_list)): + if i == 0: + new_fruit_list = fruit_list[i] + else: + new_fruit_list += ', ' + fruit_list[i] + +fruit_list = new_fruit_list +fruit_list = "Mangoes, " + new_fruit_list +# Convert the string back to the list. +fruit_list = fruit_list.split(', ') +print(fruit_list) + +# Add another fruit to the beginning of the list using insert() and display the list. +fruit_list.insert(0, 'Pineapples') +print(fruit_list) + +# Display all the fruits that begin with "P" using a for-loop. +all_fruits_begin_with_P = list() +for fruit in fruit_list: + if fruit.startswith('P'): + all_fruits_begin_with_P.append(fruit) +print(all_fruits_begin_with_P) + + +# --------------------------------------------------------------------------------------------------------------------- +# Series 2 +# --------------------------------------------------------------------------------------------------------------------- + +# Using the list created in series 1 above: + +# Display the list. +fruit_list_2 = fruit_list[:] +print(fruit_list_2) + +# Remove the last fruit from the list. +fruit_list_2.pop() + +# Display the list. +print(fruit_list_2) + +# Ask the user for a fruit to delete and find it and delete it. +fruit = input('Enter a fruit to delete: ') +if fruit in fruit_list_2: + fruit_list_2.remove(fruit) +print(fruit_list_2) + +# Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences. +fruit_list_2 *= 2 +print(fruit_list_2) +# Repeatedly ask the user for a fruit until a match is found. +fruit = '' +is_match_found = False +while not is_match_found: + fruit = input('Enter a fruit to delete: ') + is_match_found = fruit in fruit_list_2 +# Delete all occurrences. +while fruit in fruit_list_2[:]: + fruit_list_2.remove(fruit) +# Display the list. +print(fruit_list_2) + + +# --------------------------------------------------------------------------------------------------------------------- +# Series 3 +# --------------------------------------------------------------------------------------------------------------------- + +# Again, using the list from series 1: +fruit_list_3 = fruit_list[:] +print(fruit_list_3) + +# Ask the user for input displaying a line like "Do you like apples?" + +# For each fruit in the list (making all lowercase). +for i in range(len(fruit_list_3)): + fruit_list_3[i] = fruit_list_3[i].lower() +print(fruit_list_3) + +# Repeatedly ask the user whether or not he/she likes apples until he/she types 'yes' or 'no'. +is_done = False +while not is_done: + response = input('Do you like apples? ') + if response.lower() == 'no': + if 'apples' in fruit_list_3: + fruit_list_3.remove('apples') + is_done = True + elif response.lower() == 'yes': + is_done = True + +# Display the list. +print(fruit_list_3) + + +# --------------------------------------------------------------------------------------------------------------------- +# Series 4 +# --------------------------------------------------------------------------------------------------------------------- + +# Make a copy of the list and reverse the letters in each fruit in the copy. +fruit_list_4 = fruit_list[:] +print(fruit_list_4) + +# Reverse the letters in each fruit in the copy. +for i in range(len(fruit_list_4)): + fruit_list_4[i] = fruit_list_4[i][::-1] +# Display the list. +print(fruit_list_4) + +# Delete the last item of the original list. +fruit_list.pop() +# Display the original list and the copy. +print(fruit_list) +print(fruit_list_4) \ No newline at end of file diff --git a/students/ChiHo/session03/mailroom.py b/students/ChiHo/session03/mailroom.py new file mode 100644 index 0000000..4d4940e --- /dev/null +++ b/students/ChiHo/session03/mailroom.py @@ -0,0 +1,137 @@ +# Mailroom Lab +# Student: Chi Kin Ho +# Date: Thursday, January 28, 2016 + + +def display_menu(): + + """ + Display the menu of 3 actions: (1) Send a Thank You, (2) Create a Report, or (3) Quit. If the user + enters an action other than 1, 2, or 3, the program will prompt him/her to enter an action again + until the correct action is entered. + + :return: 1, 2 or 3 which corresponds to each of the above three actions. + """ + + # Repeatedly display a menu of 3 actions until the user enters the correct action. + while True: + print('\nMenu of 3 Actions') + print('\t1. Send a Thank You') + print('\t2. Create a Report') + print('\t3. Quit') + action = input('Enter an action: ') + + if action == '1' or action == '2' or action == '3': + return int(action) # action is correct + else: + print('Invalid input. Please enter either 1, 2 or 3') + + +def send_a_thank_you(donors_dict): + + while True: + name = input("Enter the donor's name: " ) + if name == 'list': + # Display the list of donors' names. + for donor_name in sorted(donors_dict): + print(donor_name) + else: + + # Prompt the user for a donation amount. + donation_amount = input("Enter a donation amount: $") + while True: + try: + + float(donation_amount) + except: + # Re-prompt the user for a donation amount. + donation_amount = input("Enter a donation amount: $") + else: + break + + # Round the donation amount to 2 decimal places. + donation_amount = round(float(donation_amount), 2) + + # Round the donation ammount to 2 decimal places. + donation_amount = round(donation_amount, 2) + if name in donors_dict: # The donor's name is already in the dictionary. + # Update the donor's record. + history_of_donations = donors_dict[name] + history_of_donations[0] += donation_amount # total donated + history_of_donations[1] += 1 # number of donations + history_of_donations[2] = round(history_of_donations[0] / history_of_donations[1], 2) # average + else: # New donor + # Add the new donor's name and the donation amount to the dictionary. + donors_dict[name] = [donation_amount, 1, donation_amount] + # Compose an e-mail thanking the donor for his/her generous donation, and print + # it on the terminal. + print('Thank you, {}, for your generous donation!'.format(name)) + + # The sending of a thank-you is completed! + return donors_dict + + +def create_a_report(donors_dict): + # Create an inverse dictionary so that it can be sorted by the total donated. + inverse_dictionary = invert_donor_dictionary(donors_dict) + for total_donated in sorted(inverse_dictionary): + donor_lists = inverse_dictionary[total_donated] + # Display each donor's history of donations. + for donor in donor_lists: + print('{:10} {:10.2f} {:10} {:10.2f}'.format(donor[0], donor[1], donor[2], donor[3])) + + +def invert_donor_dictionary(donors_dict): + # Create an inverse dictionary so that it can be sorted by the total donated before creating a report. + inverse_dictionary = dict() + + for donor_name in donors_dict: + # Get the history of donations of a given donor's name. + history_of_donations = donors_dict[donor_name] + # Get the total donated. + total_donated = history_of_donations[0] + # Get the number of donations. + number_of_donations = history_of_donations[1] + # Get the average amount of donations. + average_donation = history_of_donations[2] + + # Check whether or not the total donated is already in the inverse_dictionary. + if total_donated not in inverse_dictionary: + # If not, add it to the inverse dictionary. + inverse_dictionary[total_donated] = list() + inverse_dictionary[total_donated].append([donor_name, total_donated, number_of_donations, average_donation]) + else: + # Otherwise, append it to the inverse dictionary. + inverse_dictionary[total_donated].append([donor_name, total_donated, number_of_donations, average_donation]) + + return inverse_dictionary + + +if __name__ == '__main__': + # Declare a dictionary that stores a list of donor names and the history of the + # total donated, the number of donations and the average donation amount. + donors_dict = dict() + + # Populate the dictionary with 5 donors with between 1 and 3 donations each. + donors_dict['David'] = [99.00, 3, 33.0] + donors_dict['Bill'] = [20.00, 2, 10.00] + donors_dict['Andrea'] = [15.00, 2, 7.50] + donors_dict['Alison'] = [80.00, 1, 80.0] + donors_dict['Ryan'] = [10.00, 2, 5.00] + + action = display_menu() + while True: + + if action == 1: # Send a Thank You + donors_dict = send_a_thank_you(donors_dict) + + elif action == 2: # Create a Report + create_a_report(donors_dict) + + else: # action == 3 -- Quit + break + + # Display the menu again and prompt the user for an action. + action = display_menu() + + diff --git a/students/ChiHo/session03/rot13.py b/students/ChiHo/session03/rot13.py new file mode 100644 index 0000000..5c453ab --- /dev/null +++ b/students/ChiHo/session03/rot13.py @@ -0,0 +1,34 @@ +# ROT13 Lab +# Student: Chi Kin Ho +# Date: Thursday, January 28, 2016 + +def rot13(s): + """ + The ROT13 encryption scheme is a simple substitution cypher where each letter in a text is replace + by the letter 13 away from it (imagine the alphabet as a circle, so it wraps around). + + :param s: the string text to be encrypted + :return: the encrypted text using the ROT13 encryption scheme + """ + + encrypted_message = '' + for letter in s: + if letter.isalpha(): + if letter.isupper(): + # This is a upper case letter. + encrypted_message += chr( ((ord(letter) - ord('A') + 13) % 26) + ord('A') ) + else: + # This is a lower case letter. + encrypted_message += chr( ((ord(letter) - ord('a') + 13) % 26) + ord('a') ) # great! + else: + encrypted_message += letter + else: + # Display the encrypted message on the screen. + print(encrypted_message) + + +if __name__ == '__main__': + rot13('Zntargvp sebz bhgfvqr arne pbeare') + + + diff --git a/students/ChiHo/session03/slicing_lab.py b/students/ChiHo/session03/slicing_lab.py new file mode 100644 index 0000000..d72c5bb --- /dev/null +++ b/students/ChiHo/session03/slicing_lab.py @@ -0,0 +1,111 @@ +# Slicing Lab +# Student: Chi Kin Ho +# Date: Saturday, January 23, 2016 + + +def exchange(s): + """ + This functions takes any sequence and returns a sequence with the first and last + items exchanged. + + :param s: any sequence + :return: a sequence with the first and last items exchanged + """ + if len(s) == 0 or len(s) == 1: + return s + else: + return s[len(s)-1:] + s[1:len(s)-1] + s[0:1] + + +def every_other_items_removed(s): + """ + This function takes any sequence and returns a sequence with every other item + removed. + + :param s: any sequence + :return: a sequence with every other item removed + """ + return s[::2] + + +def first_and_last_4_items_removed(s): + """ + This function takes any sequence and returns a sequence with the first and last + 4 items removed, and every other item in between. + + :param s: any sequence + :return: a sequence with the first and last 4 items removed, and every other + item in between + """ + s = s[4:] + s = s[:-4] + return s + + +def reverse(s): + """ + This function takes any sequence and returns a sequence reversed. + + :param s: any sequence + :return: a sequence reversed + """ + + return s[::-1] + + +def middle_third_last_third_first_third(s): + """ + This function takes any sequence and returns a sequence with the middle third, + then last third, then the first third in the new order. + + :param s: any sequence + :return: a sequence with the middle third, then last third, then the first + third in the new order + """ + + return s[int(len(s)/3):int(2*len(s)/3)] + s[int(2*len(s)/3):] + s[0:int(len(s)/3)] + + +if __name__ == '__main__': + print(exchange("")) + print(exchange("a")) + print(exchange("ab")) + print(exchange("abc")) + print(exchange("abcd")) + print(exchange("abcde")) + print(exchange("abcdefghijk")) + + print(every_other_items_removed("")) + print(every_other_items_removed("a")) + print(every_other_items_removed("ab")) + print(every_other_items_removed("abc")) + print(every_other_items_removed("abcd")) + print(every_other_items_removed("abcde")) + print(every_other_items_removed("abcdefghijk")) + + print(first_and_last_4_items_removed("")) + print(first_and_last_4_items_removed("a")) + print(first_and_last_4_items_removed("ab")) + print(first_and_last_4_items_removed("abc")) + print(first_and_last_4_items_removed("abcd")) + print(first_and_last_4_items_removed("abcde")) + print(first_and_last_4_items_removed("abcdefghijk")) + + print(reverse("")) + print(reverse("a")) + print(reverse("ab")) + print(reverse("abc")) + print(reverse("abcd")) + print(reverse("abcde")) + print(reverse("abcdefghijk")) + + print(middle_third_last_third_first_third("")) + print(middle_third_last_third_first_third("a")) + print(middle_third_last_third_first_third("ab")) + print(middle_third_last_third_first_third("abc")) + print(middle_third_last_third_first_third("abcd")) + print(middle_third_last_third_first_third("abcde")) + print(middle_third_last_third_first_third("abcdefghijkl")) + + + diff --git a/students/ChiHo/session03/string_formatting_lab.py b/students/ChiHo/session03/string_formatting_lab.py new file mode 100644 index 0000000..dc56605 --- /dev/null +++ b/students/ChiHo/session03/string_formatting_lab.py @@ -0,0 +1,6 @@ +# String Lab +# Student: Chi Kin Ho +# Date: Thursday, January 28, 2016 + +f = (2, 123.4567, 10000) +print("file_{:0>3d}: {:.2f}, {:.0e}".format(*f)) diff --git a/students/ChiHo/session04/dict_lab.py b/students/ChiHo/session04/dict_lab.py new file mode 100644 index 0000000..5333d30 --- /dev/null +++ b/students/ChiHo/session04/dict_lab.py @@ -0,0 +1,106 @@ +# Dictionary and Key Lab +# Student: Chi Kin Ho +# Date: Thursday, January 28, 2016 + +# Create a dictionary containing "name", "city", and "cake" for "Chris" from "Seattle" who likes "Chocolate". +dictionary = dict() +dictionary['cake'] = ['name', 'city'] +dictionary['Chocolate'] = ['Chris', 'Seattle'] +# Display the dictionary. +print(dictionary) + +# Delete the entry for "cake". +dictionary.pop('cake') +# Display the dictionary. +print(dictionary) + +# Add an entry for "fruit" with "Mango" and display the dictionary. +dictionary['Mango'] = ['David', 'Toronto'] + +# Display the dictionary keys. +for key in dictionary.keys(): + print(key) +# Display the dictionary values. +for value in dictionary.values(): + print(value) + +# Display whether or not "cake" is a key in the dictionary (i.e., False) (now). +print('cake' in dictionary) +# Display whether or nto "Mango" is a value in the dictionary (i.e., True). +print('Mango' in dictionary) + +# Using the dictionary from item 1: Make a dictionary using the same keys but with the number of 't's in each value. +dictionary2 = dict() + +def find_the_number_of_t(v): + """ + This function takes an input string argument and returns the number of t's in this string argument. + + :param v: the input string argument + :return: the number of t's in this string argument + """ + number_of_ts = 0 + for letter in v: + if letter == 't' or letter == 'T': + number_of_ts += 1 + return number_of_ts + +for key in dictionary: + dictionary2[key] = [find_the_number_of_t(dictionary[key][0]), find_the_number_of_t(dictionary[key][1])] + +# Display the two dictionaries. +print(dictionary) +print(dictionary2) + +# Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible by 2, 3 and 4. +s2 = set() +s3 = set() +s4 = set() +for number in range(0, 21): + if number % 2 == 0: + # Add the number that is divisible by 2 to s2. + s2.add(number) + if number % 3 == 0: + # Add the number that is divisible by 3 to s3. + s3.add(number) + if number % 4 == 0: + # Add the number that is divisible by 4 to s4. + s4.add(number) + +# Display the sets. +print(s2) # set 2 +print(s3) # set 3 +print(s4) # set 4 + +# Display if s3 is a subset of s2 (False). +print(s3.issubset(s2)) +# Display if s4 is a subset of s2 (True). +print(s4.issubset(s2)) + +# Create a set with letters in 'Python' and add 'i' to the set. +python_set = set() +for letter in 'Python': + python_set.add(letter) +python_set.add('i') + +# Display the set. +print(python_set) + +# Create a frozenset with the letters in 'marathon'. +frozenset = set() +for letter in 'marathon': + frozenset.add(letter) + +# Display the set. +print(frozenset) + +# Display the union and intersection of the two sets. +print(python_set.union(frozenset)) +print(python_set.intersection(frozenset)) + + + + + + + diff --git a/students/ChiHo/session05/exceptions_lab.py b/students/ChiHo/session05/exceptions_lab.py new file mode 100644 index 0000000..d20fdaa --- /dev/null +++ b/students/ChiHo/session05/exceptions_lab.py @@ -0,0 +1,17 @@ +# Exceptions Lab +# Student: Chi Kin Ho +# Date: Sunday, February 7, 2016 + + +def safe_input(): + try: + data = input("Enter a value: ") + except (KeyboardInterrupt, EOFError) : + return None + else: + return data + + +data = safe_input() +print(data) + diff --git a/students/ChiHo/session06/trapz.py b/students/ChiHo/session06/trapz.py new file mode 100644 index 0000000..c416125 --- /dev/null +++ b/students/ChiHo/session06/trapz.py @@ -0,0 +1,73 @@ +# Week 6 - Lab #1: Trapezoidal Rule +# Date: Friday, February 12, 2016 +# Student: Chi Kin Ho +import math + + +def trapezoidal_rule(function, x1, x2, *coefficients): + """ + calculates the area of a trapezoidal between x = x1 and x = x2 + + :param function: the height of the trapezoid represented by a function + :param a: left-most x-coordinate at x = x1 + :param b: right-most x-coordinate at x = x2 + :param: coefficients: the list of coefficients of the function + :return: the area of the trapezoid + """ + return (x2 - x1) * (function(x1, *coefficients)+function(x2, *coefficients))/2 + + +def line(x, m=1, B=0): + """ + a very simple straight horizontal line at y = mx+B + :param x: the x-coordinate + :param m: the slope of the line + :param B: the y-intercept of the line + :return: the y-coordinate at the x-coordinate + """ + return m*x + B + + +def quadratic(x, A=0, B=0, C=0): + """ + Evaluates a quadratic equation at x + :param x: the x-coordinate + :param A: the A coefficient of the quadratic function + :param B: the B coefficient of the quadratic function + :param C: the C coefficient of the quadratic function + :return: the y-coordinate of the quadratic function evaluated at x + """ + return A * x**2 + B * x + C + + +def trapz(function, a, b, h, *coefficients): + """ + Compute the area under the curve defined by + y = function(x), for x between a and b + + :param function: the function to evaluate + :param a: the start point for teh integration + :param b: the end point for the integration + :param h: the step size of the trapezoid + :param coefficients: the list of coefficients of the function + :return: the area under the function from a to b with the step size of h + """ + + area = 0 # the area under a function + while a < b: + # Calculate the area of a trapezoid. + area += trapezoidal_rule(function, a, a+h, *coefficients) + # Update the lower bound. + a += h + return area + + +if __name__ == '__main__': + print(trapz(line, 0, 10, 0.5)) + print(trapz(line, 0, 10, 0.5, 2, 5)) + print(trapz(quadratic, 0, 1, 0.5, 1)) + print(trapz(quadratic, 0, 1, 0.1, 1)) + print(trapz(quadratic, 0, 1, 0.01, 1)) + print(trapz(quadratic, 0, 1, 0.001, 1)) + print(trapz(quadratic, 2, 20, 0.001, 1, 3, 2)) + print(trapz(math.sin, 2, 20, 0.001)) diff --git a/students/ChiHo/session06/weapon.py b/students/ChiHo/session06/weapon.py new file mode 100644 index 0000000..3536b5c --- /dev/null +++ b/students/ChiHo/session06/weapon.py @@ -0,0 +1,35 @@ +# Weapon Lab +# Student: Chi Kin Ho +# Date: Wednesday, February 17, 2016 + + +def hand_weapon(size): + if size == 'small': + return 1 + elif size == 'medium': + return 2 + else: + return 3 + + +def gun(size): + if size == 'small': + return 5 + elif size == 'medium': + return 8 + else: + return 13 + + +def flower_power(size): + if size == 'small': + return 21 + elif size == 'medium': + return 34 + else: + return 55 + + +def score(weapon_type, weapon_size): + return weapon_type(weapon_size) + diff --git a/students/ChiHo/session07/html_render.py b/students/ChiHo/session07/html_render.py new file mode 100644 index 0000000..44ee705 --- /dev/null +++ b/students/ChiHo/session07/html_render.py @@ -0,0 +1,180 @@ +# Week 7 - Lab #1: HTML Renderer Exercise +# Date: Friday, February 19, 2016 +# Student: Chi Kin Ho + +# !/usr/bin/env python + +""" +Python class example. +""" + +# The start of it all: +# Fill it all in here. + + +class Element(object): + + tag = 'html' # class attribute + level = 1 # indentation level + + def __init__(self, content=None, **kwargs): + # Initialize the Element object with the given content. + if content is None: + self.content = list() + else: + self.content = [content] + + if kwargs is not None: + if 'style' in kwargs: + self.style = kwargs['style'] + else: + self.style = None + + if 'id' in kwargs: + self.id = kwargs['id'] + else: + self.id = None + + def append(self, new_content): + # Append the new_content to the end of the existing content. + self.content.append(new_content) + + def render(self, file_out, ind=""): + + file_out.write(ind * Element.level + '<' + self.tag) + + if self.style is not None: + file_out.write(' ' + 'style="' + self.style + '"') + if self.id is not None: + file_out.write(' ' + 'id="' + self.id + '"') + + file_out.write('>\n') + + for content in self.content: + if isinstance(content, str): # Stop the recursion when content is of string. + file_out.write(ind * (Element.level + 1) + content + '\n') + else: # Recursively call render() to print the tag element. + Element.level += 1 + content.render(file_out, ind) + Element.level -= 1 + + file_out.write(ind * Element.level + '') + + if self.tag != 'html': + file_out.write('\n') + + +class Html(Element): + + tag = 'html' # Override the Element's class attribute with html + + def render(self, file_out, ind=""): + + file_out.write('' + '\n') + Element.render(self, file_out, ind) + + +class Body(Element): + + tag = 'body' # Override the Element's class attribute with body + + +class P(Element): + + tag = 'p' # Override the Element's class attribute with p + + +class Head(Element): + + tag = 'head' # Override the Element's class attribute with head + + +class OneLineTag(Element): + + def render(self, file_out, ind=""): + + file_out.write(ind * Element.level + '<' + self.tag + '>') + file_out.write(' ' + self.content[0] + ' ') + file_out.write('' + '\n') + + +class Title(OneLineTag): + + tag = 'title' # Override the OneLineTag's class attribute with title + + +class SelfClosingTag(Element): + + def render(self, file_out, ind=""): + + file_out.write(ind * Element.level + '<' + self.tag + ' />' + '\n') + + +class Hr(SelfClosingTag): + + tag = 'hr' # Override the SelfClosingTag's class attribute with hr + + +class Br(SelfClosingTag): + + tag = 'br' # Override the SelfClosingTag's class attribute with br + + +class Meta(SelfClosingTag): + + tag = 'meta' # Override the SelfClosingTag's class attribute with meta + + def __init__(self, **kwargs): + + Element.__init__(self, None) + if 'charset' in kwargs: + self.charset = kwargs['charset'] + + def render(self, file_out, ind=""): + + file_out.write(ind * Element.level + '<' + self.tag + ' charset="' + self.charset + '" />' + '\n') + + +class A(Element): + + tag = 'a' # Override the Element's class attribute with a + + def __init__(self, link, content=None): + + Element.__init__(self, content) + self.link = link # Store the hyperlink of the anchor tag. + + def render(self, file_out, ind=""): + + file_out.write(ind * Element.level + '<' + self.tag + ' href="' + self.link + '">') + + for content in self.content: + if isinstance(content, str): # Stop the recursion when content is of string. + file_out.write(' ' + content + ' ') + else: # Recursively call render() to print the tag element. + Element.level += 1 + content.render(file_out, ind) + Element.level -= 1 + + file_out.write('\n') + + +class Ul(Element): + + tag = 'ul' # Override the Element's class attribute with ul + + +class Li(Element): + + tag = 'li' # Override the Element's class attribute with li + + +class H(OneLineTag): + + tag = 'h' # Override the OneLineTag's class attribute with h2 + + def __init__(self, size, content=None, **kwargs): + + self.tag += str(size) # Add the size of the header to the tag name + Element.__init__(self, content, **kwargs) + diff --git a/students/ChiHo/session07/run_html_render.py b/students/ChiHo/session07/run_html_render.py new file mode 100644 index 0000000..5bd0f79 --- /dev/null +++ b/students/ChiHo/session07/run_html_render.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python + +""" +a simple script can run and test your html rendering classes. + +Uncomment the steps as you add to your rendering. + +""" + +from io import StringIO + +# importing the html_rendering code with a short name for easy typing. +import html_render as hr +# reloading in case you are running this in iPython +# -- we want to make sure the latest version is used +import importlib +importlib.reload(hr) + + +# writing the file out: +def render_page(page, filename): + """ + render the tree of elements + + This uses StringIO to render to memory, then dump to console and + write to file -- very handy! + """ + + f = StringIO() + page.render(f, " ") + + f.seek(0) + + print(f.read()) + + f.seek(0) + open(filename, 'w').write(f.read()) + + +# Step 1 +######### + +# page = hr.Element() + +# page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text") + +# page.append("And here is another piece of text -- you should be able to add any number") + +# render_page(page, "test_html_output1.html") + +# ## Step 2 +# ########## + +# page = hr.Html() + +# body = hr.Body() + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) + +# body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +# page.append(body) + +# render_page(page, "test_html_output2.html") + +# # Step 3 +# ########## + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +# body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +# page.append(body) + +# render_page(page, "test_html_output3.html") + +# # Step 4 +# ########## + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# page.append(body) + +# render_page(page, "test_html_output4.html") + +# # Step 5 +# ######### + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# page.append(body) + +# render_page(page, "test_html_output5.html") + +# # Step 6 +# ######### + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# body.append("And this is a ") +# body.append( hr.A("http://google.com/", "link") ) +# body.append("to google") + +# page.append(body) + +# render_page(page, "test_html_output6.html") + +# # Step 7 +# ######### + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append( hr.H(2, "PythonClass - Class 6 example") ) + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# list = hr.Ul(id="TheList", style="line-height:200%") + +# list.append( hr.Li("The first item in a list") ) +# list.append( hr.Li("This is the second item", style="color: red") ) + +# item = hr.Li() +# item.append("And this is a ") +# item.append( hr.A("http://google.com/", "link") ) +# item.append("to google") + +# list.append(item) + +# body.append(list) + +# page.append(body) + +# render_page(page, "test_html_output7.html") + +# # Step 8 +# ######## + +page = hr.Html() + + +head = hr.Head() +head.append( hr.Meta(charset="UTF-8") ) +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append( hr.H(2, "PythonClass - Class 6 example") ) + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +list = hr.Ul(id="TheList", style="line-height:200%") + +list.append( hr.Li("The first item in a list") ) +list.append( hr.Li("This is the second item", style="color: red") ) + +item = hr.Li() +item.append("And this is a ") +item.append( hr.A("http://google.com/", "link") ) +item.append("to google") + +list.append(item) + +body.append(list) + +page.append(body) + +render_page(page, "test_html_output8.html") diff --git a/students/DeanaHolmer/Boto Library.pptx b/students/DeanaHolmer/Boto Library.pptx new file mode 100644 index 0000000..492b420 Binary files /dev/null and b/students/DeanaHolmer/Boto Library.pptx differ diff --git a/students/DeanaHolmer/README.rst b/students/DeanaHolmer/README.rst new file mode 100644 index 0000000..4b87f6a --- /dev/null +++ b/students/DeanaHolmer/README.rst @@ -0,0 +1 @@ +This is Deana's Readme. It is a good Readme. diff --git a/students/DeanaHolmer/session02/fizzbuzz.py b/students/DeanaHolmer/session02/fizzbuzz.py new file mode 100644 index 0000000..daaddd4 --- /dev/null +++ b/students/DeanaHolmer/session02/fizzbuzz.py @@ -0,0 +1,23 @@ +# Deana Holmer +# UWPCE Python 2016 Winter +# "fizzbuzz.py" due 1/21/2016 +# In this exercise we count from 1-100, printing "fizz" +# instead of number for multiples of 3, +# "buzz" instead of number for multiples of 5 +# and "fizzbuzz" instead of number for multiples of 3 and 5 + +import os +os.chdir('C:\\Documents\\Python\\python35src\\UWPython1\\week2') + +# do you know how to ask the user for input instead of hard-coding these variables? +fizznum = 3 +buzznum = 5 +for i in range(1, 101): + if i % (fizznum * buzznum) == 0: # could you also use an 'OR' here? + print("fizzbuzz") + elif i % fizznum == 0: + print("fizz") + elif i % buzznum == 0: + print("buzz") + else: + print(i) diff --git a/students/DeanaHolmer/session02/grid-printer.py b/students/DeanaHolmer/session02/grid-printer.py new file mode 100644 index 0000000..87a1574 --- /dev/null +++ b/students/DeanaHolmer/session02/grid-printer.py @@ -0,0 +1,34 @@ +# Deana Holmer +# UWPCE Python 2016 Winter +# "grid-printer.py" due 1/21/2016 +# In this exercise we draw blocks using functions, loops and string +# manipulation + +import os +os.chdir('C:\\Documents\\Python\\python35src\\UWPython1\\week2') + + +def block_ceiling(num_blocks_across, block_width): + print_line = '+' + for i in range(0, num_blocks_across): + print_line = print_line + ' -' * block_width + ' +' + return print_line + + +def block_wall(num_blocks_across, block_width): + print_line = '|' + for i in range(0, num_blocks_across): + print_line = print_line + ' ' * block_width + ' |' + return print_line + +# parameters +block_width = 4 +block_height = 4 +num_blocks_across = 2 +num_blocks_down = 2 + +for i in range(0, num_blocks_down): + print(block_ceiling(num_blocks_across, block_width)) + for j in range(0, block_height): + print(block_wall(num_blocks_across, block_width)) +print(block_ceiling(num_blocks_across, block_width)) diff --git a/students/DeanaHolmer/session02/series.py b/students/DeanaHolmer/session02/series.py new file mode 100644 index 0000000..ce3f6b2 --- /dev/null +++ b/students/DeanaHolmer/session02/series.py @@ -0,0 +1,56 @@ +# Deana Holmer +# UWPCE Python 2016 Winter +# "series.py" due 1/21/2016 +# In this exercise we compute finbonacci series +import os +os.chdir('C:\\Documents\\Python\\python35src\\UWPython1\\week2') + + +def fibonacci(n): + """Compute and return next number in fibonacci sequence.""" + if n <= 1: + return n + else: + return (fibonacci(n - 1) + fibonacci(n - 2)) + + +def lucas(n): + """Compute and return next number in lucas sequence.""" + if n == 0: + return 2 + elif n == 1: + return 1 + else: + return (lucas(n - 1) + lucas(n - 2)) + +def sum_series(n, a=0, b=1): + """Decide on fibonacci lucas or other series and run it.""" + if a == 0 and b == 1: + return fibonacci(n) + elif a == 2 and b == 1: + return lucas(n) + else: + return None + +# test it +nterms = 10 + +print ("Test fibonacci") +for i in range(nterms): + print(fibonacci(i)) + +print ("Test lucas") +for i in range(nterms): + print(lucas(i)) + +print ("Test sum_series with defaults") +for i in range(nterms): + print(sum_series(i)) + +print ("Test sum_series with lucas params") +for i in range(nterms): + print(sum_series(i,2,1)) + +print ("Test sum_series with other params") +for i in range(nterms): + print(sum_series(i,4,5)) diff --git a/students/DeanaHolmer/session03/rot13.py b/students/DeanaHolmer/session03/rot13.py new file mode 100644 index 0000000..b6bf348 --- /dev/null +++ b/students/DeanaHolmer/session03/rot13.py @@ -0,0 +1,15 @@ +"""rot13.py""" +import string + +def rot13 (str): + """Translate str by mapping alphachars from intab to chars 13 ascii positions away in outtab""" + intab = "abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + outtab = "nopqrstuvwzyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM" + + return str.translate(str.maketrans(intab,outtab)) + +#Assigned string to translate +print(rot13("Zntargvp sebz bhgfvqr arne pbeare")) + +#General Test +print(rot13("The Quick Brown Fox Jumped Over The Lazy Dog")) diff --git a/students/DeanaHolmer/session04/mailroom.py b/students/DeanaHolmer/session04/mailroom.py new file mode 100644 index 0000000..04bb4bf --- /dev/null +++ b/students/DeanaHolmer/session04/mailroom.py @@ -0,0 +1,69 @@ +"""mailroom.py + Deana Holmer + Practice with Dictionaries, User Input and Strings""" + +# one way to populate tuple-like dictionary with initial values +donors = \ + { 'Chuck': [100,200,300], + 'Mary': [50], + 'Todd': [50,100], + 'Janet': [200,300], + 'Bob': [10,20,30] + } +# alternate method +menu = {} +menu ['1']="Send a Thank You" +menu ['2']="Create a Report" + +def main_menu(menu): + """Print main menu and return selection.""" + for option in sorted(menu.keys()): + print ("{}: {}".format(option, menu[option])) + return(input('Select option> ')) + +def donor_menu(donors): + """Print donor menu and return selected name. Print donor list. Add new donor to list. Return name.""" + name=input("Select donor> ") + if name.lower() == 'list': + name=input("Select donor: {} > ".format(sorted(donors.keys()))) + if name not in donors.keys(): + donors.setdefault(name, None) + return(name) + +def donate(donor_name, donors): + """Get donation amount from user and add to donor dictionary. Return amount.""" + amt="" + while not amt.isdigit(): + amt=input("Donation amount> ") + donors[donor_name].append(int(amt)) + return(amt) + +def thanks (donor_name, donation_amt): + """Generate thank you letter for donation. Return text.""" + return ("\nDear {}.\n\tThank you for your donation of ${}. \nSincerely,\n\tUs\n".format(donor_name, donation_amt)) + +def report(donor_name,donations): + """Generate donor report""" + ttl= sum(amt for amt in donations) + cnt= len(donations) + avg= int(ttl/cnt) + return "{}\t{}\t{}\t{}".format(donor_name, ttl, cnt, avg) + + + +if __name__ == '__main__': + """Present Main Menu and Perform Requested Actions.""" + while True: + option=main_menu(menu) + if option== '1': + donor_name= donor_menu(donors) + donation_amt=donate(donor_name, donors) + print(thanks(donor_name, donation_amt)) + elif option=='2': + print("Name\tTotal\tNum\tAvgAmt") + for donor_name in donors.keys(): + print(report(donor_name, donors[donor_name])) + else: + break + + diff --git a/students/DeanaHolmer/session05/files-lab.py b/students/DeanaHolmer/session05/files-lab.py new file mode 100644 index 0000000..f2ccbdb --- /dev/null +++ b/students/DeanaHolmer/session05/files-lab.py @@ -0,0 +1,31 @@ +"""Deana Holmer""" +"""files-lab.py""" +import os +cwd=os.getcwd() +DATAINFILENAME=os.path.join(cwd,'students.txt') +DATAOUTFILENAME=os.path.join(cwd,'students.out') + +with open(DATAINFILENAME,'r') as inf, open (DATAOUTFILENAME, 'w') as outf: + students={} + languages={} + for each_line in inf: + try: + (name, langstr) = each_line.split(':',1) + students[name]=langstr.split(',') + for each_lang in students[name]: + each_lang=each_lang.strip() + if each_lang not in languages.keys(): + languages.setdefault(each_lang, 1) + else: + languages[each_lang] +=1 + except ValueError: + if len(each_line) > 1: + outf.write('#ValueError# ' + each_line) + for name in students: + outf.write(name + '\n') + outf.write('\t' + str(students[name]) + '\n') + + for l in languages: + print ('{}:\t{}'.format(l, languages[l])) + + diff --git a/students/JohnRudolph/README.rst b/students/JohnRudolph/README.rst new file mode 100644 index 0000000..149d7af --- /dev/null +++ b/students/JohnRudolph/README.rst @@ -0,0 +1 @@ +# Python code for UWPCE-PythonCert class for John Rudolph \ No newline at end of file diff --git a/students/JohnRudolph/lab2/fizzbuzz.py b/students/JohnRudolph/lab2/fizzbuzz.py new file mode 100644 index 0000000..6a822e0 --- /dev/null +++ b/students/JohnRudolph/lab2/fizzbuzz.py @@ -0,0 +1,20 @@ +#createe fizzbuzz function +def fizzbuzz(start, stop): + #need to +1 to stop in order to print last number + for i in range(start, stop +1): + #set string to null + str = '' + if i % 3 !=0 and i % 5 != 0: print(i) + else: + if (i % 3) == 0: str = 'Fizz' + if (i % 5) == 0: str = str + 'Buzz' + print(str) + +#make sure input is entered as an integer +try: + stop = int(input('Input last integer in range: ')) + fizzbuzz(1, stop) +except: + print('You did not enter that value as an integer! Try again') + +# what happens if I input a 0? diff --git a/students/JohnRudolph/lab2/moneycount.py b/students/JohnRudolph/lab2/moneycount.py new file mode 100644 index 0000000..e55c6b0 --- /dev/null +++ b/students/JohnRudolph/lab2/moneycount.py @@ -0,0 +1,20 @@ + +def moneycount(p, n, d, q): + #get total cash input based on int entered for each coin type + totalcash = .01 * p + n *.05 + d * .10 + q * .25 + if totalcash == 1: + print('You have won the game') + elif totalcash < 1: print('Your total change is less than a dollar') + else: print('Your total change is greater than a dollar') + +#ask for input - make sure an int is enetered for each coin type +try: + p = int(input('# of pennies: ')) + n = int(input('# of nickels: ')) + d = int(input('# of dimes: ')) + q = int(input('# of quarters: ')) + + moneycount(p, n, d, q) + +except: + print('You did not enter that value as an integer! Try again') \ No newline at end of file diff --git a/students/JohnRudolph/lab2/series.py b/students/JohnRudolph/lab2/series.py new file mode 100644 index 0000000..5d16be9 --- /dev/null +++ b/students/JohnRudolph/lab2/series.py @@ -0,0 +1,55 @@ + +def fibonacci(n): + ''' + This function creates a fibonacci sequence and returns the last number in series based on input 'n' + The sequnece generates a new number based on sum of previous 2 numbers in the sequence + Sequence starts n = 1 return 0 and n = 2 return 1 + Sequence can populate recursively when n > 2 + ''' + if n == 1: + fib = 0 + return fib + elif n == 2: + fib = 1 + return fib + else: + fib = fibonacci(n-1) + fibonacci(n-2) + return fib + +def lucas(n): + ''' + This function creates lucas numbers and returns the last number in series based on input 'n' + The sequnece generates a new number based on sum of previous 2 numbers in the sequence + Same logic as fibonacci but sequence starts n = 1 return 2 and n = 2 return 1 + Sequence can populate recursively when n > 2 + ''' + if n == 1: + luc = 2 + return luc + elif n == 2: + luc = 1 + return luc + else: + luc = lucas(n-1) + lucas(n-2) + return luc + +def sum_series(n, int1=0, int2=1): + ''' + This function creates a recursive series similar to fibonacci and lucas functions + Except it accepts optional input parameters that determin which 2 values are used to start sequence + If optional parameters are left blank then fibonacci starting values are used + ''' + if n == 1: + s = int1 + return s + elif n == 2: + s = int2 + return s + else: + s = sum_series(n-1, int1, int2) + sum_series(n-2, int1, int2) + return s + +print(fibonacci(8), lucas(8), sum_series(8,2,1)) + + + diff --git a/students/JohnRudolph/session3/list_lab.py b/students/JohnRudolph/session3/list_lab.py new file mode 100644 index 0000000..bda0540 --- /dev/null +++ b/students/JohnRudolph/session3/list_lab.py @@ -0,0 +1,180 @@ +#!/usr/bin/python3.4 + +''' +######################################################################### + SECTION 1 OF LIST LAB +######################################################################### + +#1 Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches” +#2 Display the list +#3 Ask the user for another fruit and add it to the end of the list +#4 Display the list +#5 Ask the user for a number and display the number back to the user and + the fruit corresponding to that number (on a 1-is-first basis) +#6 Add another fruit to the beginning of the list using “+” and display the list +#7 Add another fruit to the beginning of the list using insert() and display the list +#8 Display all the fruits that begin with “P”, using a for loop +''' + +#1 +fruit = ["Apples", "Pears", "Oranges", "Peaches"] + +#2 +print(fruit) + +#3 +new_fruit = input("Add another fruit to list\n") + +fruit.append(new_fruit) + +#4 +print(fruit) + +#5 +#Add an error handler so that user has to input a valid list index +index_check = None +while index_check is None: + try: + get_num = int(input("Select a number from 1 to " + str(len(fruit)) + " inclusive\n")) + print(get_num, " ", fruit[get_num - 1]) + index_check = True + except: + print("Invalid index number try again") + +#6 +new_fruit = [input("Add another new fruit to list\n")] + +fruit = new_fruit + fruit + +print("List with ", new_fruit[0],"\n", fruit) + +#7 +new_fruit = input("Add another fruit to list\n") + +fruit.insert(0,new_fruit) + +print("List with ", new_fruit,"\n", fruit) + +#8 +#create empty list to hold values that will be populated in loop below +p_fruits = [] + +#loop over each fruit in list and determine if fruit starts with p (not case sensitive) +for item in fruit: + if item[0].lower() == "p": + p_fruits.append(item) + +print("List of fruits that start with P\n", p_fruits) + + +''' +######################################################################### + SECTION 2 OF LIST LAB +######################################################################### + +#9 Display the list. +#10 Remove the last fruit from the list. +#11 Display the list. +#12 Ask the user for a fruit to delete and find it and delete it. +#13 Bonus: Multiply the list times two. Keep asking until a match is found. + Once found, delete all occurrences.) +''' + +#9 +print("Current fruit list\n", fruit) + +#10 +#creating a new list called fruit 2 based on list from section 1 +fruit2 = list(fruit) +del fruit2[-1] + +#11 +print("Deleted the last item from list\n", fruit2) + +#12 +#Add an error handler so that user has to input a valid list index +index_check = None +while index_check is None: + try: + get_str = input("Type a fruit from current list to delete\n") + fruit2.remove(get_str) + index_check = True + except: + print("The fruit you typed in not in the list! Try again ") + +print("You deleted ", get_str, "New list\n", fruit2) + +#13 - Doing this on the deleted list from #12 +''' +First while loop checks to see if fruit entered exists in list +If fruit does exist in list the loop through list until all instance of fruit is removed +If fruit does not exist in list then copy fruit list and append to existing list +''' +index_check = None #flag to determine if a valid fruit has been entered +while index_check is None: + get_str = input("Type the fruit from current list to delete\n") + if get_str in fruit2: + while get_str in fruit2: + fruit2.remove(get_str) + index_check = True #set flag to True to quit valid fruit loop + else: + fruit2_copy = list(fruit2) + fruit2 = fruit2_copy + fruit2_copy + print("The fruit you typed in not in the list so I doubled the list! Try again ") + print(fruit2) + +print("You deleted ", get_str,"\n", fruit2) + +''' +######################################################################### + SECTION 3 OF LIST LAB +######################################################################### +#14 Ask the user for input displaying a line like “Do you like apples?” +#15 Display the list. +''' + +#14 +for item in fruit: + ''' + For each item in fruit list prompt a response from user + If reponse is not yes or no then retry + Else if no then remove item from list + ''' + response = input("Do you like " + item.lower() + " ?\n") + + while response.lower() not in ["yes", "no"]: + print("You didn't answer Yes or No! Try again. ") + response = input("Do you like " + item.lower() + " ?\n") + + if response == 'no': + fruit.remove(item) +#15 +print(fruit) + +''' +######################################################################### + SECTION 4 OF LIST LAB +######################################################################### +#16 Make a copy of the list and reverse the letters in each fruit in the copy. +#17 Delete the last item of the original list. Display the original list and the copy. +''' +#16 +fruit_copy = list(fruit) + +for item in fruit_copy[:]: + item_flip = item[::-1] + fruit_copy.remove(item) + fruit_copy.append(item_flip) + +#17 +del fruit[-1] + +print(fruit) +print(fruit_copy) + + + + + + + diff --git a/students/JohnRudolph/session3/mailroom.py b/students/JohnRudolph/session3/mailroom.py new file mode 100644 index 0000000..5d34437 --- /dev/null +++ b/students/JohnRudolph/session3/mailroom.py @@ -0,0 +1,199 @@ + +''' +################################################################################ +GENERATE RANDOM DONOR LIST +################################################################################ +''' + + +def createDonors(numDonors): + ''' + This function is used to create a donorlist + Input desired number of into donorlist function + For each donor input function will randomly generate_ + # of donations between 1-3 + And randomly generate a donation amount between 100-1000 + Will return a list of lists + ''' + + donorList = [] + + for x in range(numDonors): + + # random # of donations between 1-3 inclusive + numDonations = random.randint(1, 3) + # list that holds donor name and donations amounts + donsubList = ['donor name' + str(x + 1)] + + # create random donations amounts between $100-$1K + for y in range(numDonations): + donsubList.append(random.randint(100, 1000)) + + donorList.append(donsubList) + + return donorList + +''' +################################################################################ +GENERAL FUNCTIONS +################################################################################ +''' + + +def actionPrompt(): + ''' + This function prompts a user to select an action: + "Send thank you" or "create a report" + Function will loop until one of these is entered + ''' + index_check = None + while index_check is None: + getAction = str( + input("Input Action: 'Send a Thank You'\t'Create a Report'\t'Quit'\n")) + if getAction.lower() not in ['send a thank you', 'create a report', 'quit']: + print("Invalid Action: Try Again!") + else: + index_check = True + return getAction + +''' +################################################################################ +THANK YOU FUNCTIONS +################################################################################ +''' + + +def appendDonor(getName): + ''' + This functions find the donor in the dictionary + Prompts user for new donations and appends donation to the dictionary key + If user does not enter a number then error will be raised + ''' + donCheck = None + while donCheck is None: + try: + donation = int(input('Enter donation amount (int) for {}:\n'.format(getName))) + ownerDic.setdefault(getName, []).append(donation) + print(getName, ownerDic[getName]) + donCheck = True + except: + print('You did not enter a valid integer Try Again!') + + +def sendThanks(getName): + ''' + This function runs the steps for sending a thank your + If user select list then print current donor dic and reprompt + If donor is already in dic then append amounts + If donor not in dic then append new donor and add amount + ''' + if getName.lower() == 'list': + for key in sorted(ownerDic): + print(key) + getName = input("Input a full name or 'list'\n") + sendThanks(getName) + elif getName in ownerDic.keys(): + print('Adding a new donation for: {}'.format(getName)) + appendDonor(getName) + emailThanks(getName) + elif getName == 'quit': + print('Quitting Thank You') + else: + print('Adding {} to Donor Database'.format(getName)) + ownerDic.setdefault(getName, []) + appendDonor(getName) + emailThanks(getName) + + +def emailThanks(getName): + ''' + This function grabs the last donation entered for a given donor + Print a thank you message with donor name and donation amount + ''' + donationList = list(ownerDic[getName]) + print('Thank you {} for your generous donation of ${}!'.format( + getName, donationList[-1])) + +''' +################################################################################ +DONORS REPORT FUNCTIONS +################################################################################ +''' + + +def getKey(item): + ''' + Function used to sort second item in a list of lists + ''' + return item[1] + + +def createtopDonors(): + ''' + Creates a new list with total donations, donation count and avg donations + by looping over master donor dictionary + New list is sorted based on total donation + ''' + sortList = [] + for key in ownerDic: + totalDon = sum(list(ownerDic[key])) + countDon = len((list(ownerDic[key]))) + avgDon = int(totalDon / countDon) + sortList.append([key, totalDon, countDon, avgDon]) + + return(sorted(sortList, key=getKey, reverse=True)) + + +def outputTopDonors(topDonors): + ''' + This function loops through the sorted top donors list + And prints each itemn in tabular format + ''' + print('Donor Name\tTotal\tCount\tAverage') + for x in topDonors: + print('{}\t{}\t{}\t{}'.format(*x)) + + +''' +################################################################################ +MAIN CODE BLOCK +################################################################################ +''' +if __name__ == '__main__': + + import random + + check = None + while check is None: + try: + # create an arbitrary # of donors - 5 per assignment directions + numDonors = int( + input('Enter number (int) of donors to generate\n')) + check = True + except: + print('You did not enter a valid int - Try again!') + + # create the initial list of donors + donorList = createDonors(numDonors) + # create an empty dictionary - will be populated in loop below + ownerDic = {} + # populate donor dict from donorlist + for donor in donorList: + donor_name = donor[0] + donations = donor[1:] + ownerDic[donor_name] = donations + + # flag used to quit prompting user for an action + quit_check = False + + while quit_check is False: + getAction = actionPrompt() + if getAction.lower() == 'send a thank you': + getName = input("Input a full name or 'list'\n") + sendThanks(getName) + elif getAction.lower() == 'create a report': + topDonors = createtopDonors() + outputTopDonors(topDonors) + elif getAction.lower() == 'quit': + print('Quitting Program!') + quit_check = True diff --git a/students/JohnRudolph/session3/rot13.py b/students/JohnRudolph/session3/rot13.py new file mode 100644 index 0000000..aeee5e4 --- /dev/null +++ b/students/JohnRudolph/session3/rot13.py @@ -0,0 +1,53 @@ + +def getnumref(let): + ''' + This function accepts any ASCII character + Function to create ASCII reference for ROT13 encryption + First if checks if letter is Upcase A-Z and performs ROT13 + Second if checks if letter is Lowcase a-z and performs ROT13 + If not Upcase or Lowcase A-Z or a-z then retain ordinal of character + ''' + if ord("A") <= ord(let) <= ord('Z'): # nice use of ord! + if ord(let) + 13 <= ord('Z'): + return ord(let) + 13 + else: + return ord(let) - ord('Z') + ord('A') +12 + elif ord('a') <= ord(let) <= ord('z'): + if ord(let) + 13 <= ord('z'): + return ord(let) + 13 + else: + return ord(let) - ord('z') + ord('a') + 12 + else: + return ord(let) + + +def rot13(string): + ''' + This function accepts a string arguement and loops through each character in string + Each character string is passed to getnumref function for ROT13 encryption + Each ROT13 encrypted character is appended to list and joined to create string + ''' + str_container = [] + for let in string: + str_container.append(chr(getnumref(let))) + s = ''.join(str_container) + return s + + +if __name__ == '__main__': + print('Zntargvp sebz bhgfvqr arne pbeare', 'ROT13: ', + rot13('Zntargvp sebz bhgfvqr arne pbeare')) + + print('Blajhkajhds!!! *&^*&^*^POP', 'ROT13: ', + rot13('Blajhkajhds!!! *&^*&^*^POP')) + + print('1111 22222 AAAA ZZZZ aaa zzzzz', 'ROT13: ', + rot13('1111 22222 AAAA ZZZZ aaa zzzzz')) + + print('abcdefghijklmnopqrstuvwxyz', 'ROT13: ', + rot13('abcdefghijklmnopqrstuvwxyz')) + + print('lmnop LMNOP', 'ROT13: ', + rot13('lmnop LMNOP')) + + diff --git a/students/JohnRudolph/session3/slicelab.py b/students/JohnRudolph/session3/slicelab.py new file mode 100644 index 0000000..090b42d --- /dev/null +++ b/students/JohnRudolph/session3/slicelab.py @@ -0,0 +1,43 @@ +s1 = list(range(1,20)) + +#1 +def exchange(lst): + fst = lst[-1] + mid = list(lst[1:-1]) + fin = lst[0] + print(fst, mid, fin) + +print(exchange(s1)) +#2 +def everyother(lst): + for n in lst: + if n % 2 == 0: + print(n) + +print(everyother(s1)) +#3 +def everyother4(lst): + lst2 = lst[3:-4] + for n in lst2: + if n % 2 == 0: + print(n) + +print(everyother4(s1)) + +print(s1[::2]) + +#4 +print(s1[::-1]) + +#5 +def thirds(lst): + countlst = len(lst) + fst = lst[0:int(countlst/3)] + mid = lst[int((countlst/3)):int((2*countlst/3))] + fin = lst[-int(2*countlst/3):-int(countlst/3)] + print(fin,mid,fst) + + +print(thirds(s1)) + + diff --git a/students/JohnRudolph/session3/str_lab.py b/students/JohnRudolph/session3/str_lab.py new file mode 100644 index 0000000..1130933 --- /dev/null +++ b/students/JohnRudolph/session3/str_lab.py @@ -0,0 +1,10 @@ +input1 = 2 +input2 = 123.4567 +input3 = 10000 + +print('File_00{} : {:.2f}, {:.0e}'.format(input1, input2, input3)) + +t = (1,2,3,4,5) +brackets = '{} '*len(t) + +print('The first {}'.format(len(t)), 'numbers are:', brackets.format(*t)) diff --git a/students/JohnRudolph/session4/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/students/JohnRudolph/session4/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100644 index 0000000..e1325ef --- /dev/null +++ b/students/JohnRudolph/session4/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,612 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Strings Lab" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "raw_string = r'one\\two'" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'one\\\\two'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "raw_string" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "regular_string = 'one\\two'" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'one\\two'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "regular_string" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Convert to and back from ordinals" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "121\n", + "111\n", + "100\n", + "97\n" + ] + } + ], + "source": [ + "for i in 'yoda':\n", + " print(ord(i))" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "yoda" + ] + } + ], + "source": [ + "for i in (121, 111, 100, 97):\n", + " print(chr(i), end='')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# String Formatting" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "stringa = 'this is a string' " + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello this is a string!'" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {}!'.format(stringa)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "stringb = 'another string'" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello this is a string! another string'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {}! {}'.format(stringa, stringb)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hanging comma is not an error - is goodf to have when have many args for nice formatting" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello another string! this is a string'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {first_string}! {second_string}'.format(second_string=stringa, first_string=stringb, )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# File and Streams" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "with open('test.txt', 'r') as f:\n", + " read_data = f.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "f.closed" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a blank text file\\nIt has some words in it\\nBlah blah blah blah'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_data" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a blank text file\n", + "It has some words in it\n", + "Blah blah blah blah\n" + ] + } + ], + "source": [ + "print(read_data)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# File Lab" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "with open('students.txt', 'r') as s:\n", + " students = s.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "studentsplit = []" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "for word in students.split('\\n'):\n", + " if len(word)>0:\n", + " studentsplit.append(word)" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Bindhu, Krishna: ', 'Bounds, Brennen: English', 'Gregor, Michael: English', 'Holmer, Deana: SQL, English', 'Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl', 'Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL', 'Rudolph, John: English, Python, Sass, R, Basic', 'Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman', 'Warren, Benjamin: English', 'Aleson, Brandon: English', 'Chang, Jaemin: English', 'Chinn, Kyle: English', 'Derdouri, Abderrazak: English', 'Fannin, Calvin: C#, SQL, R', 'Gaffney, Thomas: SQL, Python, R, VBA, English', 'Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby', 'Ganzalez, Luis: Basic, C++, Python, English, Spanish', 'Ho, Chi Kin: English', 'McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley', 'Myerscough, Damian: ', 'Newton, Michael: Python, Perl, Matlab', 'Sarpangala, Kishan: ', 'Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab', 'Zhao, Yuanrui: ']\n" + ] + } + ], + "source": [ + "print(studentsplit)" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "namelan = []\n", + "for word in studentsplit:\n", + " namelan.append(word.split(':')) " + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[['Bindhu, Krishna', ' '], ['Bounds, Brennen', ' English'], ['Gregor, Michael', ' English'], ['Holmer, Deana', ' SQL, English'], ['Kumar, Pradeep', ' English, Hindi, Python, shell, d2k, SQL, Perl'], ['Rees, Susan', ' English, Latin, HTML, CSS, Javascript, Ruby, SQL'], ['Rudolph, John', ' English, Python, Sass, R, Basic'], ['Solomon, Tsega', ' C, C++, Perl, VHDL, Verilog, Specman'], ['Warren, Benjamin', ' English'], ['Aleson, Brandon', ' English'], ['Chang, Jaemin', ' English'], ['Chinn, Kyle', ' English'], ['Derdouri, Abderrazak', ' English'], ['Fannin, Calvin', ' C#, SQL, R'], ['Gaffney, Thomas', ' SQL, Python, R, VBA, English'], ['Glogowski, Bryan', ' Basic, Pascal, C, Perl, Ruby'], ['Ganzalez, Luis', ' Basic, C++, Python, English, Spanish'], ['Ho, Chi Kin', ' English'], ['McKeag, Gregory', ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley'], ['Myerscough, Damian', ' '], ['Newton, Michael', ' Python, Perl, Matlab'], ['Sarpangala, Kishan', ' '], ['Schincariol, Mike', ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab'], ['Zhao, Yuanrui', ' ']]\n" + ] + } + ], + "source": [ + "print(namelan)" + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Bindhu, Krishna', ' ']\n", + "['Bounds, Brennen', ' English']\n", + "['Gregor, Michael', ' English']\n", + "['Holmer, Deana', ' SQL, English']\n", + "['Kumar, Pradeep', ' English, Hindi, Python, shell, d2k, SQL, Perl']\n", + "['Rees, Susan', ' English, Latin, HTML, CSS, Javascript, Ruby, SQL']\n", + "['Rudolph, John', ' English, Python, Sass, R, Basic']\n", + "['Solomon, Tsega', ' C, C++, Perl, VHDL, Verilog, Specman']\n", + "['Warren, Benjamin', ' English']\n", + "['Aleson, Brandon', ' English']\n", + "['Chang, Jaemin', ' English']\n", + "['Chinn, Kyle', ' English']\n", + "['Derdouri, Abderrazak', ' English']\n", + "['Fannin, Calvin', ' C#, SQL, R']\n", + "['Gaffney, Thomas', ' SQL, Python, R, VBA, English']\n", + "['Glogowski, Bryan', ' Basic, Pascal, C, Perl, Ruby']\n", + "['Ganzalez, Luis', ' Basic, C++, Python, English, Spanish']\n", + "['Ho, Chi Kin', ' English']\n", + "['McKeag, Gregory', ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley']\n", + "['Myerscough, Damian', ' ']\n", + "['Newton, Michael', ' Python, Perl, Matlab']\n", + "['Sarpangala, Kishan', ' ']\n", + "['Schincariol, Mike', ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab']\n", + "['Zhao, Yuanrui', ' ']\n" + ] + } + ], + "source": [ + "lang = {}\n", + "for lan in namelan:\n", + " for i,x in enumerate(lan): " + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{' English, Hindi, Python, shell, d2k, SQL, Perl': ' English, Hindi, Python, shell, d2k, SQL, Perl', ' English, Python, Sass, R, Basic': ' English, Python, Sass, R, Basic', ' Python, Perl, Matlab': ' Python, Perl, Matlab', ' ': ' ', ' SQL, Python, R, VBA, English': ' SQL, Python, R, VBA, English', ' C#, SQL, R': ' C#, SQL, R', ' Basic, Pascal, C, Perl, Ruby': ' Basic, Pascal, C, Perl, Ruby', ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab': ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab', ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley': ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley', ' English, Latin, HTML, CSS, Javascript, Ruby, SQL': ' English, Latin, HTML, CSS, Javascript, Ruby, SQL', ' English': ' English', ' SQL, English': ' SQL, English', ' C, C++, Perl, VHDL, Verilog, Specman': ' C, C++, Perl, VHDL, Verilog, Specman', ' Basic, C++, Python, English, Spanish': ' Basic, C++, Python, English, Spanish'}\n" + ] + } + ], + "source": [ + "print(lang)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Correct way to do this" + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " \n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " SQL, English\n", + "\n", + " English, Hindi, Python, shell, d2k, SQL, Perl\n", + "\n", + " English, Latin, HTML, CSS, Javascript, Ruby, SQL\n", + "\n", + " English, Python, Sass, R, Basic\n", + "\n", + " C, C++, Perl, VHDL, Verilog, Specman\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " C#, SQL, R\n", + "\n", + " SQL, Python, R, VBA, English\n", + "\n", + " Basic, Pascal, C, Perl, Ruby\n", + "\n", + " Basic, C++, Python, English, Spanish\n", + "\n", + " English\n", + "\n", + " C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley\n", + "\n", + " \n", + "\n", + " Python, Perl, Matlab\n", + "\n", + " \n", + "\n", + " Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab\n", + "\n", + " \n", + "\n" + ] + } + ], + "source": [ + "with open('students.txt', 'r') as f:\n", + " for lines in f:\n", + " students_languages = lines.split(':')[1]\n", + " print(students_languages)" + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "language_set = set()\n", + "with open('students.txt', 'r') as f:\n", + " for lines in f:\n", + " students_languages = lines.split(':')[1]\n", + " language_list = students_languages.split(',') \n", + " for item in language_list:\n", + " language_set.add(item)" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{' Basic\\n', ' Ruby', ' Lisp', ' Ruby\\n', ' VHDL', ' SQL', ' Bash', ' C#', ' Latin', ' Python', ' C++', ' Tcl', ' Assembley\\n', ' C', ' Basic', ' R', ' Perl\\n', ' Ada', ' Pascal', ' CSS', ' Sass', ' Scheme', ' shell', ' English\\n', ' Objective-C', ' \\n', ' Spanish\\n', ' Specman\\n', ' English', ' Javascript', ' Perl', ' R\\n', ' Hindi', ' HTML', ' VBA', ' d2k', ' Prolog', ' SQL\\n', ' Verilog', ' Matlab\\n'}\n" + ] + } + ], + "source": [ + "print(language_set)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session4/kata.py b/students/JohnRudolph/session4/kata.py new file mode 100644 index 0000000..e19f226 --- /dev/null +++ b/students/JohnRudolph/session4/kata.py @@ -0,0 +1,64 @@ + +def getnonchars(txtstring): + ''' + Get a list of nonalphachars in string + ''' + nonchar = [] + for word in txtstring.split(' '): + for let in word: + if (ord(let) < ord('A') or ord(let) > ord('z')) and (let not in nonchar): + nonchar.append(let) + return(nonchar) + + +def removenonchar(nonchar, txtstring): + ''' + Removes non alphas from words + ''' + for char in nonchar: + if char in txtstring: + txtstring = txtstring.replace(char, ' ') + return txtstring + + +def splittxtstring(txtstring): + ''' + Splits text string into list of individual words in string + ''' + txtsplit = [] + for word in (txtstring.split(' ')): + if len(word) > 0: + txtsplit.append(word) + + return txtsplit + + +def groupwords(txtsplit): + ''' + Create dictionary with 2 word pairs as key and 3rd word as value + ''' + groupwords = {} + for (i, word) in enumerate(txtsplit): + if i > (len(txtsplit) - 3): + pass + else: + wordpair = '{} {}'.format(txtsplit[i], txtsplit[i + 1]) + wordafter = txtsplit[i + 2] + if wordpair in groupwords: + groupwords[wordpair].append(wordafter) + else: + groupwords['{}'.format(wordpair)] = [wordafter] + return groupwords + +if __name__ == '__main__': + # import txt file for kata trigram + smalltxt = open('sherlock_small.txt.', 'r') + # reat in txt and remove and line returns + txtstring = smalltxt.read().replace('\n', ' ') + # identify nonalpha chars in txt string + nonchars = getnonchars(txtstring) + # remove nonalpha chars from string + ftxtstring = removenonchar(nonchars, txtstring) + # append each word in string to list + txtsplit = splittxtstring(ftxtstring) + print(groupwords(txtsplit)) diff --git a/students/JohnRudolph/session4/notes4.ipynb b/students/JohnRudolph/session4/notes4.ipynb new file mode 100644 index 0000000..e1325ef --- /dev/null +++ b/students/JohnRudolph/session4/notes4.ipynb @@ -0,0 +1,612 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Strings Lab" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "raw_string = r'one\\two'" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'one\\\\two'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "raw_string" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "regular_string = 'one\\two'" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'one\\two'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "regular_string" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Convert to and back from ordinals" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "121\n", + "111\n", + "100\n", + "97\n" + ] + } + ], + "source": [ + "for i in 'yoda':\n", + " print(ord(i))" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "yoda" + ] + } + ], + "source": [ + "for i in (121, 111, 100, 97):\n", + " print(chr(i), end='')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# String Formatting" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "stringa = 'this is a string' " + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello this is a string!'" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {}!'.format(stringa)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "stringb = 'another string'" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello this is a string! another string'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {}! {}'.format(stringa, stringb)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hanging comma is not an error - is goodf to have when have many args for nice formatting" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello another string! this is a string'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Hello {first_string}! {second_string}'.format(second_string=stringa, first_string=stringb, )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# File and Streams" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "with open('test.txt', 'r') as f:\n", + " read_data = f.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "f.closed" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a blank text file\\nIt has some words in it\\nBlah blah blah blah'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "read_data" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a blank text file\n", + "It has some words in it\n", + "Blah blah blah blah\n" + ] + } + ], + "source": [ + "print(read_data)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# File Lab" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "with open('students.txt', 'r') as s:\n", + " students = s.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "studentsplit = []" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "for word in students.split('\\n'):\n", + " if len(word)>0:\n", + " studentsplit.append(word)" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Bindhu, Krishna: ', 'Bounds, Brennen: English', 'Gregor, Michael: English', 'Holmer, Deana: SQL, English', 'Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl', 'Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL', 'Rudolph, John: English, Python, Sass, R, Basic', 'Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman', 'Warren, Benjamin: English', 'Aleson, Brandon: English', 'Chang, Jaemin: English', 'Chinn, Kyle: English', 'Derdouri, Abderrazak: English', 'Fannin, Calvin: C#, SQL, R', 'Gaffney, Thomas: SQL, Python, R, VBA, English', 'Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby', 'Ganzalez, Luis: Basic, C++, Python, English, Spanish', 'Ho, Chi Kin: English', 'McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley', 'Myerscough, Damian: ', 'Newton, Michael: Python, Perl, Matlab', 'Sarpangala, Kishan: ', 'Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab', 'Zhao, Yuanrui: ']\n" + ] + } + ], + "source": [ + "print(studentsplit)" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "namelan = []\n", + "for word in studentsplit:\n", + " namelan.append(word.split(':')) " + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[['Bindhu, Krishna', ' '], ['Bounds, Brennen', ' English'], ['Gregor, Michael', ' English'], ['Holmer, Deana', ' SQL, English'], ['Kumar, Pradeep', ' English, Hindi, Python, shell, d2k, SQL, Perl'], ['Rees, Susan', ' English, Latin, HTML, CSS, Javascript, Ruby, SQL'], ['Rudolph, John', ' English, Python, Sass, R, Basic'], ['Solomon, Tsega', ' C, C++, Perl, VHDL, Verilog, Specman'], ['Warren, Benjamin', ' English'], ['Aleson, Brandon', ' English'], ['Chang, Jaemin', ' English'], ['Chinn, Kyle', ' English'], ['Derdouri, Abderrazak', ' English'], ['Fannin, Calvin', ' C#, SQL, R'], ['Gaffney, Thomas', ' SQL, Python, R, VBA, English'], ['Glogowski, Bryan', ' Basic, Pascal, C, Perl, Ruby'], ['Ganzalez, Luis', ' Basic, C++, Python, English, Spanish'], ['Ho, Chi Kin', ' English'], ['McKeag, Gregory', ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley'], ['Myerscough, Damian', ' '], ['Newton, Michael', ' Python, Perl, Matlab'], ['Sarpangala, Kishan', ' '], ['Schincariol, Mike', ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab'], ['Zhao, Yuanrui', ' ']]\n" + ] + } + ], + "source": [ + "print(namelan)" + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Bindhu, Krishna', ' ']\n", + "['Bounds, Brennen', ' English']\n", + "['Gregor, Michael', ' English']\n", + "['Holmer, Deana', ' SQL, English']\n", + "['Kumar, Pradeep', ' English, Hindi, Python, shell, d2k, SQL, Perl']\n", + "['Rees, Susan', ' English, Latin, HTML, CSS, Javascript, Ruby, SQL']\n", + "['Rudolph, John', ' English, Python, Sass, R, Basic']\n", + "['Solomon, Tsega', ' C, C++, Perl, VHDL, Verilog, Specman']\n", + "['Warren, Benjamin', ' English']\n", + "['Aleson, Brandon', ' English']\n", + "['Chang, Jaemin', ' English']\n", + "['Chinn, Kyle', ' English']\n", + "['Derdouri, Abderrazak', ' English']\n", + "['Fannin, Calvin', ' C#, SQL, R']\n", + "['Gaffney, Thomas', ' SQL, Python, R, VBA, English']\n", + "['Glogowski, Bryan', ' Basic, Pascal, C, Perl, Ruby']\n", + "['Ganzalez, Luis', ' Basic, C++, Python, English, Spanish']\n", + "['Ho, Chi Kin', ' English']\n", + "['McKeag, Gregory', ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley']\n", + "['Myerscough, Damian', ' ']\n", + "['Newton, Michael', ' Python, Perl, Matlab']\n", + "['Sarpangala, Kishan', ' ']\n", + "['Schincariol, Mike', ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab']\n", + "['Zhao, Yuanrui', ' ']\n" + ] + } + ], + "source": [ + "lang = {}\n", + "for lan in namelan:\n", + " for i,x in enumerate(lan): " + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{' English, Hindi, Python, shell, d2k, SQL, Perl': ' English, Hindi, Python, shell, d2k, SQL, Perl', ' English, Python, Sass, R, Basic': ' English, Python, Sass, R, Basic', ' Python, Perl, Matlab': ' Python, Perl, Matlab', ' ': ' ', ' SQL, Python, R, VBA, English': ' SQL, Python, R, VBA, English', ' C#, SQL, R': ' C#, SQL, R', ' Basic, Pascal, C, Perl, Ruby': ' Basic, Pascal, C, Perl, Ruby', ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab': ' Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab', ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley': ' C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley', ' English, Latin, HTML, CSS, Javascript, Ruby, SQL': ' English, Latin, HTML, CSS, Javascript, Ruby, SQL', ' English': ' English', ' SQL, English': ' SQL, English', ' C, C++, Perl, VHDL, Verilog, Specman': ' C, C++, Perl, VHDL, Verilog, Specman', ' Basic, C++, Python, English, Spanish': ' Basic, C++, Python, English, Spanish'}\n" + ] + } + ], + "source": [ + "print(lang)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Correct way to do this" + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " \n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " SQL, English\n", + "\n", + " English, Hindi, Python, shell, d2k, SQL, Perl\n", + "\n", + " English, Latin, HTML, CSS, Javascript, Ruby, SQL\n", + "\n", + " English, Python, Sass, R, Basic\n", + "\n", + " C, C++, Perl, VHDL, Verilog, Specman\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " English\n", + "\n", + " C#, SQL, R\n", + "\n", + " SQL, Python, R, VBA, English\n", + "\n", + " Basic, Pascal, C, Perl, Ruby\n", + "\n", + " Basic, C++, Python, English, Spanish\n", + "\n", + " English\n", + "\n", + " C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley\n", + "\n", + " \n", + "\n", + " Python, Perl, Matlab\n", + "\n", + " \n", + "\n", + " Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab\n", + "\n", + " \n", + "\n" + ] + } + ], + "source": [ + "with open('students.txt', 'r') as f:\n", + " for lines in f:\n", + " students_languages = lines.split(':')[1]\n", + " print(students_languages)" + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "language_set = set()\n", + "with open('students.txt', 'r') as f:\n", + " for lines in f:\n", + " students_languages = lines.split(':')[1]\n", + " language_list = students_languages.split(',') \n", + " for item in language_list:\n", + " language_set.add(item)" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{' Basic\\n', ' Ruby', ' Lisp', ' Ruby\\n', ' VHDL', ' SQL', ' Bash', ' C#', ' Latin', ' Python', ' C++', ' Tcl', ' Assembley\\n', ' C', ' Basic', ' R', ' Perl\\n', ' Ada', ' Pascal', ' CSS', ' Sass', ' Scheme', ' shell', ' English\\n', ' Objective-C', ' \\n', ' Spanish\\n', ' Specman\\n', ' English', ' Javascript', ' Perl', ' R\\n', ' Hindi', ' HTML', ' VBA', ' d2k', ' Prolog', ' SQL\\n', ' Verilog', ' Matlab\\n'}\n" + ] + } + ], + "source": [ + "print(language_set)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session4/set_lab.py b/students/JohnRudolph/session4/set_lab.py new file mode 100644 index 0000000..4898ee7 --- /dev/null +++ b/students/JohnRudolph/session4/set_lab.py @@ -0,0 +1,60 @@ +cityDic = {'name':'Chris', 'city':'Seattle', 'cake':'chocolate'} + +print(cityDic) + +cityDic.pop('cake') + +print(cityDic) + +cityDic['fruit'] = 'Mango' + +print(cityDic) + +print(cityDic.keys()) + +print(cityDic.values()) + +print('cake' in cityDic) + +print('Mango' in cityDic.values()) + +newDic = {} +for item in cityDic: + newDic[item] = cityDic[item].count('t') + +print(newDic) + +s2 = set() +s3 = set() +s4 = set() + +for i in range(20): + if i % 2 == 0: + s2.update([i]) + if i % 3 == 0: + s3.update([i]) + if i % 4 == 0: + s4.update([i]) + +print(s2) +print(s3) +print(s4) + +print(s3.issubset(s2)) +print(s4.issubset(s2)) + +pySet = set() +setString = 'Python' +for let in setString: + pySet.update([let]) + +pySet.update(['i']) + +print(pySet) + +frozen = frozenset(('m', 'a', 'r', 'a','t','h','o','n')) + +print(frozen) + + + diff --git a/students/JohnRudolph/session4/sherlock_small.txt. b/students/JohnRudolph/session4/sherlock_small.txt. new file mode 100644 index 0000000..dad12e2 --- /dev/null +++ b/students/JohnRudolph/session4/sherlock_small.txt. @@ -0,0 +1,16 @@ +One night--it was on the twentieth of March, 1888--I was +returning from a journey to a patient (for I had now returned to +civil practice), when my way led me through Baker Street. As I +passed the well-remembered door, which must always be associated +in my mind with my wooing, and with the dark incidents of the +Study in Scarlet, I was seized with a keen desire to see Holmes +again, and to know how he was employing his extraordinary powers. +His rooms were brilliantly lit, and, even as I looked up, I saw +his tall, spare figure pass twice in a dark silhouette against +the blind. He was pacing the room swiftly, eagerly, with his head +sunk upon his chest and his hands clasped behind him. To me, who +knew his every mood and habit, his attitude and manner told their +own story. He was at work again. He had risen out of his +drug-created dreams and was hot upon the scent of some new +problem. I rang the bell and was shown up to the chamber which +had formerly been in part my own. diff --git a/students/JohnRudolph/session4/students.txt b/students/JohnRudolph/session4/students.txt new file mode 100644 index 0000000..1c83671 --- /dev/null +++ b/students/JohnRudolph/session4/students.txt @@ -0,0 +1,24 @@ +Bindhu, Krishna: +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: diff --git a/students/JohnRudolph/session4/test.txt b/students/JohnRudolph/session4/test.txt new file mode 100644 index 0000000..5386d20 --- /dev/null +++ b/students/JohnRudolph/session4/test.txt @@ -0,0 +1,3 @@ +This is a blank text file +It has some words in it +Blah blah blah blah \ No newline at end of file diff --git a/students/JohnRudolph/session5/cigar_party.py b/students/JohnRudolph/session5/cigar_party.py new file mode 100644 index 0000000..544d2a1 --- /dev/null +++ b/students/JohnRudolph/session5/cigar_party.py @@ -0,0 +1,7 @@ +def cigar_party(cigars, isweekend): + if (40 <= cigars <= 60) and (isweekend is False): + return True + elif (40 <= cigars) and (isweekend is True): + return True + else: + return False \ No newline at end of file diff --git a/students/JohnRudolph/session5/codingbat.py b/students/JohnRudolph/session5/codingbat.py new file mode 100644 index 0000000..795157d --- /dev/null +++ b/students/JohnRudolph/session5/codingbat.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +""" +Examples from: http://codingbat.com + +Put here so we can write unit tests for them ourselves +""" + +# Python > Warmup-1 > sleep_in + + +def sleep_in(weekday, vacation): + if vacation is True: + return True + elif weekday is False: + return True + else: + return False + + +def sumdouble(a, b): + if a == b: + return (a + b) * 2 + else: + return(a + b) + diff --git a/students/JohnRudolph/session5/exceptlab.py b/students/JohnRudolph/session5/exceptlab.py new file mode 100644 index 0000000..cfce191 --- /dev/null +++ b/students/JohnRudolph/session5/exceptlab.py @@ -0,0 +1,9 @@ + +def getsafeinput(): + try: + getinput = input("Input Something\n") + return getinput + except (EOFError, KeyboardInterrupt): + return None + +print(getsafeinput()) diff --git a/students/JohnRudolph/session5/mailroom.py b/students/JohnRudolph/session5/mailroom.py new file mode 100644 index 0000000..edeccf6 --- /dev/null +++ b/students/JohnRudolph/session5/mailroom.py @@ -0,0 +1,185 @@ +import random + +################################################################################ +########################GENERATE RANDOM DONOR LIST############################## +################################################################################ + +def createDonors(numDonors): + ''' + This function is used to create a donorlist + Input desired number of into donorlist function + For each donor input function will randomly generate_ + # of donations between 1-3 + And randomly generate a donation amount between 100-1000 + Will return a list of lists + ''' + + donorList = [] + + for x in range(numDonors): + + # random # of donations between 1-3 inclusive + numDonations = random.randint(1, 3) + # list that holds donor name and donations amounts + donsubList = ['donor name' + str(x + 1)] + + # create random donations amounts between $100-$1K + for y in range(numDonations): + donsubList.append(random.randint(100, 1000)) + + donorList.append(donsubList) + + return donorList + +################################################################################ +#############################GENERAL FUNCTIONS################################## +################################################################################ + +def actionPrompt(): + ''' + This function prompts a user to select an action: + "Send thank you" or "create a report" + Function will loop until one of these is entered + ''' + index_check = None + while index_check is None: + getAction = str(input("Input Action: 'Send a Thank You'\t'Create a Report'\t'Quit'\n")) + if getAction.lower() not in ['send a thank you', 'create a report', 'quit']: + print("Invalid Action: Try Again!") + else: + index_check = True + return getAction + +################################################################################ +#############################THANK YOU FUNCTIONS################################ +################################################################################ + +def appendDonor(getName): + ''' + This functions find the donor in the dictionary + Prompts user for new donations and appends donation to the dictionary key + If user does not enter a number then error will be raised + ''' + donCheck = None + while donCheck is None: + try: + donation = int(input('Enter donation amount (int) for {}:\n'.format(getName))) + ownerDic.setdefault(getName, []).append(donation) + print(getName, ownerDic[getName]) + donCheck = True + except: + print('You did not enter a valid integer Try Again!') + + +def sendThanks(getName): + ''' + This function runs the steps for sending a thank your + If user select list then print current donor dic and reprompt + If donor is already in dic then append amounts + If donor not in dic then append new donor and add amount + ''' + if getName.lower() == 'list': + for key in sorted(ownerDic): + print(key) + getName = input("Input a full name or 'list'\n") + sendThanks(getName) + elif getName in ownerDic.keys(): + print('Adding a new donation for: {}'.format(getName)) + appendDonor(getName) + emailThanks(getName) + elif getName == 'quit': + print('Quitting Thank You') + else: + print('Adding {} to Donor Database'.format(getName)) + ownerDic.setdefault(getName, []) + appendDonor(getName) + emailThanks(getName) + + +def emailThanks(getName): + ''' + This function grabs the last donation entered for a given donor + Print a thank you message with donor name and donation amount + ''' + donationList = list(ownerDic[getName]) + print('Thank you {} for your generous donation of ${}!'.format( + getName, donationList[-1])) + +################################################################################ +#########################DONORS REPORT FUNCTIONS################################ +################################################################################ + +def getKey(item): + ''' + Function used to sort second item in a list of lists + ''' + return item[1] + + +def createtopDonors(): + ''' + Creates a new list with total donations, donation count and avg donations + by looping over master donor dictionary + New list is sorted based on total donation + ''' + sortList = [] + for key in ownerDic: + totalDon = sum(list(ownerDic[key])) + countDon = len((list(ownerDic[key]))) + avgDon = int(totalDon / countDon) + sortList.append([key, totalDon, countDon, avgDon]) + + return(sorted(sortList, key=getKey, reverse=True)) + + +def outputTopDonors(topDonors): + ''' + This function loops through the sorted top donors list + And prints each itemn in tabular format + ''' + print('Donor Name\tTotal\tCount\tAverage') + for x in topDonors: + print('{}\t{}\t{}\t{}'.format(*x)) + +################################################################################ +################################MAIN CODE BLOCK################################# +################################################################################ + +if __name__ == '__main__': + + import random + + check = None + while check is None: + try: + # create an arbitrary # of donors - 5 per assignment directions + numDonors = int( + input('Enter number (int) of donors to generate\n')) + check = True + except: + print('You did not enter a valid int - Try again!') + + # create the initial list of donors + donorList = createDonors(numDonors) + # create an empty dictionary - will be populated in loop below + ownerDic = {} + # populate donor dict from donorlist + for donor in donorList: + donor_name = donor[0] + donations = donor[1:] + ownerDic[donor_name] = donations + + # flag used to quit prompting user for an action + quit_check = False + + while quit_check is False: + getAction = actionPrompt() + if getAction.lower() == 'send a thank you': + getName = input("Input a full name or 'list'\n") + sendThanks(getName) + elif getAction.lower() == 'create a report': + topDonors = createtopDonors() + outputTopDonors(topDonors) + elif getAction.lower() == 'quit': + print('Quitting Program!') + quit_check = True diff --git a/students/JohnRudolph/session5/output.txt b/students/JohnRudolph/session5/output.txt new file mode 100644 index 0000000..dad12e2 --- /dev/null +++ b/students/JohnRudolph/session5/output.txt @@ -0,0 +1,16 @@ +One night--it was on the twentieth of March, 1888--I was +returning from a journey to a patient (for I had now returned to +civil practice), when my way led me through Baker Street. As I +passed the well-remembered door, which must always be associated +in my mind with my wooing, and with the dark incidents of the +Study in Scarlet, I was seized with a keen desire to see Holmes +again, and to know how he was employing his extraordinary powers. +His rooms were brilliantly lit, and, even as I looked up, I saw +his tall, spare figure pass twice in a dark silhouette against +the blind. He was pacing the room swiftly, eagerly, with his head +sunk upon his chest and his hands clasped behind him. To me, who +knew his every mood and habit, his attitude and manner told their +own story. He was at work again. He had risen out of his +drug-created dreams and was hot upon the scent of some new +problem. I rang the bell and was shown up to the chamber which +had formerly been in part my own. diff --git a/students/JohnRudolph/session5/paths.py b/students/JohnRudolph/session5/paths.py new file mode 100644 index 0000000..6fee83c --- /dev/null +++ b/students/JohnRudolph/session5/paths.py @@ -0,0 +1,86 @@ +import os +import itertools + +# list all files in curdir + + +def printcurdir(): + ''' + Print all files in active directory + ''' + print('Files in active directory:\n') + for f in os.listdir('.'): + print(f) + +def checkfileext(cfile, dfile): + ''' + Check if copy and destination file have same extension + ''' + try: + if dfile.split('.')[1] == cfile.split('.')[1]: + return True + else: + return False + except ValueError: + return False + +''' +os.mknod("output.txt") + +# get current dir path +fname = open('sherlock_small.txt.', 'rb') +outname = open('output.txt', 'wb') + +for i in itertools.count(): + record = bytearray(fname.read(16)) + outname.write(record) + if not record: + break +''' + + +if __name__ == '__main__': + + # print current directory + printcurdir() + # get file name to copy + fcheck = True + while fcheck is True: + cfile = input('Name of File to copy (filename.ext)\n') + if os.path.isfile('{}{}{}'.format(os.getcwd(), '/', cfile)): + print('Found ', cfile) + fcheck = False + else: + print('File not found! Listing available files:\n') + printcurdir() + + # destination of copied file + dcheck = True + while dcheck is True: + ddir = input('Name of directory for destination file\n') + if os.path.isdir(ddir): + print('Found', ddir) + dcheck = False + else: + print(ddir, ' Not Found! Create directory and try again') + + # create destination file + ccheck = True + while ccheck is True: + dfile = input('Name of output file (filename.ext)\n') + if checkfileext(cfile, dfile) is True: + ccheck = False + else: + print('Problem with {}{} name or extension'.format(cfile, dfile)) + + #open copy file + rcfile = open(cfile, 'rb') + rdfile = open(os.path.join(ddir, dfile), 'wb') + for i in itertools.count(): + record = bytearray(rcfile.read(16)) + rdfile.write(record) + if not record: + break + + rcfile.close() + rdfile.close() \ No newline at end of file diff --git a/students/JohnRudolph/session5/sherlock_small.txt b/students/JohnRudolph/session5/sherlock_small.txt new file mode 100644 index 0000000..dad12e2 --- /dev/null +++ b/students/JohnRudolph/session5/sherlock_small.txt @@ -0,0 +1,16 @@ +One night--it was on the twentieth of March, 1888--I was +returning from a journey to a patient (for I had now returned to +civil practice), when my way led me through Baker Street. As I +passed the well-remembered door, which must always be associated +in my mind with my wooing, and with the dark incidents of the +Study in Scarlet, I was seized with a keen desire to see Holmes +again, and to know how he was employing his extraordinary powers. +His rooms were brilliantly lit, and, even as I looked up, I saw +his tall, spare figure pass twice in a dark silhouette against +the blind. He was pacing the room swiftly, eagerly, with his head +sunk upon his chest and his hands clasped behind him. To me, who +knew his every mood and habit, his attitude and manner told their +own story. He was at work again. He had risen out of his +drug-created dreams and was hot upon the scent of some new +problem. I rang the bell and was shown up to the chamber which +had formerly been in part my own. diff --git a/Examples/Session06/test_cigar_party.py b/students/JohnRudolph/session5/test_cigar_party.py similarity index 100% rename from Examples/Session06/test_cigar_party.py rename to students/JohnRudolph/session5/test_cigar_party.py diff --git a/students/JohnRudolph/session5/test_codingbat.py b/students/JohnRudolph/session5/test_codingbat.py new file mode 100755 index 0000000..4df4cf8 --- /dev/null +++ b/students/JohnRudolph/session5/test_codingbat.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +""" +test file for codingbat module + +This version can be run with nose or py.test +""" + +from codingbat import sleep_in +from codingbat import sumdouble + + +def test_false_false(): + assert sleep_in(False, False) is True + + +def test_true_false(): + assert not (sleep_in(True, False)) is True + + +def test_false_true(): + assert sleep_in(False, True) is True + + +def test_true_true(): + assert sleep_in(True, True) is True + + +def test_sumdouble1(): + assert sumdouble(1, 2) == 3 + + +def test_sumdouble2(): + assert sumdouble(3, 2) == 5 + + +def test_sumdouble3(): + assert sumdouble(2, 2) == 8 diff --git a/students/JohnRudolph/session5/test_mailroom.py b/students/JohnRudolph/session5/test_mailroom.py new file mode 100644 index 0000000..9f5599f --- /dev/null +++ b/students/JohnRudolph/session5/test_mailroom.py @@ -0,0 +1,12 @@ + +from mailroom import createDonors +from mailroom import actionPrompt + +# test that # of donors generated in correct +def test_creatdonorslen(): + assert len(createDonors(5)) == 5 + +# test that # of donations for each donor is between 1-3 +def test_creatdonorsdons(): + for n in createDonors(5): + assert 1 <= len(n) <= 3 diff --git a/students/JohnRudolph/session6/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/students/JohnRudolph/session6/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100644 index 0000000..4416f6f --- /dev/null +++ b/students/JohnRudolph/session6/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,447 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Session 6 notes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Exceptions - notes" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " f = open('missing.txt')\n", + " process(f) # never called if file missing\n", + "except:\n", + " print(\"couldn't open missing.txt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "simple try and except loop" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " f = open('missing.txt')\n", + "except:\n", + " print(\"couldn't open missing.txt\")\n", + "else:\n", + " process(f)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " with open('missing.txt') as f:\n", + " process(f)\n", + "except:\n", + " print(\"couldn't open missing.txt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Best way to write exception is this way using with open" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Advanced Passing arguments" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "donor_name = 'Exit'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "if donor_name.lower() == 'exit':\n", + " print('bye')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "builtin_function_or_method" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(donor_name.lower)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(donor_name.lower())" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def myfunc(a=0, b=1, c=2):\n", + " print(a, b, c)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 1 22\n" + ] + } + ], + "source": [ + "myfunc(5, c=22)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0 1 2\n" + ] + } + ], + "source": [ + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def my_positional_and_kwargs_func(x, y, z=\"Hi I'm Z\"):\n", + " print(x, y, z)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "my_positional_and_kwargs_func() missing 2 required positional arguments: 'x' and 'y'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmy_positional_and_kwargs_func\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: my_positional_and_kwargs_func() missing 2 required positional arguments: 'x' and 'y'" + ] + } + ], + "source": [ + "my_positional_and_kwargs_func()" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hi im X Hi im Y Hi I'm Z\n" + ] + } + ], + "source": [ + "my_positional_and_kwargs_func(\"Hi im X\", \"Hi im Y\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_positional_and_kwargs_func" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "mydict = {\"last_name\": 'Grimes', \"first_name\": 'Rick'}" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'my name is Rick Grimes'" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"my name is {first_name} {last_name}\".format(**mydict)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'my name is Rick Grimes'" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"my name is {} {}\".format(mydict['first_name'], mydict['last_name'])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Switch Dictionary" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "switch_dict = {\n", + " 0: 'zero',\n", + " 1: 'one',\n", + " 2: 'two',\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'zero'" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_dict.get(0)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "switch_dict.get('2345' or 'nothing')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session6/passfunc.py b/students/JohnRudolph/session6/passfunc.py new file mode 100644 index 0000000..39c578e --- /dev/null +++ b/students/JohnRudolph/session6/passfunc.py @@ -0,0 +1,42 @@ +def size_func(fib, lfib): + if fib % 2 == 0: + size = 'medium' + else: + if lfib % 2 == 0: + size = 'large' + else: + size = 'small' + return size + + +def list_pop(fib_list, size_list): + list_len = len(fib_list) + for i in range(3): + indx = i + list_len + fib_list.append(fib_list[indx - 2]+fib_list[indx - 1]) + size_list.append(size_func(fib_list[indx], fib_list[indx - 1])) + return fib_list[list_len:], size_list[list_len:] + + +def hand_weapon(): + fib_list = list(range(2)) + size_list = [] + for i in range(3): + fib_list.append(fib_list[i]+fib_list[i+1]) + size_list.append(size_func(fib_list[i + 2], fib_list[i + 1])) + return fib_list[2:], size_list + + +def gun(): + fib_list, size_list = hand_weapon() + return list_pop(fib_list, size_list) + + +def flower_power(): + fib_list, size_list = gun() + return list_pop(fib_list, size_list) + + +def score(weapon_type, weapon_size): + fib_list, size_list = weapon_type() + return fib_list[size_list.index(weapon_size)] diff --git a/students/JohnRudolph/session6/session6.ipynb b/students/JohnRudolph/session6/session6.ipynb new file mode 100644 index 0000000..4416f6f --- /dev/null +++ b/students/JohnRudolph/session6/session6.ipynb @@ -0,0 +1,447 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Session 6 notes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Exceptions - notes" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " f = open('missing.txt')\n", + " process(f) # never called if file missing\n", + "except:\n", + " print(\"couldn't open missing.txt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "simple try and except loop" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " f = open('missing.txt')\n", + "except:\n", + " print(\"couldn't open missing.txt\")\n", + "else:\n", + " process(f)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "couldn't open missing.txt\n" + ] + } + ], + "source": [ + "try:\n", + " do_something()\n", + " with open('missing.txt') as f:\n", + " process(f)\n", + "except:\n", + " print(\"couldn't open missing.txt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Best way to write exception is this way using with open" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Advanced Passing arguments" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "donor_name = 'Exit'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "if donor_name.lower() == 'exit':\n", + " print('bye')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "builtin_function_or_method" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(donor_name.lower)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(donor_name.lower())" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def myfunc(a=0, b=1, c=2):\n", + " print(a, b, c)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 1 22\n" + ] + } + ], + "source": [ + "myfunc(5, c=22)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0 1 2\n" + ] + } + ], + "source": [ + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def my_positional_and_kwargs_func(x, y, z=\"Hi I'm Z\"):\n", + " print(x, y, z)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "my_positional_and_kwargs_func() missing 2 required positional arguments: 'x' and 'y'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmy_positional_and_kwargs_func\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: my_positional_and_kwargs_func() missing 2 required positional arguments: 'x' and 'y'" + ] + } + ], + "source": [ + "my_positional_and_kwargs_func()" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hi im X Hi im Y Hi I'm Z\n" + ] + } + ], + "source": [ + "my_positional_and_kwargs_func(\"Hi im X\", \"Hi im Y\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_positional_and_kwargs_func" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "mydict = {\"last_name\": 'Grimes', \"first_name\": 'Rick'}" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'my name is Rick Grimes'" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"my name is {first_name} {last_name}\".format(**mydict)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'my name is Rick Grimes'" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"my name is {} {}\".format(mydict['first_name'], mydict['last_name'])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Switch Dictionary" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "switch_dict = {\n", + " 0: 'zero',\n", + " 1: 'one',\n", + " 2: 'two',\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'zero'" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "switch_dict.get(0)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "switch_dict.get('2345' or 'nothing')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session6/test_passfunc.py b/students/JohnRudolph/session6/test_passfunc.py new file mode 100644 index 0000000..749e93e --- /dev/null +++ b/students/JohnRudolph/session6/test_passfunc.py @@ -0,0 +1,16 @@ +from passfunc import score +from passfunc import hand_weapon +from passfunc import gun +from passfunc import flower_power + + +def test_scoring(): + assert score(hand_weapon, 'small') == 1 + assert score(hand_weapon, 'medium') == 2 + assert score(hand_weapon, 'large') == 3 + assert score(gun, 'small') == 5 + assert score(gun, 'medium') == 8 + assert score(gun, 'large') == 13 + assert score(flower_power, 'small') == 21 + assert score(flower_power, 'medium') == 34 + assert score(flower_power, 'large') == 55 \ No newline at end of file diff --git a/students/JohnRudolph/session6/test_trap.py b/students/JohnRudolph/session6/test_trap.py new file mode 100644 index 0000000..7c88ec3 --- /dev/null +++ b/students/JohnRudolph/session6/test_trap.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +from numpy import trapz +from numpy import isclose +from math import sin, cos +from trap import trap + +######################################################### +#################INPUT Explicit f(x)##################### +######################################################### + + +def linefunc(x): + ''' + Returns f(x): y = 5 + ''' + return 5 + + +def linearfunc(x): + ''' + Returns f(x): y = 2x + 5 + ''' + return 2 * x + 5 + + +def quadraticfunc(x): + '''' + Return f(x): y = 2(x)^2 + 4(x) + 5 + ''' + return 2*x**2 + 4*x + 5 + + +def sinfunc(x): + '''' + Return f(x): y = sin(x) + ''' + return sin(x) + + +######################################################### +#################INPUT General f(x)###################### +######################################################### +def genlinearfunc(x, A=1, B=1): + ''' + Returns f(x): y = Ax + B + For arbitrary values of A and B + ''' + return A * x + B + + +def genquadraticfunc(x, A=1, B=1, C=1): + ''' + Return Return f(x): y = A(x)^2 + B(x) + C + For arbitrary values of A, B and C + ''' + return A*x**2 + B*x + C + + +def gensinfunc(x, A=1, w=1): + ''' + Return Return f(x): y = Asin(wx) + For arbitrary values of A, B and C + ''' + return A*sin(w*x) + + +######################################################### +################TESTS USING CALC THEORY################## +######################################################### +def test_linear1(): + ''' + Check if area under linear function for Trap + Is approx equal to analytical solution + (1/2)A(b^2 - a^2)+B(b-a) + ''' + A, B, a, b = 2, 5, 0, 100 + area1 = .5*A*(b**2 - a**2) + B*(b-a) + area2 = trap(linearfunc, 0, 100, 1000) + assert isclose(area1, area2) is True + +def test_genlinear1(): + ''' + Check if area under linear function for Trap + Is approx equal to analytical solution + (1/2)A(b^2 - a^2)+B(b-a) + ''' + A, B, a, b = 3, 4, 0, 100 + area1 = .5*A*(b**2 - a**2) + B*(b-a) + area2 = trap(genlinearfunc, 0, 100, 1000, A=A, B=B) + assert isclose(area1, area2) is True + +def test_quadratic1(): + ''' + Check if area under quadratic function for Trap + Is approx equal to analytical solution + (A/3)(b^3 - a^3) + (B/2)(b^2-a^2) + C(b-a) + ''' + A, B, C, a, b = 2, 4, 5, 0, 100 + area1 = (A/3)*(b**3 + a**3) + (B/2)*(b**2 + a**2) + C*(b-a) + area2 = trap(quadraticfunc, 0, 100, 1000) + assert isclose(area1, area2) is True + + +def test_genquadratic1(): + ''' + Check if area under quadratic function for Trap + Is approx equal to analytical solution + (A/3)(b^3 - a^3) + (B/2)(b^2-a^2) + C(b-a) + ''' + A, B, C, a, b = 2, 4, 5, 0, 100 + area1 = (A/3)*(b**3 + a**3) + (B/2)*(b**2 + a**2) + C*(b-a) + area2 = trap(genquadraticfunc, 0, 100, 1000, A=A, B=B, C=C) + assert isclose(area1, area2) is True + + +def test_sin1(): + ''' + Check if area under sin function for Trap + Is approx equal to analytical solution + sin(x) = cos(a) - cos(b) + ''' + a, b = 0, 100 + area1 = cos(a) - cos(b) + area2 = trap(sinfunc, 0, 100, 1000) + assert isclose(area1, area2, atol=0.05) is True + + +def test_gensin1(): + ''' + Check if area under sin function for Trap + Is approx equal to analytical solution + sin(x) = cos(a) - cos(b) + ''' + A, w, a, b = 2, 4, 0, 100 + area1 = (A/w)*(cos(w*a) - cos(w*b)) + area2 = trap(gensinfunc, 0, 100, 1000, A=A, w=w) + assert isclose(area1, area2, atol=0.05) is True + + +######################################################### +####################TESTS USING TRAPZ#################### +######################################################### + +def test_line2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = 5 + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(linefunc(i)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(linefunc, x1, x2, step) + assert isclose(area1, area2) is True + + +def test_linear2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = ax + b + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(linearfunc(i)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(linearfunc, x1, x2, step) + assert isclose(area1, area2) is True + + +def test_genlinear2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = ax + b - generalized + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(genlinearfunc(i, A=2, B=2)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(genlinearfunc, x1, x2, step, A=2, B=2) + assert isclose(area1, area2) is True + + +def test_quadratic2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = ax^2 + bx + c + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(quadraticfunc(i)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(quadraticfunc, x1, x2, step) + assert isclose(area1, area2) is True + + +def test_genquadratic2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = ax + b - generalized + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(genquadraticfunc(i, A=2, B=2, C=2)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(genquadraticfunc, x1, x2, step, A=2, B=2, C=2) + assert isclose(area1, area2) is True + + +def test_sin2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = sin(x) + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(sinfunc(i)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(sin, x1, x2, step) + assert isclose(area1, area2, atol=0.05) is True + + +def test_gensin2(): + ''' + Checks if area under curve computed for Trap func + Is approximately equal to Trapz function from Numpy + For f(x) = Asin(wx) - generalized + ''' + xvector = range(100) + yvector = [] + for i in xvector: + yvector.append(gensinfunc(i, A=2, w=3)) + area1 = trapz(yvector, x=xvector) + x1, x2 = xvector[0], xvector[-1] + step = len(xvector) + area2 = trap(gensinfunc, x1, x2, step, A=2, w=3) + assert isclose(area1, area2, atol=0.05) is True diff --git a/students/JohnRudolph/session6/trap.py b/students/JohnRudolph/session6/trap.py new file mode 100644 index 0000000..993cd1f --- /dev/null +++ b/students/JohnRudolph/session6/trap.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 + +######################################################### +###############TRAPEZOIDAL FUNCTIONS #################### +######################################################### + +def createxvector(x1, x2, step): + ''' + Creates a vector of values from + x1 to x2 by specified step increments + ''' + xvector = [] + while x1 <= x2: + xvector.append(x1) + x1 += step + return xvector + + +def createyvector(fx, xvector, **kwargs): + ''' + Creates a vector of values based on + a given function (fx) and given x values vector + ''' + keys = kwargs + yvector = [] + for i in xvector: + yvector.append(fx(i, **keys)) + return yvector + + +def trap(fx, x1, x2, div, **kwargs): + ''' + This function integrates under a given function + By using the trapezoid rule + A defined function must be supplied + With a start value for x1 and end value x2 which is used + And the number of intervals to split between x1 and x2 + ''' + keys = kwargs + step = (x2 - x1) / div + xvector = createxvector(x1, x2, step) + yvector = createyvector(fx, xvector, **keys) + areavector = [] + cntr = -1 + for i, n in zip(xvector, yvector): + cntr += 1 + if cntr < len(xvector) - 1: + deltax = xvector[cntr + 1] - i + deltay = (n + yvector[cntr + 1])/2 + areavector.append(deltax * deltay) + + return sum(areavector) diff --git a/students/JohnRudolph/session7/.ipynb_checkpoints/class lab2-checkpoint.ipynb b/students/JohnRudolph/session7/.ipynb_checkpoints/class lab2-checkpoint.ipynb new file mode 100644 index 0000000..286dcb3 --- /dev/null +++ b/students/JohnRudolph/session7/.ipynb_checkpoints/class lab2-checkpoint.ipynb @@ -0,0 +1,6 @@ +{ + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session7/.ipynb_checkpoints/class_notes-checkpoint.ipynb b/students/JohnRudolph/session7/.ipynb_checkpoints/class_notes-checkpoint.ipynb new file mode 100644 index 0000000..b2bddf9 --- /dev/null +++ b/students/JohnRudolph/session7/.ipynb_checkpoints/class_notes-checkpoint.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Notes on Classes" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Point(object):\n", + " size = 4\n", + " color = 'red'\n", + " \n", + " \n", + " def __init__(self, x, y):\n", + " origin = 0\n", + " self.x = x\n", + " self.y = y\n", + " self.z = x * y -2\n", + " \n", + " def get_color(self):\n", + " return self.color\n", + " \n", + " \n", + " def get_size(self):\n", + " return self.size\n", + " \n", + " def gimme_two_values(self, a,b):\n", + " self.x = a\n", + " self.y = b" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_point = Point(2, 3)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.get_color()" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_other_point = Point(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_other_point.get_color()" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_other_point.get_size()" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.z" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'color',\n", + " 'get_color',\n", + " 'get_size',\n", + " 'gimme_two_values',\n", + " 'size',\n", + " 'x',\n", + " 'y',\n", + " 'z']" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(my_point)" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_point.gimme_two_values(54, 666)" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "54" + ] + }, + "execution_count": 46, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.x" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 47, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.color" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session7/class lab2.ipynb b/students/JohnRudolph/session7/class lab2.ipynb new file mode 100644 index 0000000..05859a2 --- /dev/null +++ b/students/JohnRudolph/session7/class lab2.ipynb @@ -0,0 +1,381 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class A:\n", + " def hello(self):\n", + " print(\"Hi\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class B(A):\n", + " def hello(self):\n", + " super().hello()\n", + " print(\"there\")" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "hello() missing 1 required positional argument: 'self'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mA\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mhello\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: hello() missing 1 required positional argument: 'self'" + ] + } + ], + "source": [ + "A.hello()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "b = B()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "<__main__.B object at 0x7f3e5ca5d710>\n" + ] + } + ], + "source": [ + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Creating classes to store animals types - using inheritence" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Animal(object):\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Mammal(Animal): \n", + " gestation_in_womb = True\n", + " warm_blood = True\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Reptile(Animal):\n", + " gestation_in_womb = False\n", + " warm_blood = False\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Bird(Reptile): \n", + " gestation_in_womb = False\n", + " warm_blood = True\n", + " \n", + " def __init__(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Dog(Mammal):\n", + " \n", + " def __init__(self, chases=True):\n", + " self.chases_cats = chases\n", + " pass\n", + " \n", + " def make_cold_blooded(self):\n", + " self.warm_blood = False" + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class Cat(Mammal):\n", + " \n", + " def __init__(self, hates_dogs = True):\n", + " self.hates_dogs = hates_dogs\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_mammal = Mammal()" + ] + }, + { + "cell_type": "code", + "execution_count": 79, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 79, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_mammal.warm_blood" + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_reptile = Reptile()" + ] + }, + { + "cell_type": "code", + "execution_count": 81, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 81, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_reptile.warm_blood" + ] + }, + { + "cell_type": "code", + "execution_count": 82, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dog1 = Dog(chases=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 83, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dog1.chases_cats" + ] + }, + { + "cell_type": "code", + "execution_count": 85, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "dog1.make_cold_blooded()" + ] + }, + { + "cell_type": "code", + "execution_count": 86, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 86, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dog1.warm_blood" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "dog1.warm_blood = True" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 93, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dog1.warm_blood" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session7/class_notes.ipynb b/students/JohnRudolph/session7/class_notes.ipynb new file mode 100644 index 0000000..b2bddf9 --- /dev/null +++ b/students/JohnRudolph/session7/class_notes.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Notes on Classes" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Point(object):\n", + " size = 4\n", + " color = 'red'\n", + " \n", + " \n", + " def __init__(self, x, y):\n", + " origin = 0\n", + " self.x = x\n", + " self.y = y\n", + " self.z = x * y -2\n", + " \n", + " def get_color(self):\n", + " return self.color\n", + " \n", + " \n", + " def get_size(self):\n", + " return self.size\n", + " \n", + " def gimme_two_values(self, a,b):\n", + " self.x = a\n", + " self.y = b" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_point = Point(2, 3)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.get_color()" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_other_point = Point(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_other_point.get_color()" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_other_point.get_size()" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.z" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['__class__',\n", + " '__delattr__',\n", + " '__dict__',\n", + " '__dir__',\n", + " '__doc__',\n", + " '__eq__',\n", + " '__format__',\n", + " '__ge__',\n", + " '__getattribute__',\n", + " '__gt__',\n", + " '__hash__',\n", + " '__init__',\n", + " '__le__',\n", + " '__lt__',\n", + " '__module__',\n", + " '__ne__',\n", + " '__new__',\n", + " '__reduce__',\n", + " '__reduce_ex__',\n", + " '__repr__',\n", + " '__setattr__',\n", + " '__sizeof__',\n", + " '__str__',\n", + " '__subclasshook__',\n", + " '__weakref__',\n", + " 'color',\n", + " 'get_color',\n", + " 'get_size',\n", + " 'gimme_two_values',\n", + " 'size',\n", + " 'x',\n", + " 'y',\n", + " 'z']" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dir(my_point)" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_point.gimme_two_values(54, 666)" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "54" + ] + }, + "execution_count": 46, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.x" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'red'" + ] + }, + "execution_count": 47, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_point.color" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session7/classsandbox.html b/students/JohnRudolph/session7/classsandbox.html new file mode 100644 index 0000000..40a746a --- /dev/null +++ b/students/JohnRudolph/session7/classsandbox.html @@ -0,0 +1,5 @@ + + + Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text + And here is another piece of text -- you should be able to add any number + \ No newline at end of file diff --git a/students/JohnRudolph/session7/html_render.py b/students/JohnRudolph/session7/html_render.py new file mode 100644 index 0000000..da25b52 --- /dev/null +++ b/students/JohnRudolph/session7/html_render.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python + +###################################################### +############## HTML RENDER EXERCISE ############### +###################################################### + +class Element(object): + ''' + Generates pretty html dynamically based on user supplied content + User supplies htmnl tags, associated text and attributes + ''' + + tag = 'html' #only necesarry because of step1 - subclass element should be used + + def __init__(self, content=None, **attributes): + # container for content - will be strings or classes + self.content = [] + # adding attributes dictionary + self.attributes = attributes + if content is not None: + self.append(content) + + def append(self, content): + #check if content is string or class + if hasattr(content, 'render'): + #if class then append + self.content.append(content) + else: + #if string then use TextWrapper to create render class + #needed so that render does not need to handle both strings/classes + self.content.append(TextWrapper(content)) + + def render_tag(self, current_ind): + # tag and then content for each class + attrs = "".join([' {}="{}"'.format(key, val) for key, val in self.attributes.items()]) + # indetation + tag + content + tag_str = "\n{}<{}{}>".format(current_ind, self.tag, attrs) + return tag_str + + def render(self, file_out, current_ind=""): + #check if element is html and print out DOCTYPE is true + if self.tag == 'html': + file_out.write('') + StartIndent.indent = current_ind #set initial indent value as class attrib + self.multi_linewrite(file_out, current_ind) #write out standard tag/content/tag + + def multi_linewrite(self, file_out, current_ind): + #writes out standard /n/tag/n/content/n/tag format + #write tag to file + file_out.write(self.render_tag(current_ind)) + #loop through and render any appended elements + for i in self.content: + i.render(file_out, '{}'.format(current_ind + StartIndent.indent)) + # write out closing tag + file_out.write("\n{}".format(current_ind, self.tag)) + + +class Html(Element): + tag = 'html' + +class Head(Element): + tag = 'head' + +class Body(Element): + tag = 'body' + + +class P(Element): + tag = 'p' + +class A(Element): + ''' + Creates a class for an anchor link element + Need to render opening and closing tags differently + Than in parent element class + Also need a special wrapper to handle link text + ''' + tag = 'a' + + def __init__(self, link, context): + super(A, self).__init__(content = context, href = link) + + def append(self, content): + #check if content is string or class + if hasattr(content, 'render'): + #if class then append + self.content.append(content) + else: + #if string then use TextWrapper to create render class + #needed so that render does not need to handle both strings/classes + self.content.append(TextWrapperAnchor(content)) + + def render_tag(self, current_ind): + #tag and then content for each class + attrs = "".join([' {}="{}"'.format(key, val) for key, val in self.attributes.items()]) + #indetation + tag + content + tag_str = "\n{}<{}{}".format(current_ind, self.tag, attrs) + return tag_str + + def render(self, file_out, current_ind=""): + #check if element is html and print out DOCTYPE is true + file_out.write(self.render_tag(current_ind)) + #loop through and render any appended elements + for i in self.content: + i.render(file_out, '{}'.format(current_ind + StartIndent.indent)) + #write out closing tag + file_out.write(" ".format(self.tag)) + + +class OneLineTag(Element): + ''' + Generates HTML for tags that have open closing tag on same line + ''' + tag = '' + + def append(self, content): + #check if content is class or text + if hasattr(content, 'render'): + #if class then append + self.content.append(content) + else: + #if string then use TextWrapper to create render class + #needed so that render does not need to handle both strings/classes + #need to call TextWrapper for One Line content + self.content.append(TextWrapperOneLine(content, self.tag)) + + def render(self, file_out, current_ind=""): + #one liners tags and content are handled in TextWrapperOneLine + for i in self.content: + i.render(file_out, current_ind) + + +class Title(OneLineTag): + tag = 'title' + + +class SelfClosingTag(Element): + ''' + Generates HTML for self closing tags + ''' + tag = '' + + def render_tag(self, current_ind): + # tag and then content for each class + attrs = "".join([' {}="{}"'.format(key, val) for key, val in self.attributes.items()]) + # indetation + tag + content + tag_str = "\n{}<{} />".format(current_ind, self.tag, attrs) + return tag_str + + def render(self, file_out, current_ind): + #write tag to file + file_out.write('{}'.format(self.render_tag(current_ind))) + + +class Hr(SelfClosingTag): + tag = 'hr' + + +class Br(SelfClosingTag): + tag = 'br' + +class TextWrapper: + """ + A wrapper that creates a render class for text + Used when passing in text content so that render method + Only has to handle class objects + """ + + def __init__(self, text): + self.text = text + + #writes out text to file + def render(self, file_out, current_ind=""): + #have to get indent from IndentCaller based on calling element subclass + file_out.write('\n{}{}'.format(current_ind, self.text)) + + +class TextWrapperOneLine: + """ + Used for One Line Renders + A wrapper that creates a render class for text + Used when passing in text content so that render method + Only has to handle class objects + """ + def __init__(self, text, elem): + self.text = text + self.element = elem + + #writes out text to file + def render(self, file_out, current_ind=""): + #have to get indent from IndentCaller based on calling element subclass + tag1, tag2 = '<{}>'.format(self.element), ''.format(self.element) + file_out.write('\n{}{} {} {}'.format(current_ind, tag1, self.text, tag2)) + + +class TextWrapperAnchor(TextWrapperOneLine): + + """ + Used for Anchor Element Renders + Used when passing in link text content so that render method + Only has to handle class objects + """ + + def __init__(self, text): + self.text = text + + def render(self, file_out, current_ind=""): + #have to get indent from IndentCaller based on calling element subclass + file_out.write('> {}'.format(self.text)) + + +class StartIndent(): + ''' + Hold the initial starting indent value + ''' + indent = '' + + def __init__(self): + pass diff --git a/students/JohnRudolph/session7/run_html_render.py b/students/JohnRudolph/session7/run_html_render.py new file mode 100644 index 0000000..18f8647 --- /dev/null +++ b/students/JohnRudolph/session7/run_html_render.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python + +""" +a simple script can run and test your html rendering classes. + +Uncomment the steps as you add to your rendering. + +""" + +from io import StringIO + +# importing the html_rendering code with a short name for easy typing. +import html_render as hr +# reloading in case you are running this in iPython +# -- we want to make sure the latest version is used +import importlib +importlib.reload(hr) + + +# writing the file out: +def render_page(page, filename): + """ + render the tree of elements + + This uses StringIO to render to memory, then dump to console and + write to file -- very handy! + """ + + f = StringIO() + page.render(f, " ") + + f.seek(0) + + print(f.read()) + + f.seek(0) + open(filename, 'w').write(f.read()) + + +# Step 1 +######### + +page = hr.Element() + +page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text") + +page.append("And here is another piece of text -- you should be able to add any number") + +render_page(page, "test_html_output1.html") + +# ## Step 2 +# ########## + +page = hr.Html() + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) + +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output2.html") + +# # Step 3 +# ########## + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output3.html") + +# # Step 4 +# ########## + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +page.append(body) + +render_page(page, "test_html_output4.html") + +# # Step 5 +# ######### + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +page.append(body) + +render_page(page, "test_html_output5.html") + +# # Step 6 +# ######### + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +body.append("And this is a ") +body.append( hr.A("http://google.com/", "link") ) +body.append("to google") + +page.append(body) + +render_page(page, "test_html_output6.html") + +# # Step 7 +# ######### + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append( hr.H(2, "PythonClass - Class 6 example") ) + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# list = hr.Ul(id="TheList", style="line-height:200%") + +# list.append( hr.Li("The first item in a list") ) +# list.append( hr.Li("This is the second item", style="color: red") ) + +# item = hr.Li() +# item.append("And this is a ") +# item.append( hr.A("http://google.com/", "link") ) +# item.append("to google") + +# list.append(item) + +# body.append(list) + +# page.append(body) + +# render_page(page, "test_html_output7.html") + +# # Step 8 +# ######## + +# page = hr.Html() + + +# head = hr.Head() +# head.append( hr.Meta(charset="UTF-8") ) +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append( hr.H(2, "PythonClass - Class 6 example") ) + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# list = hr.Ul(id="TheList", style="line-height:200%") + +# list.append( hr.Li("The first item in a list") ) +# list.append( hr.Li("This is the second item", style="color: red") ) + +# item = hr.Li() +# item.append("And this is a ") +# item.append( hr.A("http://google.com/", "link") ) +# item.append("to google") + +# list.append(item) + +# body.append(list) + +# page.append(body) + +# render_page(page, "test_html_output8.html") diff --git a/students/JohnRudolph/session7/sample_html.html b/students/JohnRudolph/session7/sample_html.html new file mode 100644 index 0000000..f2687e9 --- /dev/null +++ b/students/JohnRudolph/session7/sample_html.html @@ -0,0 +1,27 @@ + + + + + PythonClass = Revision 1087: + + +

PythonClass - Class 6 example

+

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+
+
    +
  • + The first item in a list +
  • +
  • + This is the second item +
  • +
  • + And this is a + link + to google +
  • +
+ + \ No newline at end of file diff --git a/students/JohnRudolph/session7/sandbox.py b/students/JohnRudolph/session7/sandbox.py new file mode 100644 index 0000000..981a047 --- /dev/null +++ b/students/JohnRudolph/session7/sandbox.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python + +""" +a simple script can run and test your html rendering classes. + +Uncomment the steps as you add to your rendering. + +""" + +from io import StringIO + +# importing the html_rendering code with a short name for easy typing. +import html_render as hr +# reloading in case you are running this in iPython +# -- we want to make sure the latest version is used +import importlib +importlib.reload(hr) + + +# writing the file out: +def render_page(page, filename): + """ + render the tree of elements + + This uses StringIO to render to memory, then dump to console and + write to file -- very handy! + """ + + f = StringIO() + page.render(f, " ") + + f.seek(0) + + print(f.read()) + + f.seek(0) + open(filename, 'w').write(f.read()) + + +# Step 1 +######### + +page = hr.Html() + +page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text") + +page.append("And here is another piece of text -- you should be able to add any number") + +render_page(page, "classsandbox.html") + +# ## Step 2 +# ########## + +page = hr.Html() + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) + +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output2.html") + +#Step 3 +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output3.html") \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_output1.html b/students/JohnRudolph/session7/test_html_output1.html new file mode 100644 index 0000000..40a746a --- /dev/null +++ b/students/JohnRudolph/session7/test_html_output1.html @@ -0,0 +1,5 @@ + + + Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text + And here is another piece of text -- you should be able to add any number + \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_output2.html b/students/JohnRudolph/session7/test_html_output2.html new file mode 100644 index 0000000..d96afdc --- /dev/null +++ b/students/JohnRudolph/session7/test_html_output2.html @@ -0,0 +1,11 @@ + + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+

+ And here is another piece of text -- you should be able to add any number +

+ + \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_output3.html b/students/JohnRudolph/session7/test_html_output3.html new file mode 100644 index 0000000..fcc9f12 --- /dev/null +++ b/students/JohnRudolph/session7/test_html_output3.html @@ -0,0 +1,14 @@ + + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+

+ And here is another piece of text -- you should be able to add any number +

+ + \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_output4.html b/students/JohnRudolph/session7/test_html_output4.html new file mode 100644 index 0000000..dd891d9 --- /dev/null +++ b/students/JohnRudolph/session7/test_html_output4.html @@ -0,0 +1,11 @@ + + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+ + \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_output5.html b/students/JohnRudolph/session7/test_html_output5.html new file mode 100644 index 0000000..5f16064 --- /dev/null +++ b/students/JohnRudolph/session7/test_html_output5.html @@ -0,0 +1,12 @@ + + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+
+ + \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_output6.html b/students/JohnRudolph/session7/test_html_output6.html new file mode 100644 index 0000000..a99822d --- /dev/null +++ b/students/JohnRudolph/session7/test_html_output6.html @@ -0,0 +1,15 @@ + + + + PythonClass = Revision 1087: + + +

+ Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text +

+
+ And this is a + link + to google + + \ No newline at end of file diff --git a/students/JohnRudolph/session7/test_html_render.py b/students/JohnRudolph/session7/test_html_render.py new file mode 100644 index 0000000..9bc52aa --- /dev/null +++ b/students/JohnRudolph/session7/test_html_render.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +from filecmp import cmp + +""" +Test for steps in html render lab +""" + +#Test part 1 +def test_html1(): + f1path = 'test_html_output1.html' + f2path = '/home/johnr_000/py101/IntroPython2016a/Examples/Session07/html_render/test_html_output1.html' + assert cmp(f1path, f2path, shallow=False) + +#Test part 2 +def test_html2(): + f1path = 'test_html_output2.html' + f2path = '/home/johnr_000/py101/IntroPython2016a/Examples/Session07/html_render/test_html_output2.html' + assert cmp(f1path, f2path, shallow=False) + +#Test part 3 +def test_html3(): + f1path = 'test_html_output3.html' + f2path = '/home/johnr_000/py101/IntroPython2016a/Examples/Session07/html_render/test_html_output3.html' + assert cmp(f1path, f2path, shallow=False) + +#Test part 4 +def test_html4(): + f1path = 'test_html_output4.html' + f2path = '/home/johnr_000/py101/IntroPython2016a/Examples/Session07/html_render/test_html_output4.html' + assert cmp(f1path, f2path, shallow=False) + +#Test part 5 +def test_html5(): + f1path = 'test_html_output5.html' + f2path = '/home/johnr_000/py101/IntroPython2016a/Examples/Session07/html_render/test_html_output5.html' + assert cmp(f1path, f2path, shallow=False) + + +#Test part 5 +def test_html6(): + f1path = 'test_html_output6.html' + f2path = '/home/johnr_000/py101/IntroPython2016a/Examples/Session07/html_render/test_html_output6.html' + assert cmp(f1path, f2path, shallow=False) + diff --git a/students/JohnRudolph/session8/.ipynb_checkpoints/Session 8 Notes-checkpoint.ipynb b/students/JohnRudolph/session8/.ipynb_checkpoints/Session 8 Notes-checkpoint.ipynb new file mode 100644 index 0000000..d276eee --- /dev/null +++ b/students/JohnRudolph/session8/.ipynb_checkpoints/Session 8 Notes-checkpoint.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/JohnRudolph/session8/Session 8 Notes.ipynb b/students/JohnRudolph/session8/Session 8 Notes.ipynb new file mode 100644 index 0000000..50fd865 --- /dev/null +++ b/students/JohnRudolph/session8/Session 8 Notes.ipynb @@ -0,0 +1,644 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Composed Class" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class Other(object):\n", + " \n", + " def __init__(self):\n", + " print(\"Other __init__\")\n", + " \n", + " def override(self):\n", + " print(\"Other override()\")\n", + " \n", + " def implicit(self):\n", + " print(\"Other implicit()\")\n", + " \n", + " def altered(self):\n", + " print(\"Other altered()\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyComposedClass(object):\n", + " \n", + " def __init__(self):\n", + " self.other = Other()\n", + " \n", + " def implicit(self):\n", + " self.other.implicit()\n", + " \n", + " def override(self):\n", + " print(\"MyComposedClass override()\")\n", + " \n", + " def altered(self):\n", + " print(\"MyComposedClass, BEFORE OTHER altered()\")\n", + " self.other.altered()\n", + " print(\"MyComposedClass, AFTER OTHER altered()\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Other __init__\n" + ] + } + ], + "source": [ + "my_composed_class = MyComposedClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Other implicit()\n" + ] + } + ], + "source": [ + "my_composed_class.implicit()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "MyComposedClass override()\n" + ] + } + ], + "source": [ + "my_composed_class.override()" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "MyComposedClass, BEFORE OTHER altered()\n", + "Other altered()\n", + "MyComposedClass, AFTER OTHER altered()\n" + ] + } + ], + "source": [ + "my_composed_class.altered()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Properties" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyClass(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5 # \"_\" unwritten python rule dont mess with this\n", + " \n", + " def get_x(self):\n", + " return self._x\n", + " \n", + " def set_x(self, x):\n", + " if 2 < x < 9:\n", + " self._x = x\n", + " else:\n", + " raise ValueError(\"WTF?\")" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_class = MyClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class.get_x()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_class.set_x(4)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "'MyClass' object has no attribute 'set'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmy_class\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m11\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m: 'MyClass' object has no attribute 'set'" + ] + } + ], + "source": [ + "my_class.set(11)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_other_class = MyClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "ValueError", + "evalue": "WTF?", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmy_class\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_x\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmy_class\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_x\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mmy_other_class\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_x\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36mset_x\u001b[1;34m(self, x)\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_x\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 12\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 13\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"WTF?\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mValueError\u001b[0m: WTF?" + ] + } + ], + "source": [ + "my_class.set_x(my_class.get_x() + my_other_class.get_x())" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class.get_x()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_class._x = my_class._x + my_other_class._x" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "<__main__.MyClass at 0x7f9a202a0b70>" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_class._x" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on class property in module builtins:\n", + "\n", + "class property(object)\n", + " | property(fget=None, fset=None, fdel=None, doc=None) -> property attribute\n", + " | \n", + " | fget is a function to be used for getting an attribute value, and likewise\n", + " | fset is a function for setting, and fdel a function for del'ing, an\n", + " | attribute. Typical use is to define a managed attribute x:\n", + " | \n", + " | class C(object):\n", + " | def getx(self): return self._x\n", + " | def setx(self, value): self._x = value\n", + " | def delx(self): del self._x\n", + " | x = property(getx, setx, delx, \"I'm the 'x' property.\")\n", + " | \n", + " | Decorators make defining new properties or modifying existing ones easy:\n", + " | \n", + " | class C(object):\n", + " | @property\n", + " | def x(self):\n", + " | \"I am the 'x' property.\"\n", + " | return self._x\n", + " | @x.setter\n", + " | def x(self, value):\n", + " | self._x = value\n", + " | @x.deleter\n", + " | def x(self):\n", + " | del self._x\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | __delete__(self, instance, /)\n", + " | Delete an attribute of instance.\n", + " | \n", + " | __get__(self, instance, owner, /)\n", + " | Return an attribute of instance, which is of type owner.\n", + " | \n", + " | __getattribute__(self, name, /)\n", + " | Return getattr(self, name).\n", + " | \n", + " | __init__(self, /, *args, **kwargs)\n", + " | Initialize self. See help(type(self)) for accurate signature.\n", + " | \n", + " | __new__(*args, **kwargs) from builtins.type\n", + " | Create and return a new object. See help(type) for accurate signature.\n", + " | \n", + " | __set__(self, instance, value, /)\n", + " | Set an attribute of instance to value.\n", + " | \n", + " | deleter(...)\n", + " | Descriptor to change the deleter on a property.\n", + " | \n", + " | getter(...)\n", + " | Descriptor to change the getter on a property.\n", + " | \n", + " | setter(...)\n", + " | Descriptor to change the setter on a property.\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors defined here:\n", + " | \n", + " | __isabstractmethod__\n", + " | \n", + " | fdel\n", + " | \n", + " | fget\n", + " | \n", + " | fset\n", + "\n" + ] + } + ], + "source": [ + "help(property)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "class MyClass2(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5 # \"_\" unwritten python rule dont mess with this\n", + " \n", + " def get_x(self):\n", + " return self._x\n", + " \n", + " def set_x(self, x):\n", + " if 2 < x < 9:\n", + " self._x = x\n", + " else:\n", + " raise ValueError(\"WTF?\")\n", + " \n", + " x = property(get_x, set_x)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_new_class2 = MyClass2()" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_new_class2.x = 8" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_new_class2.x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Getters and setters are used to validate inputs to a class attribute - allow for internal control of the class while still allowing users to interact with class attributes" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class MyDecoratorClass(object):\n", + " \n", + " def __init__(self):\n", + " self._x = 5 # \"_\" unwritten python rule dont mess with this\n", + " self._y = 10\n", + "\n", + "# def get_x(self):\n", + "# return self._x \n", + " \n", + " @property\n", + " def x(self):\n", + " return self._x\n", + " \n", + " \n", + "# def set_x(self, x):\n", + "# if 2 < x < 9:\n", + "# self._x = x\n", + "# else:\n", + "# raise ValueError(\"WTF?\")\n", + " \n", + " @x.setter\n", + " def x(self, x):\n", + " if 2 < x < 9:\n", + " self._x = x\n", + " else:\n", + " raise ValueError(\"WTF?\")\n", + " \n", + " #x = property(get_x, set_x)" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_decorator_class = MyDecoratorClass()" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_decorator_class.x" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_decorator_class.x += 1" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_decorator_class.x" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/LuisGonzalez/README.rst b/students/LuisGonzalez/README.rst new file mode 100644 index 0000000..6277eea --- /dev/null +++ b/students/LuisGonzalez/README.rst @@ -0,0 +1,3 @@ +readme test1 +test1 +testing diff --git a/students/LuisGonzalez/lightning/pyinstaller.pptx b/students/LuisGonzalez/lightning/pyinstaller.pptx new file mode 100644 index 0000000..ae17970 Binary files /dev/null and b/students/LuisGonzalez/lightning/pyinstaller.pptx differ diff --git a/students/LuisGonzalez/rot13.py b/students/LuisGonzalez/rot13.py new file mode 100644 index 0000000..6c6dc91 --- /dev/null +++ b/students/LuisGonzalez/rot13.py @@ -0,0 +1,50 @@ +import string +upper = "" +if __name__ == '__main__': + print("This program will encrypt your input using ROT13.") + print("Please enter the text to be encrypted") + encrypt = input() + for k in encrypt: + if k.isalpha() == False: + print(k, end='') + else: + if k.isupper(): + upper = True + else: + upper = False + outputL = chr(ord(k.lower())-13) + outputU = chr(ord(k.lower())+13) + if (ord(k.lower())) > 109: + if upper == True: + print(outputL.upper(), end='') + else: + print(outputL, end='') + else: + if upper == True: + print(outputU.upper(), end='') + else: + print(outputU, end='') + + print("") + print("Please enter the text to be encrypted") + encrypt = input() + for k in encrypt: + if k.isalpha() == False: + print(k, end='') + else: + if k.isupper(): + upper = True + else: + upper = False + outputL = chr(ord(k.lower())+13) + outputU = chr(ord(k.lower())-13) + if (ord(k.lower())) < 110: + if upper == True: + print(outputL.upper(), end='') + else: + print(outputL, end='') + else: + if upper == True: + print(outputU.upper(), end='') + else: + print(outputU, end='') diff --git a/students/LuisGonzalez/session03 b/students/LuisGonzalez/session03 new file mode 160000 index 0000000..ab9eba1 --- /dev/null +++ b/students/LuisGonzalez/session03 @@ -0,0 +1 @@ +Subproject commit ab9eba10326d8ca56d33d01ca8e7bccd70e750ff diff --git a/students/LuisGonzalez/session04/test01.rst b/students/LuisGonzalez/session04/test01.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/LuisGonzalez/session06/test_trapz.py b/students/LuisGonzalez/session06/test_trapz.py new file mode 100644 index 0000000..e9b3d1d --- /dev/null +++ b/students/LuisGonzalez/session06/test_trapz.py @@ -0,0 +1,41 @@ +from trapz import trapz + +def line(x): + return x + +def slopedline(x, M, B): + return M*x+B + +def quadratic(x, A, B, C): + return A*x**2 + B * x + C + +def isclose(a, b, tol=1e-9): + if (a-b) < tol: + return True + else: + return False + +def testtrapzline(line, a, b, N): + + answer = line*b - line*a + #assert trapz(line, a, b, N) == answer + #print(trapz(line, a, b, N)) + print(answer) + +def testslopedline(a,b, N,M,B): + answer = M*(b**2 - a**2)/2 + B*(b - a) + assert isclose(trapz(slopedline, a, b, N, M=M, B=B), answer, 0.0005) + print(trapz(slopedline, a, b, N, M=M, B=B)) + print(answer) + +def testtrapzquadratic(a, b, N, A, B, C): + answer = (A/3)*(b**3 - a**3) + B/2*(b**2 - a**2) + C*(b - a) + #not sure why my function is not as accurate as i thought it would be + #thats why i increase the closeness parameter to 0.03 + assert isclose(trapz(quadratic, a, b, N, A=A, B=B, C=C), answer, 0.03) + print(trapz(quadratic, a, b, N, A=A, B=B, C=C)) + print(answer) +testtrapzquadratic(1, 4, 5000, 1, 4, 2) +testslopedline(0,10,5000,5,10) +#testtrapzline(5,0, 10, 10) + diff --git a/students/LuisGonzalez/session06/trapz.py b/students/LuisGonzalez/session06/trapz.py new file mode 100644 index 0000000..d1268fc --- /dev/null +++ b/students/LuisGonzalez/session06/trapz.py @@ -0,0 +1,11 @@ +def trapz(fun, a, b, N, **kwargs): + + h = ((b-a)/N) + area = 0 + + while a < b: + area += (h/2) * (fun(a, **kwargs) + fun(a+h, **kwargs)) + a = a + h + + return area + diff --git a/students/LuisGonzalez/session07/html_render.py b/students/LuisGonzalez/session07/html_render.py new file mode 100644 index 0000000..d1911d7 --- /dev/null +++ b/students/LuisGonzalez/session07/html_render.py @@ -0,0 +1,112 @@ + +class Element(object): + tag = "html" + indent = 1 + def __init__(self, content = None, **kwargs): + + self.content = content + + if len(kwargs) > 0: + self.extraAttributes = str(kwargs).strip('{}') + self.extraAttributes = self.extraAttributes.replace("'", "", 2) + self.extraAttributes = " " + self.extraAttributes.replace("'", '"') + else: + self.extraAttributes = None + if self.content is None: + self.content = list() + else: + self.content = [content] + def append(self, new_content): + self.content.append(new_content) + + def render(self, file_out, ind=""): + if self.tag == "html": + file_out.write("\n") + + file_out.write(ind * Element.indent + "<" + self.tag) + if self.extraAttributes is not None: + file_out.write(self.extraAttributes) + file_out.write(">\n ") + else: + file_out.write(">\n") + + for content in self.content: + + if isinstance(content, str): + file_out.write(ind * (Element.indent + 1) + content + '\n') + else: + Element.indent += 1 + content.render(file_out, ind) + Element.indent -= 1 + + file_out.write(ind * Element.indent + "\n") + +class Html(Element): + tag = "html" + +class Body(Element): + tag = "body" + +class P(Element): + tag = "p" + +class Head(Element): + tag = "head" + +class OneLineTag(Element): + def render(self, file_out, ind=""): + file_out.write(ind * Element.indent + "<" + self.tag + "> ") + + for content in self.content: + file_out.write(content) + file_out.write(" \n") + +class Title(OneLineTag): + tag = "title" + +class SelfClosingTag(Element): + def render(self, file_out, ind=""): + file_out.write(ind * Element.indent + "<" + self.tag + " /> \n") + +class Hr(SelfClosingTag): + tag = "hr" + +class Br(SelfClosingTag): + tag = "br" + +class A(Element): + tag = "a" + def __init__(self, link, content): + self.link = link + self.content = content + self.extraAttributes = None + + def render(self, file_out, ind=""): + file_out.write(ind * Element.indent + "<" + self.tag + ' href="' + self.link + '"') + file_out.write("> " + self.content + " \n") + +class Ul(Element): + tag = "ul" + +class Li(Element): + tag = "li" + +class H(OneLineTag): + tag = "h" + def __init__(self, level, content = None): + self.tag = self.tag + str(level) + self.level = level + self.content = content + +class Meta(SelfClosingTag): + tag = "meta" + def __init__(self, **kwargs): + self.content = str(kwargs) + self.content = str(kwargs).strip('{}') + self.content = self.content.replace("'", "", 2) + self.content = " " + self.content.replace("'", '"') + + def render(self, file_out , ind=""): + file_out.write(ind * Element.indent + "<" + self.tag) + file_out.write(self.content + "/>\n") + diff --git a/students/LuisGonzalez/session07/run_html_render.py b/students/LuisGonzalez/session07/run_html_render.py new file mode 100644 index 0000000..ebcdbe9 --- /dev/null +++ b/students/LuisGonzalez/session07/run_html_render.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python + +""" +a simple script can run and test your html rendering classes. +Uncomment the steps as you add to your rendering. +""" + +from io import StringIO + +# importing the html_rendering code with a short name for easy typing. +import html_render as hr +# reloading in case you are running this in iPython +# -- we want to make sure the latest version is used +import importlib +importlib.reload(hr) + + +# writing the file out: +def render_page(page, filename): + """ + render the tree of elements + This uses StringIO to render to memory, then dump to console and + write to file -- very handy! + """ + + f = StringIO() + page.render(f, " ") + + f.seek(0) + + print(f.read()) + + f.seek(0) + open(filename, 'w').write(f.read()) + + +# Step 1 +######### +''' +page = hr.Element() + +page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text") + +page.append("And here is another piece of text -- you should be able to add any number") + +render_page(page, "test_html_output1.html") + +# ## Step 2 +# ########## + +page = hr.Html() + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) + +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output2.html") + +# # Step 3 +# ########## + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +body.append(hr.P("And here is another piece of text -- you should be able to add any number")) + +page.append(body) + +render_page(page, "test_html_output3.html") + +# Step 4 +########## + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +page.append(body) + +render_page(page, "test_html_output4.html") + +# # Step 5 +######### + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +page.append(body) + +render_page(page, "test_html_output5.html") + +# Step 6 +######### + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +body.append("And this is a ") +body.append( hr.A("http://google.com/", "link") ) +body.append("to google") + +page.append(body) + +render_page(page, "test_html_output6.html") + +# Step 7 +######### + +page = hr.Html() + +head = hr.Head() +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append( hr.H(2, "PythonClass - Class 6 example") ) + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +list = hr.Ul(id="TheList", style="line-height:200%") + +list.append( hr.Li("The first item in a list") ) +list.append( hr.Li("This is the second item", style="color: red") ) + +item = hr.Li() +item.append("And this is a ") +item.append( hr.A("http://google.com/", "link") ) +item.append("to google") + +list.append(item) + +body.append(list) + +page.append(body) + +render_page(page, "test_html_output7.html") +''' +# # Step 8 +# ######## + +page = hr.Html() + + +head = hr.Head() +head.append(hr.Meta(charset="UTF-8") ) +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append( hr.H(2, "PythonClass - Class 6 example") ) + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +list = hr.Ul(id="TheList", style="line-height:200%") + +list.append( hr.Li("The first item in a list") ) +list.append( hr.Li("This is the second item", style="color: red") ) + +item = hr.Li() +item.append("And this is a ") +item.append( hr.A("http://google.com/", "link") ) +item.append("to google") + +list.append(item) + +body.append(list) + +page.append(body) + +render_page(page, "test_html_output8.html") diff --git a/students/LuisGonzalez/week3.rst b/students/LuisGonzalez/week3.rst new file mode 100644 index 0000000..0ab3039 --- /dev/null +++ b/students/LuisGonzalez/week3.rst @@ -0,0 +1 @@ +week3 \ No newline at end of file diff --git a/students/LuisGonzalez/week4.rst b/students/LuisGonzalez/week4.rst new file mode 100644 index 0000000..e69de29 diff --git a/students/MichaelGregor/README.rst b/students/MichaelGregor/README.rst new file mode 100644 index 0000000..2870991 --- /dev/null +++ b/students/MichaelGregor/README.rst @@ -0,0 +1 @@ +This is Michael Gregor's ReadMe \ No newline at end of file diff --git a/students/MichaelGregor/Session 2/Fibonacci/series.py b/students/MichaelGregor/Session 2/Fibonacci/series.py new file mode 100644 index 0000000..3661840 --- /dev/null +++ b/students/MichaelGregor/Session 2/Fibonacci/series.py @@ -0,0 +1,12 @@ +# Admittedly this is not my own work. I simply could figure it out nor do I under stand how this works yet :/ +def main(): + fibonacci(7) + +def fibonacci(n): + x,y = 1,1 + for i in range(n-1): + x,y = y,x+y + print(x) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/students/MichaelGregor/Session 2/FizzBuzz/FizzBuzz.py b/students/MichaelGregor/Session 2/FizzBuzz/FizzBuzz.py new file mode 100644 index 0000000..1821e93 --- /dev/null +++ b/students/MichaelGregor/Session 2/FizzBuzz/FizzBuzz.py @@ -0,0 +1,36 @@ + +def main(): + FizzBuzz(100) + + +def FizzBuzz(number_count): + ''' This function to print out the numbers from 1 to n, but replace numbers divisible by 3 with "Fizz", numbers + divisible by 5 with "Buzz". Numbers divisible by both factors should display "FizzBuzz. + + :param number_count: This is the number you want to count up to + :type number_count: int + :return: None + ''' + + x = 1 + while x <= number_count: # how can you also use the range function here? + # Get the reminder of x when divided by 3 and 5 + check_three = x % 3 + check_five = x % 5 + + # Check to see if x is divisible by 3 or 5, and if it isn't, print the number + if check_five is not 0: + if check_three is not 0: + print(x) + + if check_three is 0 and check_five is 0: # can you combine this all into three if/elif/else statments? + print("FizzBuzz") + elif check_three is 0: + print("Fizz") + elif check_five is 0: + print("Buzz") + + x += 1 + +if __name__ == "__main__": + main() diff --git a/students/MichaelGregor/Session 2/GridLab/GridPart2.py b/students/MichaelGregor/Session 2/GridLab/GridPart2.py new file mode 100644 index 0000000..af5b132 --- /dev/null +++ b/students/MichaelGregor/Session 2/GridLab/GridPart2.py @@ -0,0 +1,69 @@ +import math + +def main(): + print_grid(16) + +def print_grid(size=3): + ''' This function builds the grid based on the dimensions and size of the box provided + + :param size: The total size square of the grid. (default=3) + :type size: int + :return: None + ''' + # Extremely hacky way of getting the correct sizing. There must be a better way to do this. + size = size / 2 + size = (int(size)) + + # We only want 4 squares, regardless of size, so we hard code the number of iterations for the first for loop. + for x in range(2): + print_line(2,size, isLine=True) + for x in range(size): + print_line(2,size, isLine=False) + print_line(2, size, isLine=True) + + +def print_line(num_plus, num_dash, isLine): + ''' + This function prints a line in the grid. A line with + and - characters is isLine is True. A line with + | and space characters if it is false. We keep this in one function and paramaterize the function to aid + in code reuse. + + :param num_plus: The number of + characters or columns we want in the grid + :type num_plus: int + :param num_dash: The number of - or spaces horizontally for each box + :type num_dash: int + :param isLine: If True, we will print a line that has + and - characters. If False, we do | and space characters + :type: bool + :return: None + ''' + # Checking to see if we are printing a line with +'s or a line with pipes + if isLine: + firstChar = "+" + secondChar = "-" + else: + firstChar = "|" + secondChar = " " + + plus_counter = 0 + space_counter = 0 + + # We begin looping based on the dimensions provided + + # First while loop is for the + or | character printing + while plus_counter < num_plus: + print(firstChar, end="") + + # Second while loop is for the - or space characters + while space_counter < num_dash: + print(secondChar, end="") + space_counter += 1 + + # We have to re-initialize the space counter or the loop with exit immediately after we print the next + # + or | character + space_counter=0 + + plus_counter +=1 + print(firstChar) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/students/MichaelGregor/Session 2/GridLab/GridPart3.py b/students/MichaelGregor/Session 2/GridLab/GridPart3.py new file mode 100644 index 0000000..ef5acfe --- /dev/null +++ b/students/MichaelGregor/Session 2/GridLab/GridPart3.py @@ -0,0 +1,65 @@ + +def main(): + print_grid(3,8) + +def print_grid(dimensions=2, spaces=3): + ''' This function builds the grid based on the dimensions and size of the box provided + + :param dimensions: The value squared to give the full dimensions of the grid (default=2) + :type dimensions: int + :param spaces: The number of spaces between the walls of each box(default=3) + :type spaces: int + :return: None + ''' + + for x in range(dimensions): + print_line(dimensions, spaces, isLine=True) + for x in range(spaces): + print_line(dimensions, spaces, isLine=False) + print_line(dimensions, spaces, isLine=True) + +def print_line(num_plus, num_dash, isLine): + ''' + This function prints a line in the grid. A line with + and - characters is isLine is True. A line with + | and space characters if it is false. We keep this in one function and paramaterize the function to aid + in code reuse. + + :param num_plus: The number of + characters or columns we want in the grid + :type num_plus: int + :param num_dash: The number of - or spaces horizontally for each box + :type num_dash: int + :param isLine: If True, we will print a line that has + and - characters. If False, we do | and space characters + :type: bool + :return: None + ''' + # Checking to see if we are printing a line with +'s or a line with pipes + if isLine: + firstChar = "+" + secondChar = "-" + else: + firstChar = "|" + secondChar = " " + + plus_counter = 0 + space_counter = 0 + + # We begin looping based on the dimensions provided + + # First while loop is for the + or | character printing + while plus_counter < num_plus: + print(firstChar, end="") + + # Second while loop is for the - or space characters + while space_counter < num_dash: + print(secondChar, end="") + space_counter += 1 + + # We have to re-initialize the space counter or the loop with exit immediately after we print the next + # + or | character + space_counter=0 + + plus_counter +=1 + print(firstChar) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/students/MichaelGregor/Session 2/MoneyCounting/MoneyCounting.py b/students/MichaelGregor/Session 2/MoneyCounting/MoneyCounting.py new file mode 100644 index 0000000..d14c69a --- /dev/null +++ b/students/MichaelGregor/Session 2/MoneyCounting/MoneyCounting.py @@ -0,0 +1,26 @@ +def main(): + # Prompt user for their guesses + num_pennies = float(input("Enter number of pennies: ")) + num_nickles = float(input("Enter number of nickles: ")) + num_dimes = float(input("Enter number of dimes: ")) + num_quarter = float(input("Enter number of quarters: ")) + + # Add total values based on input + total_pennies = num_pennies * .01 + total_nickles = num_nickles * .05 + total_dimes = num_dimes * .10 + total_quarters = num_quarter * .25 + + # Combine results + result = total_dimes + total_nickles + total_pennies + total_quarters + + # Check if user hits exactly 1 dollar and if not, provide how much over or under they were + if result == 1.0: + print("Congratz for winning the game") + elif result < 1.0: + print("Total amount is {} which is under $1.00".format(result)) + else: + print("Total amount is {} which is above $1.00".format(result)) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/students/MichaelGregor/Session 3/ListLab.py b/students/MichaelGregor/Session 3/ListLab.py new file mode 100644 index 0000000..94ef8a2 --- /dev/null +++ b/students/MichaelGregor/Session 3/ListLab.py @@ -0,0 +1,69 @@ +food = ["Apples", "Pears", "Oranges", "Peaches"] + +print(food) + +food.append(input("Give me another food: ")) + +print(food) + +foodLength = len(food) + +index_to_find = (int(input("Give me a number: "))) +#Check to make sure they give a valid input +while index_to_find > foodLength: + index_to_find = (int(input("There are only {} items in the list, give me another number: ".format(foodLength)))) + +index_to_find -= 1 + +print(food[index_to_find]) + +food += ["Grapes"] + +print(food) + +food.insert(0, "Pizza") + +print(food) + +food.pop() + +print(food) + +doublefood = food * 2 +removeFood = input("Give me a food to remove: ") + +#Check to make sure they give a valid input +while removeFood not in doublefood: + removeFood = input("That food isn't in the list, give me another food: ") +while removeFood in doublefood: + doublefood.remove(removeFood) + +print(doublefood) + +print(food) + +#Iterate through each food item +for item in food: + foodOpinion = "" + # Validate that they give us yes or no answer only + while not (foodOpinion == "yes" or foodOpinion == "no"): + foodOpinion = input("Do you like {}? Yes or No?".format(item)) + foodOpinion = foodOpinion.lower() + + if foodOpinion == "yes": + continue + elif foodOpinion == "no": + food.remove(item) + +print(food) + +newFood = [] + +#Iterate though each food item, reverse the letters and put into a new list +for item in food: + item = item[::-1] + newFood.append((item)) + +print(newFood) +food.pop() +print(food) \ No newline at end of file diff --git a/students/MichaelGregor/Session 3/StringFomatting.py b/students/MichaelGregor/Session 3/StringFomatting.py new file mode 100644 index 0000000..be8e6ae --- /dev/null +++ b/students/MichaelGregor/Session 3/StringFomatting.py @@ -0,0 +1,26 @@ + + +myInput = (2, 123.4567, 10000) +print("file_00{} , floatr2: ,{:.2f}, center15,{:>15.2e}".format(myInput[0], myInput[1], myInput[2])) + +for x in range(1): + myTuple = (float(input("what is age")),str(input("what is your name")),float(input("what was your age last year"))) + print("the first 3 numbers are: {:$< 8.2f}, {:&^12s}, {:*>+12.2f}".format(*myTuple)) +# the ^<> mean center right or left justify with a column width of that many numbered spaces +# e = scientific notation, d = decimal to the digits you specify, s = string and g= + + +''' see 7.1.3.1. Format Specification Mini-Language: +https://docs.python.org/2.6/library/string.html#formatstrings + +The general form of a standard format specifier is: + +format_spec ::= [[fill]align][sign][#][0][width][.precision][type] +fill ::= +align ::= "<" | ">" | "=" | "^" +sign ::= "+" | "-" | " " +width ::= integer +precision ::= integer +type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" + +''' \ No newline at end of file diff --git a/students/MichaelGregor/Session 3/classWork.py b/students/MichaelGregor/Session 3/classWork.py new file mode 100644 index 0000000..704b926 --- /dev/null +++ b/students/MichaelGregor/Session 3/classWork.py @@ -0,0 +1,31 @@ + +s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +''' +#First +length = len(s) - 1 +s[0], s[length] = s[length], s[0] +print(s) +''' +''' +#second + +sliceable = s[::2] +print(sliceable) +''' +''' +#third +length = len(s) +length -= 1 +s.pop(length) +s.pop(0) + +slicable = s[::2] + +print(slicable) +''' +''' +#fourth +s = s[::-1] +print(s) +''' + diff --git a/students/MichaelGregor/Session 3/rot13.py b/students/MichaelGregor/Session 3/rot13.py new file mode 100644 index 0000000..978508b --- /dev/null +++ b/students/MichaelGregor/Session 3/rot13.py @@ -0,0 +1,133 @@ +''' +Simple Framework that i created to flesh out a possible solution + +def encode(phrase): + + phrase_to_encode = phrase + encoded_phrase = "" + + for char in phrase_to_encode: + + newChar = ord(char) + newChar = newChar + 13 + encoded_phrase = encoded_phrase + chr(newChar) + + + print(encoded_phrase) + +def decode(phrase): + + phrase_to_decode = phrase + decoded_phrase = "" + + for char in phrase_to_decode: + + newChar = ord(char) + newChar = newChar - 13 + decoded_phrase = decoded_phrase + chr(newChar) + + print(decoded_phrase) + +def main(): + + text_to_alter = input("Enter some text you wish to alter: ") + + print("Enter 1 to encode\nEnter 2 to decode") + execution = input(":") + + while not (execution == "1" or execution == "2"): + execution = input("Please enter 1 or 2 only:") + + if execution == "1": + encode(text_to_alter) + elif execution == "2": + decode(text_to_alter) + +''' + +def main(): + + encrypted = rot13("Zntargvp sebz bhgfvqr arne pbeare", decrypt=True) + + print(encrypted) + + +def rot13(phrase, decrypt): + + encoded_phrase = "" + + for character in phrase: # We loop through each character in the phrase + + letter = character.isalpha() # As we want to preserve casing and punctuation, we need + case = character.isupper() # to check each character for both before encode/decode + + + if letter is True: + + if case is True: + + if decrypt is True: # If decypting, we case all upper case letters to lower + character = character.lower() # so we only have to subtract ascii's integers to complete + asc = ord(character) # the alphabet loop + + if asc < 110: # We need to skip over ascii's integers 91-96 which aren't + asc = asc - 19 # letters + encoded = chr(asc) + + else: + asc = asc - 13 + encoded = (chr(asc)).upper() # We bring the char back to upper to preserve casing + + elif decrypt is False: + asc = ord(character) + + if asc > 77: # When encrypting, we are 'looping' into lower case ascii + asc = asc + 19 # integers, so we need to bring it back to upper case + + encoded = (chr(asc)).upper() + + else: + asc = asc + 13 + encoded = chr(asc) + + encoded_phrase = encoded_phrase + encoded # We append our 'new' character to our encoded/decode phrase + + elif case is False: + + if decrypt is True: + asc = ord(character) + + if asc < 110: # When looping backward we run into uppercase letters so we + asc = asc - 19 # bring the character to lower to preserve case. + + encoded = (chr(asc)).lower() + + else: + asc = asc - 13 + encoded = chr(asc) + + elif decrypt is False: + character = character.upper() # We send this to upper to start so we can just add ascii + asc = ord(character) # integers and send them to lower to preserve case after + # encode/decode + if asc > 77: + asc = asc + 19 + encoded = chr(asc) + else: + asc = asc + 13 + encoded = chr(asc) + + encoded = encoded.lower() + + encoded_phrase = encoded_phrase + encoded + + else: + encoded_phrase = encoded_phrase + character # If character isn't an alpha char, we preserve it and move + # to the next character. + return encoded_phrase + +if __name__ == '__main__': + main() + + +# nice job! diff --git a/students/MichaelGregor/Session 4/dict_lab.py b/students/MichaelGregor/Session 4/dict_lab.py new file mode 100644 index 0000000..e044b89 --- /dev/null +++ b/students/MichaelGregor/Session 4/dict_lab.py @@ -0,0 +1,45 @@ + + +def main(): + + myDict = {'name':'Chris', + 'city':'Seattle', + 'cake':'Chocolate'} + + print(myDict) + + myDict.pop('cake') + + print(myDict) + + myDict.update({'fruit':'Mango'}) + + print(myDict) + print(myDict.keys()) + + print(myDict.values()) + + find = 'cake' in myDict + print(find) + + find = 'Mango' in myDict + print(find) + + myDict = {'name':'Chris', + 'city':'Seattle', + 'cake':'Chocolate'} + + newDict = {('name', 'city', 'cake')} + count = 0 + for key in myDict: + value = myDict.get(key) + count = value.count('t') + newDict.update(key, count) + + print(newDict) + + + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/students/MichaelGregor/Session 4/mailroom.py b/students/MichaelGregor/Session 4/mailroom.py new file mode 100644 index 0000000..a613a79 --- /dev/null +++ b/students/MichaelGregor/Session 4/mailroom.py @@ -0,0 +1,343 @@ +import os +import platform +from operator import itemgetter + +# Create global dictionaries so that multiple methods can used them for data flow control + +donor_list = {'Mike Singletary':[50.00, 100.00, 200.00], + 'Mike Ditka':[300.00, 500.00, 50.00], + 'Sweetness': [20.00, 700.00], + 'The Fridge': [900.00, 2000.00], + 'Dan Hampton': [3000.00]} + +donor_final_report_list = {} + + +def show_main_menu(): + """ + Shows the main menu and is the beginning of the control flow + + :return: None + """ + + menu_option = '' + + while not (menu_option == '1' or menu_option == '2' or menu_option == '3'): + clear_screen() + + print("**************************************************") + print("**************************************************") + print("* *") + print("* THE MAILROOM *") + print("* *") + print("**************************************************") + print("* *") + print("* What would you like to do today? *") + print("* 1. Send a Thank you *") + print("* 2. Create a Report *") + print("* 3. Exit Program *") + print("* *") + print("**************************************************") + print("**************************************************") + menu_option = input(":") + + if menu_option == '1': + send_thank_you() + elif menu_option == '2': + create_report() + else: + print("Thank you for using The Mailroom!") + + +def send_thank_you(): + """ + Launches the Send Thank You control flow. Use to list the current donors available or create a new donor. + + :return: None + """ + + full_name = input("Please provide the full name: ") + + if full_name == "list": + show_donor_list() + + elif full_name not in get_donor_names(): + + create_new_name = '' + + while not (create_new_name == '1' or create_new_name == '2'): + + print(("{} is not in the current list of donors\n Do you wish to create a new donor?".format(full_name))) + print("1. Yes") + print("2. No") + create_new_name = input(":") + + if create_new_name == '1': + add_donor_donation(full_name) + else: + show_main_menu() + elif full_name in get_donor_names(): + + donor_management(full_name) + + +def donor_management(full_name): + """ + This function is used to Add donations to a specific donor and to trigger the final thank you email. + + :param full_name: The name of the donor who we are adding a donation to or sending email + :type full_name: String + :return: None + """ + + option = '' + + while not (option == '1' or option == '2' or option == '3'): + + clear_screen() + print("**************************************************") + print(" {} ".format(full_name)) + print("* *") + print("* Choose and option *") + print("* 1. Add a donation *") + print("* 2. Send Thank You email *") + print("* 3. Go Back *") + print("* *") + print("**************************************************") + option = input(":") + + if option == '1': + add_donor_donation(full_name) + elif option == '2': + send_email(full_name) + elif option == '3': + show_main_menu() + + +def create_report(): + """ + This prints a report of all the donors, their total donation amount, number of donations, and average + + :return: + """ + + clear_screen() + + donors = get_donor_names() + + donor_totals_list = {} + + for name in donors: # We need to get each donor and start to collect + donor_report_list = [] # data to build the report. + + total_donations = 0.0 + num_of_donations = float(len(get_donor_donations_data(name))) + donations = get_donor_donations_data(name) + + for donation in donations: # All the donor donations are in List format so + total_donations += donation # so we have to iterate through each donation + # and total them together. + average_donation = total_donations / num_of_donations + donor_report_list.append(total_donations) # Here we begin to build a new Dictionary object + donor_report_list.append(average_donation) # to hold the data we need for the final report. + donor_report_list.append(int(num_of_donations)) + + donor_totals_list.update({name: total_donations}) # We create a new totals dictionary object so + # so we can use it later to sort the report by + donor_final_report_list.update({name: donor_report_list}) # total amount of donations. + + print("*****************************************************************") + print("* DONOR REPORT *") + print("* *") + print(" {0:20} {1:7} {2:9}{3:5}".format("NAME", "TOTAL", "NUMBER", "AVERAGE")) + + + # Woot, my only stack overflow answer in this program. So we are sorting each name in the dictionary by the + # donor_totals_list. This will by default sort smallest to largest. The 'reverse=True' statement allows the + # us to sort the names by the donation total largest to smallest. We then iterate through each name, gather a + # the donor report which is a List item pulled from the global donor_final_report_list and format the output in + # the print statement. + + for name,value in sorted(donor_totals_list.items(), key=itemgetter(1), reverse=True): + donor_report = get_donor_donations_data(name, final=True) + print(" {0:20} ${1:9} {2:7} ${3:.2f}".format(name, donor_report[0], donor_report[2], donor_report[1])) + + print("* *") + print("*****************************************************************") + input("Press Enter to continue") + + show_main_menu() + + +def add_donor_donation(full_name): + """ + This adds a donation amount to a specific donor. + + :param full_name: Name of the donor that we are adding a donation too. + :type full_name: String + :return: Donor name (full_name) + """ + + donations = get_donor_donations_data(full_name) + print("Please enter a donation amount for {}".format(full_name)) + donation_amount = '' + + while not donation_amount.isdigit(): # Check to make sure the donation amount is a + donation_amount = input("No decimals please:$") # a integer number as a string to prevent + # weird data being entered. + donation_amount = float(donation_amount) # We then cast it as a float before we add it + donations.append(donation_amount) # to the donor's donations for easy math later. + donor_list.update({full_name: donations}) + + print("A ${:.2f} donation has been added to {}'s donation history".format(donation_amount, full_name)) + input("Press Enter to continue") + + donor_management(full_name) + + +def send_email(full_name): + """ + Formats an email and prints it to the screen. + + :param full_name: Donor Name + :type full_name: String + :return: Donor Name (full_name) + """ + + donations = get_donor_donations_data(full_name) + total_donations = 0.0 + for donation in donations: + total_donations += donation + + print("Dear {},\n".format(full_name)) + print("Thank you for your donations which have totaled up to ${:.2f}! We greatly appreciate your generosity and you can " + "be assured that these funds will be put to good use.\n\nIf you have any questions at all, please don't " + "hesitate to contact me at mgregor@hahaigotyourmoney.com\n\nMichael Gregor\nDirector of Deception".format(total_donations)) + + input("\n\n\nPress enter to continue") + + donor_management(full_name) + + +def clear_screen(): + """ + Determines what operating system is currently running and executes the applicable command line argument to clear + the screen. + + :return: None + """ + + operating_systems = platform.system() + + if operating_systems == 'Windows': + os.system('cls') + else: + os.system('clear') + + +def get_donor_names(): + """ + Iterates through our donor list and returns the names (i.e. the Keys for the donor dictionary objects) + + :return: Donor names as a List object (names) + """ + + donors = get_donor_list() + names = [] + + for name in donors: + names.append(name) + + return names + + +def get_donor_donations_data(donar_name, final=False): + """ + Gets the donation data for a particular donor. + + :param donar_name: Donor name + :type donar_name: String + :param final: Checks to see if we are getting data for the final report + :type final: Bool + + :return: Returns the List Object inside the applicable donor dictionary (donor[name]) + """ + + if final == True: + donors = get_final_report_list() + else: + donors = get_donor_list() + + for name in donors: + if name == donar_name: + return donors[name] + + +def get_donor_list(): + """ + Gets the global donor list + + :return: Dictionary Object of Donors and their donations (donor_list) + """ + + global donor_list + return donor_list + + +def get_final_report_list(): + """ + Gets the global donor final report + + :return: Dictionary Object of Donors and their total donation amount, number of donations, and average + donation (donor_final_report_list) + """ + + global donor_final_report_list + return donor_final_report_list + + +def show_donor_list(): + """ + Show the list of donor names + + :return: None + """ + + clear_screen() + + names = get_donor_names() + + print("**************************************************") + print("* *") + print("* DONORS *") + print("* *") + for name in names: + print(" {} ".format(name)) + print("* *") + print("**************************************************") + + send_thank_you() + + +def main(): + """ + Launches Program + + :return: None + """ + + show_main_menu() + + +if __name__ == "__main__": + main() + + + + + + + + + + diff --git a/students/MichaelGregor/Session 5/FilePath.py b/students/MichaelGregor/Session 5/FilePath.py new file mode 100644 index 0000000..4657c69 --- /dev/null +++ b/students/MichaelGregor/Session 5/FilePath.py @@ -0,0 +1,13 @@ +import os + +for file in os.listdir(): + print(os.path.abspath(file)) + +with open('students.txt', 'r') as f: + file = f.read() + +with open('students_copy.txt', 'w') as f: + f.write(file) + +for file in os.listdir(): + print(os.path.abspath(file)) \ No newline at end of file diff --git a/students/MichaelGregor/Session 5/Mike Ditka_Letter.txt b/students/MichaelGregor/Session 5/Mike Ditka_Letter.txt new file mode 100644 index 0000000..0fdb4b7 --- /dev/null +++ b/students/MichaelGregor/Session 5/Mike Ditka_Letter.txt @@ -0,0 +1,8 @@ +Dear Mike Ditka, + +Thank you for your donations which have totaled up to $850.00! We greatly appreciate your generosity and you can be assured that these funds will be put to good use. + +If you have any questions at all, please don't hesitate to contact me at mgregor@hahaigotyourmoney.com + +Michael Gregor +Director of Deception diff --git a/students/MichaelGregor/Session 5/files.py b/students/MichaelGregor/Session 5/files.py new file mode 100644 index 0000000..db92699 --- /dev/null +++ b/students/MichaelGregor/Session 5/files.py @@ -0,0 +1,9 @@ +language_set = set() + +with open('students.txt', 'r') as f: + for line in f: + student_info = line.split(':')[1] + language_list = student_info.split(',') + for language in language_list: + language_set.add(language) +print(language_set) diff --git a/students/MichaelGregor/Session 5/mailroom_update.py b/students/MichaelGregor/Session 5/mailroom_update.py new file mode 100644 index 0000000..3989e91 --- /dev/null +++ b/students/MichaelGregor/Session 5/mailroom_update.py @@ -0,0 +1,350 @@ +import os +import platform +from operator import itemgetter + +# Create global dictionaries so that multiple methods can used them for data flow control + +donor_list = {'Mike Singletary':[50.00, 100.00, 200.00], + 'Mike Ditka':[300.00, 500.00, 50.00], + 'Sweetness': [20.00, 700.00], + 'The Fridge': [900.00, 2000.00], + 'Dan Hampton': [3000.00]} + +donor_final_report_list = {} + +ap = os.path.abspath('mailroom_update') + + +def show_main_menu(): + """ + Shows the main menu and is the beginning of the control flow + + :return: None + """ + + menu_option = '' + + while not (menu_option == '1' or menu_option == '2' or menu_option == '3'): + clear_screen() + + print("**************************************************") + print("**************************************************") + print("* *") + print("* THE MAILROOM *") + print("* *") + print("**************************************************") + print("* *") + print("* What would you like to do today? *") + print("* 1. Send a Thank you *") + print("* 2. Create a Report *") + print("* 3. Exit Program *") + print("* *") + print("**************************************************") + print("**************************************************") + menu_option = input(":") + + if menu_option == '1': + send_thank_you() + elif menu_option == '2': + create_report() + else: + print("Thank you for using The Mailroom!") + + +def send_thank_you(): + """ + Launches the Send Thank You control flow. Use to list the current donors available or create a new donor. + + :return: None + """ + + full_name = input("Please provide the full name: ") + + if full_name == "list": + show_donor_list() + + elif full_name not in get_donor_names(): + + create_new_name = '' + + while not (create_new_name == '1' or create_new_name == '2'): + + print(("{} is not in the current list of donors\n Do you wish to create a new donor?".format(full_name))) + print("1. Yes") + print("2. No") + create_new_name = input(":") + + if create_new_name == '1': + add_donor_donation(full_name) + else: + show_main_menu() + elif full_name in get_donor_names(): + + donor_management(full_name) + + +def donor_management(full_name): + """ + This function is used to Add donations to a specific donor and to trigger the final thank you email. + + :param full_name: The name of the donor who we are adding a donation to or sending email + :type full_name: String + :return: None + """ + + option = '' + + while not (option == '1' or option == '2' or option == '3'): + + clear_screen() + print("**************************************************") + print(" {} ".format(full_name)) + print("* *") + print("* Choose and option *") + print("* 1. Add a donation *") + print("* 2. Send Thank You email *") + print("* 3. Go Back *") + print("* *") + print("**************************************************") + option = input(":") + + if option == '1': + add_donor_donation(full_name) + elif option == '2': + send_email(full_name) + elif option == '3': + show_main_menu() + + +def create_report(): + """ + This prints a report of all the donors, their total donation amount, number of donations, and average + + :return: + """ + + clear_screen() + + donors = get_donor_names() + + donor_totals_list = {} + + for name in donors: # We need to get each donor and start to collect + donor_report_list = [] # data to build the report. + + total_donations = 0.0 + num_of_donations = float(len(get_donor_donations_data(name))) + donations = get_donor_donations_data(name) + + for donation in donations: # All the donor donations are in List format so + total_donations += donation # so we have to iterate through each donation + # and total them together. + average_donation = total_donations / num_of_donations + donor_report_list.append(total_donations) # Here we begin to build a new Dictionary object + donor_report_list.append(average_donation) # to hold the data we need for the final report. + donor_report_list.append(int(num_of_donations)) + + donor_totals_list.update({name: total_donations}) # We create a new totals dictionary object so + # so we can use it later to sort the report by + donor_final_report_list.update({name: donor_report_list}) # total amount of donations. + + print("*****************************************************************") + print("* DONOR REPORT *") + print("* *") + print(" {0:20} {1:7} {2:9}{3:5}".format("NAME", "TOTAL", "NUMBER", "AVERAGE")) + + + # Woot, my only stack overflow answer in this program. So we are sorting each name in the dictionary by the + # donor_totals_list. This will by default sort smallest to largest. The 'reverse=True' statement allows the + # us to sort the names by the donation total largest to smallest. We then iterate through each name, gather a + # the donor report which is a List item pulled from the global donor_final_report_list and format the output in + # the print statement. + + for name,value in sorted(donor_totals_list.items(), key=itemgetter(1), reverse=True): + donor_report = get_donor_donations_data(name, final=True) + print(" {0:20} ${1:9} {2:7} ${3:.2f}".format(name, donor_report[0], donor_report[2], donor_report[1])) + + print("* *") + print("*****************************************************************") + input("Press Enter to continue") + + show_main_menu() + + +def add_donor_donation(full_name): + """ + This adds a donation amount to a specific donor. + + :param full_name: Name of the donor that we are adding a donation too. + :type full_name: String + :return: Donor name (full_name) + """ + + donations = get_donor_donations_data(full_name) + print("Please enter a donation amount for {}".format(full_name)) + donation_amount = '' + + while not donation_amount.isdigit(): # Check to make sure the donation amount is a + donation_amount = input("No decimals please:$") # a integer number as a string to prevent + # weird data being entered. + donation_amount = float(donation_amount) # We then cast it as a float before we add it + donations.append(donation_amount) # to the donor's donations for easy math later. + donor_list.update({full_name: donations}) + + print("A ${:.2f} donation has been added to {}'s donation history".format(donation_amount, full_name)) + input("Press Enter to continue") + + donor_management(full_name) + + +def send_email(full_name): + """ + Formats an email and prints it to the screen. + + :param full_name: Donor Name + :type full_name: String + :return: Donor Name (full_name) + """ + + donations = get_donor_donations_data(full_name) + total_donations = 0.0 + for donation in donations: + total_donations += donation + + header = ("Dear {},\n".format(full_name)) + body = ("Thank you for your donations which have totaled up to ${:.2f}! We greatly appreciate your generosity and you can " + "be assured that these funds will be put to good use.\n\nIf you have any questions at all, please don't " + "hesitate to contact me at mgregor@hahaigotyourmoney.com\n\nMichael Gregor\nDirector of Deception".format(total_donations)) + + input("File written to disk.\nPress enter to continue") + + f = open('{}_Letter.txt'.format(full_name), 'w+') + f.write(header + '\n') + f.write(body + '\n') + f.close() + + donor_management(full_name) + + +def clear_screen(): + """ + Determines what operating system is currently running and executes the applicable command line argument to clear + the screen. + + :return: None + """ + + operating_systems = platform.system() + + if operating_systems == 'Windows': + os.system('cls') + else: + os.system('clear') + + +def get_donor_names(): + """ + Iterates through our donor list and returns the names (i.e. the Keys for the donor dictionary objects) + + :return: Donor names as a List object (names) + """ + + donors = get_donor_list() + names = [] + + for name in donors: + names.append(name) + + return names + + +def get_donor_donations_data(donar_name, final=False): + """ + Gets the donation data for a particular donor. + + :param donar_name: Donor name + :type donar_name: String + :param final: Checks to see if we are getting data for the final report + :type final: Bool + + :return: Returns the List Object inside the applicable donor dictionary (donor[name]) + """ + + if final == True: + donors = get_final_report_list() + else: + donors = get_donor_list() + + for name in donors: + if name == donar_name: + return donors[name] + + +def get_donor_list(): + """ + Gets the global donor list + + :return: Dictionary Object of Donors and their donations (donor_list) + """ + + global donor_list + return donor_list + + +def get_final_report_list(): + """ + Gets the global donor final report + + :return: Dictionary Object of Donors and their total donation amount, number of donations, and average + donation (donor_final_report_list) + """ + + global donor_final_report_list + return donor_final_report_list + + +def show_donor_list(): + """ + Show the list of donor names + + :return: None + """ + + clear_screen() + + names = get_donor_names() + + print("**************************************************") + print("* *") + print("* DONORS *") + print("* *") + for name in names: + print(" {} ".format(name)) + print("* *") + print("**************************************************") + + send_thank_you() + + +def main(): + """ + Launches Program + + :return: None + """ + + show_main_menu() + + +if __name__ == "__main__": + main() + + + + + + + + + + diff --git a/students/MichaelGregor/Session 5/students.txt b/students/MichaelGregor/Session 5/students.txt new file mode 100644 index 0000000..7311d13 --- /dev/null +++ b/students/MichaelGregor/Session 5/students.txt @@ -0,0 +1,24 @@ +Bindhu, Krishna: +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: \ No newline at end of file diff --git a/students/MichaelGregor/Session 6/asserts.py b/students/MichaelGregor/Session 6/asserts.py new file mode 100644 index 0000000..ed7104b --- /dev/null +++ b/students/MichaelGregor/Session 6/asserts.py @@ -0,0 +1,44 @@ +def test_scoring(): + assert score('hand_weapon', 'small') == 1 + assert score('hand_weapon', 'medium') == 2 + assert score('hand_weapon', 'large') == 3 + assert score('gun', 'small') == 5 + assert score('gun', 'medium') == 8 + assert score('gun', 'large') == 13 + assert score('flower_power', 'small') == 21 + assert score('flower_power', 'medium') == 34 + assert score('flower_power', 'large') == 55 + +def hand_weapon(weapon_size): + if weapon_size == 'small': + return 1 + elif weapon_size == 'medium': + return 2 + elif weapon_size == 'large': + return 3 + +def gun(weapon_size): + if weapon_size == 'small': + return 5 + elif weapon_size == 'medium': + return 8 + elif weapon_size == 'large': + return 13 + +def flower_power(weapon_size): + if weapon_size == 'small': + return 21 + elif weapon_size == 'medium': + return 34 + elif weapon_size == 'large': + return 55 + +def score(weapon_type, weapon_size): + + if weapon_type == 'hand_weapon': + return hand_weapon(weapon_size) + elif weapon_type == 'gun': + return gun(weapon_size) + elif weapon_type == 'flower_power': + return flower_power(weapon_size) + diff --git a/students/MikeSchincariol/README.rst b/students/MikeSchincariol/README.rst new file mode 100644 index 0000000..1bf82df --- /dev/null +++ b/students/MikeSchincariol/README.rst @@ -0,0 +1 @@ +SOme text :) diff --git a/students/MikeSchincariol/session1/.keep b/students/MikeSchincariol/session1/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session10/.keep b/students/MikeSchincariol/session10/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session2/.keep b/students/MikeSchincariol/session2/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session2/FizzBuzz/FizzBuzz.py b/students/MikeSchincariol/session2/FizzBuzz/FizzBuzz.py new file mode 100644 index 0000000..8706ced --- /dev/null +++ b/students/MikeSchincariol/session2/FizzBuzz/FizzBuzz.py @@ -0,0 +1,18 @@ + +def FizzBuzz(n): + if not isinstance(n, int): + raise TypeError("FIZZBUZZ: Argument of type {0} is not supported. Only type 'int' is allowed".format(type(n))) + for i in range(1, n+1): + if (i % 3 == 0 and i % 5 == 0): + print('FizzBuzz') + elif (i % 3 == 0): + print('Fizz') + elif (i % 5 == 0): + print('Buzz') + else: + print('{0}'.format(i)) + + +if __name__ == "__main__": + FizzBuzz(60) + #FizzBuzz("qwerty") \ No newline at end of file diff --git a/students/MikeSchincariol/session2/MoneyCounting/moneycounting.py b/students/MikeSchincariol/session2/MoneyCounting/moneycounting.py new file mode 100644 index 0000000..277970c --- /dev/null +++ b/students/MikeSchincariol/session2/MoneyCounting/moneycounting.py @@ -0,0 +1,74 @@ +import math + +#A method to get input from the user and validate that it is an int +def get_integer_input(prompt): + while True: + val_is_ok = False + val = input(prompt) + try: + val = int(val) + val_is_ok = True + except: + #Normally too wide an exception scope, but, in this case, + #anything that isn't explictly an integer is a problem we + #want to catch. + print("The quantity entered must be an integer") + + if val_is_ok: + break + return val + + +#Main program +#Opening banner +print("-- The Money Counting Game --") +print("To play, enter the quantity of each type of coin.") +print("If the sum of all the coin you enter totals $1, you win!") + +#Play again loop +while True: + + print("\n") + num_pennies = get_integer_input("Enter the number of pennies : ") + num_nickels = get_integer_input("Enter the number of nickels : ") + num_dimes = get_integer_input("Enter the number of dimes : ") + num_quarters = get_integer_input("Enter the number of quarters: ") + + total = round((1*num_pennies + 5*num_nickels + 10*num_dimes + 25*num_quarters) / 100, 2) + delta = round(total - 1.0, 2) + + if total == 1: + print(" _ _ __ _______ _ _ _ _ ______ _____ _ _ ") + print("| | | \ \ / /_ _| \ | | \ | | ____| __ \ | | |") + print("| | | \ \ /\ / / | | | \| | \| | |__ | |__) | | | |") + print("| | | \ \/ \/ / | | | . ` | . ` | __| | _ / | | |") + print("|_|_| \ /\ / _| |_| |\ | |\ | |____| | \ \ |_|_|") + print("(_|_) \/ \/ |_____|_| \_|_| \_|______|_| \_\ (_|_)") + else: + print("__ __ _ __") + print("\ \ / / | | _ / /") + print(" \ \_/ /__ _ _ | | ___ ___ ___ (_) |") + print(" \ / _ \| | | | | | / _ \/ __|/ _ \ | |") + print(" | | (_) | |_| | | |___| (_) \__ \ __/ _| |") + print(" |_|\___/ \__,_| |______\___/|___/\___| (_) |") + print(" \\_\\") + print("\n") + print("Your money totalled: ${0}, which was a difference of ${1} from the goal.".format(total, delta)) + + + done = False + while True: + print("\n") + play_again = input("Would you like to play again [y/n]? ").lower() + if play_again not in ['y', 'n']: + print("Invalid choice. Cmon...it's only 2 keys...you can get this right.") + print("Now concentrate...") + continue + elif play_again in ['n']: + done = True + break + else: + done = False + break + if done : + break diff --git a/students/MikeSchincariol/session3/.keep b/students/MikeSchincariol/session3/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session3/mailroom.py b/students/MikeSchincariol/session3/mailroom.py new file mode 100755 index 0000000..938d6f6 --- /dev/null +++ b/students/MikeSchincariol/session3/mailroom.py @@ -0,0 +1,196 @@ +#!/usr/bin/python3 + +def show_main_menu(): + ''' Present the menu to find out what the user wants to do. ''' + ''' Returns an int giving the menu item selected. ''' + while True: + print("") + print("MAIN MENU") + print("(1) Send a Thank You") + print("(2) Print Report") + print("(3) Exit") + choice = input("Choice --> ") + try: + choice = int(choice) + if choice not in [1, 2, 3]: + print("Invalid selection. Please try again.") + else: + break + except: + print("Invalid selection. Please try again.") + finally: + pass + return choice + + +def print_donors(donor_list): + ''' Prints a list of the donors to the screen + :param donor_list: List object containing donor first name, last name, and list of donation amounts + :return: Nothing + ''' + print("") + for idx, donor in enumerate(donor_list): + print("DONOR: {0:3} NAME: {1:20} AMOUNTS: {2}". format(idx, donor[0], str(donor[1]))) + + +def is_donor_in_list(donor_list, full_name): + ''' Checks if the donor, given by the string full_name, is in the donor_list. + :param donor_list: List object containing donors full name and list of donation amounts + :return: True if donor in list, otherwise, false. + ''' + found = False + for donor in donor_list: + if full_name == donor[0]: + found = True + break + return found + + +def find_donor_idx(donor_list, full_name): + ''' CHecks if the donor, given by the string full_name, is in the donor_list and returns its index if it is. + :param donor_list: List object containing donors full name and list of donatino amounts + :param full_name: Donors full name as a string. + :return: Integer index giving the location of the donor in donor_list + ''' + found_at_idx = None + for idx, donor in enumerate(donor_list): + if donor[0] == full_name: + found_at_idx = idx + break + return found_at_idx + + +def thank(donor_list): + ''' Carries out the tasks necessary to enter, possibly create a new donor, + add a donation amount to the donor, and create a thank-you letter. + :param donor_list: List object containing donor first name, last name, and list of donation amounts + :return: Nothing + ''' + while True: + print("") + cmd = input("[Full Name|'list'|'thank_all'|'back'] --> ").lower() + if cmd == "list": + print_donors(donors) + continue + elif cmd == "back": + break + elif cmd == "thank_all": + # The user wants to print thank-you's to all donors + # Loop over all the donors, find the total sum donated. Then craft + # a thank-you message and write it to both the terminal and to disk. + for donor in donor_list: + donor_name = donor[0] + donation_sum = sum(donor[1]) + + msg = ("\n" + "Dear {0}, \n" + "\n" + "Thank you for your generous donations totalling ${1}.\n" + "Trundle and Biffs all over the world will benefit from your kindness!\n" + "\n" + "Yours Truely,\n" + " Bing Flaherty").format(donor_name, donation_sum) + print(msg) + with open("{0}_thank_you.txt".format(donor_name), "w") as fd: + fd.writelines(msg) + + else: + # The user provided a name to add to the list. + # Adding a donation and printing a thank-you. + # First check if the donor is in the list already, if not add them. + full_name = cmd.title() + if not(is_donor_in_list(donors, full_name)): + donor_list.append([full_name, []]) + + # Get the donation amount... + while True: + amnt = input("Donation amount --> ") + try: + amnt = int(amnt) + break + except: + print("Invalid donation amount. Please try again. Input only numbers") + finally: + pass + # Find the donor entry in the donor list and append the donation amount + donor_entry_idx = find_donor_idx(donor_list, full_name) + donor_entry = donor_list[donor_entry_idx] + donor_entry[1].append(amnt) + + # Compose thank-you message and print to the terminal and a file + msg = ("\n" + "Dear {0}, \n" + "\n" + "Thank you for your generous donation of ${1}.\n" + "Trundle and Biffs all over the world will benefit from your kindness!\n" + "\n" + "Yours Truely,\n" + " Bing Flaherty").format(full_name, amnt) + print(msg) + with open("{0}_thank_you.txt".format(full_name), "w") as fd: + fd.writelines(msg) + + + + + + +def report(donor_list): + '''Compute number of donations, total donation amount and average donation amount for each user. + and print results in tabular format to the screen. + ''' + report_table = [] + for donor in donor_list: + total_donations = sum(donor[1]) + avg_donations = round(total_donations / len(donor[1]), 2) + report_table.append([donor[0], total_donations, avg_donations]) + + # Sort the list by total donation amount + report_table.sort(key=report_table_sort_by_total_donation_amount_fn, reverse=True) + + # Print sorted donor list to screen + print("") + print("-"*80) + print("{0:20} | {1:>20} | {2:>20}".format("NAME", "TOTAL DONATIONS", "AVG DONATION")) + print("-"*80) + for donor in report_table: + print("{0:20} | ${1:>20,.2f} | ${2:>20,.2f}". format(donor[0], + donor[1], + donor[2])) + print("-"*80) + + +def report_table_sort_by_total_donation_amount_fn(item): + ''' Returns the second item from the list item given to it + :param item: A list item + :return: The second item from the list item + ''' + return item[1] + + + + +if __name__ == "__main__": + + # Print program banner + print("----------------") + print("--- Mailroom ---") + print("----------------") + + # Populate the starting donors database + donors = list() + donors.append(["Steve Robertson", [100, 50]]) + donors.append(["Jane Iverson", [10]]) + donors.append(["Pac Liquor", [1000, 5000]]) + donors.append(["Anita Henchman", [10, 25, 75]]) + donors.append(["Zack Wing", [25, 100, 250]]) + + # Main kernel of program + while True: + choice = show_main_menu() + if choice in [1]: + thank(donors) + elif choice in [2]: + report(donors) + else: + exit() diff --git a/students/MikeSchincariol/session3/rot13.py b/students/MikeSchincariol/session3/rot13.py new file mode 100755 index 0000000..8f4941f --- /dev/null +++ b/students/MikeSchincariol/session3/rot13.py @@ -0,0 +1,48 @@ +#!/usr/bin/python3 + +def rot13(text): + + # Create the translations tables to feed to str.translate() + lc_first_half = "abcdefghijklm" + lc_second_half = "nopqrstuvwxyz" + lc_translate = str.maketrans(lc_first_half + lc_second_half, + lc_second_half + lc_first_half) + + uc_first_half = lc_first_half.upper() + uc_second_half = lc_second_half.upper() + uc_translate = str.maketrans(uc_first_half + uc_second_half, + uc_second_half + uc_first_half) + + # Loop over each character + retval = "" + for char in text: + if char.isspace(): + # Pass spaces through unmodified + retval += char + elif char.islower(): + # Convert lower case letter + retval += str(char).translate(lc_translate) + elif char.isupper(): + # Convert upper case letter + retval += str(char).translate(uc_translate) + else: + # Pass numbers and punctuation through unmodified + retval += char + + # Done. Return the result back to the caller. + return retval + + +# If not called as a function, run some tests +if __name__ == "__main__": + test_val = '"Hello World"' + result = rot13(test_val) + assert(result == '"Uryyb Jbeyq"') + print("Test {0} OK: {1} -> {2}".format(1, test_val, result)) + + test_val = '"Zntargvp sebz bhgfvqr arne pbeare"' + result = rot13(test_val) + assert(result == '"Magnetic from outside near corner"') + print("Test {0} OK: {1} -> {2}".format(2, test_val, result)) + +# great job both encrypting and decrpyting without requiring the user to spcecify which diff --git a/students/MikeSchincariol/session4/.keep b/students/MikeSchincariol/session4/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session4/dict_lab.py b/students/MikeSchincariol/session4/dict_lab.py new file mode 100755 index 0000000..46c68e0 --- /dev/null +++ b/students/MikeSchincariol/session4/dict_lab.py @@ -0,0 +1,76 @@ +#!/usr/bin/python3 + +# Create a dictionary containing “name”, “city”, and “cake” for “Chris” +# from “Seattle” who likes “Chocolate”. +d = {"name": "Chris", + "city": "Seattle", + "cake": "Chocolate"} + + +# Display the dictionary +print(d) + + +# Delete the entry for “cake”. +del d['cake'] + + +# Display the dictionary +print(d) + + +# Add an entry for “fruit” with “Mango” and display the dictionary. +d['fruit'] = "Mango" +# Display the dictionary keys. +print("") +for key in d.keys(): print(key) +print("") +# Display the dictionary values. +print("") +for val in d.values(): print(val) +print("") +# Display whether or not “cake” is a key in the dictionary (i.e. False) (now). +if "cake" in list(d.keys()): + print("True") +else: + print("False") +# Display whether or not “Mango” is a value in the dictionary (i.e. True). +if "Mango" in list(d.values()): + print("True") +else: + print("False") + +# Using the dictionary from item 1: Make a dictionary using the same keys but with the number of ‘t’s in each value. +d = {"name": "Christ".count('t'), + "city": "Seattle".count('t'), + "cake": "Chocolate".count('t')} + + +# Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible 2, 3 and 4. +s2 = set([x for x in range(0, 21) if x % 2 == 0]) +s3 = set([x for x in range(0, 21) if x % 3 == 0]) +s4 = set([x for x in range(0, 21) if x % 4 == 0]) + +# Display the sets. +print("Numbers divisible by 2: {0}".format(s2)) +print("Numbers divisible by 3: {0}".format(s3)) +print("Numbers divisible by 4: {0}".format(s4)) + + +# Display if s3 is a subset of s2 (False) +s3.issubset(s2) + +# and if s4 is a subset of s2 (True). +s4.issubset(s2) + +# Create a set with the letters in ‘Python’ and add ‘i’ to the set. +s5 = set("Python") +s5.add("i") + + +# Create a frozenset with the letters in ‘marathon’ +f1 = frozenset("marathon") + +# Display the union and intersection of the two sets. +s5.union(f1) +s5.intersection(f1) diff --git a/students/MikeSchincariol/session5/.keep b/students/MikeSchincariol/session5/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session5/codingbat_sleep_in.py b/students/MikeSchincariol/session5/codingbat_sleep_in.py new file mode 100644 index 0000000..976a3a7 --- /dev/null +++ b/students/MikeSchincariol/session5/codingbat_sleep_in.py @@ -0,0 +1,2 @@ +def sleep_in(weekday, vacation): + return (not weekday) or vacation diff --git a/students/MikeSchincariol/session5/file_copy.py b/students/MikeSchincariol/session5/file_copy.py new file mode 100644 index 0000000..9cc5a18 --- /dev/null +++ b/students/MikeSchincariol/session5/file_copy.py @@ -0,0 +1,27 @@ +import os.path + +def file_copy(src, dst): + + CHUNK_SIZE = 128 + + # Open the files for reading and writing. Don't try + # and catch any errors as we want the caller to get the exception + # and deal with it. + num_bytes_copied = 0 + with open(src, "rb") as src_fd: + with open(dst, "wb") as dst_fd: + while True: + # Read in at most CHUNK_SIZE bytes and then write them + # to the output stream. Keep track of how many byes + # have been transferred. + buf = src_fd.read(CHUNK_SIZE) + if len(buf) == 0: + break + else: + num_bytes_copied += len(buf) + dst_fd.write(buf) + print("{0} bytes copied".format(num_bytes_copied)) + + +if __name__ == "__main__": + file_copy("students.txt", "students_copy.txt") \ No newline at end of file diff --git a/students/MikeSchincariol/session5/file_path_printer b/students/MikeSchincariol/session5/file_path_printer new file mode 100644 index 0000000..45f47eb --- /dev/null +++ b/students/MikeSchincariol/session5/file_path_printer @@ -0,0 +1,8 @@ +import os +import os.path + +print("FD") +for item in os.listdir(os.curdir): + print("{0}{1}: {2}".format("*" if os.path.isdir(item) else " ", + "*" if not(os.path.isdir(item)) else " ", + item)) \ No newline at end of file diff --git a/students/MikeSchincariol/session5/parse_students.py b/students/MikeSchincariol/session5/parse_students.py new file mode 100644 index 0000000..2b8d584 --- /dev/null +++ b/students/MikeSchincariol/session5/parse_students.py @@ -0,0 +1,36 @@ +#!/usr/bin/python3 + + +#Open the students file +language_dict = {} + +with open("students.txt", "r") as f: + for line in f: + + # Split on full name (given by ':') + name = line.split(":")[0] + languages = line.split(":")[1] + + # Convert the languages into a list + languages = languages.split(",") + + # Clean up white space from around language string items post strip + for idx, lang_line in enumerate(languages[:]): + languages[idx] = lang_line.strip() + + # Filter for empty language lists + if len(languages[0]) == 0: + continue + + # Loop over the languages specified and if they are not present + # then add them to the dict with a count of 1. If they are present, + # increment the count + for language in languages: + if language not in language_dict: + language_dict[language] = 0 + language_dict[language] = language_dict[language] + 1 + + +# Print the list of languages and how many times it was seen +for k, v in language_dict.items(): + print ("{0:>12}:{1:>5}".format(k, v)) \ No newline at end of file diff --git a/students/MikeSchincariol/session5/students.txt b/students/MikeSchincariol/session5/students.txt new file mode 100644 index 0000000..fe6b413 --- /dev/null +++ b/students/MikeSchincariol/session5/students.txt @@ -0,0 +1,24 @@ +Bindhu, Krishna: +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: \ No newline at end of file diff --git a/students/MikeSchincariol/session5/test_codingbat_sleep_in.py b/students/MikeSchincariol/session5/test_codingbat_sleep_in.py new file mode 100644 index 0000000..01e6e28 --- /dev/null +++ b/students/MikeSchincariol/session5/test_codingbat_sleep_in.py @@ -0,0 +1,14 @@ +from codingbat_sleep_in import sleep_in + + +def test_sleep_in_1(): + assert sleep_in(False, False) == True + +def test_sleep_in_2(): + assert sleep_in(False, True) == True + +def test_sleep_in_3(): + assert sleep_in(True, False) == False + +def test_sleep_in_4(): + assert sleep_in(True, True) == True diff --git a/students/MikeSchincariol/session6/.keep b/students/MikeSchincariol/session6/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session6/cigar_party.py b/students/MikeSchincariol/session6/cigar_party.py new file mode 100644 index 0000000..269f25d --- /dev/null +++ b/students/MikeSchincariol/session6/cigar_party.py @@ -0,0 +1,13 @@ +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +def cigar_party(num_cigars, weekend): + return (weekend and num_cigars >= 40) or (num_cigars >= 40 and num_cigars <= 60) \ No newline at end of file diff --git a/students/MikeSchincariol/session6/mailroom.py b/students/MikeSchincariol/session6/mailroom.py new file mode 100755 index 0000000..b897150 --- /dev/null +++ b/students/MikeSchincariol/session6/mailroom.py @@ -0,0 +1,197 @@ +#!/usr/bin/python3 +from safe_input import safe_input + +def show_main_menu(): + ''' Present the menu to find out what the user wants to do. ''' + ''' Returns an int giving the menu item selected. ''' + while True: + print("") + print("MAIN MENU") + print("(1) Send a Thank You") + print("(2) Print Report") + print("(3) Exit") + choice = safe_input("Choice --> ") + try: + choice = int(choice) + if choice not in [1, 2, 3]: + print("Invalid selection. Please try again.") + else: + break + except: + print("Invalid selection. Please try again.") + finally: + pass + return choice + + +def print_donors(donor_list): + ''' Prints a list of the donors to the screen + :param donor_list: List object containing donor first name, last name, and list of donation amounts + :return: Nothing + ''' + print("") + for idx, donor in enumerate(donor_list): + print("DONOR: {0:3} NAME: {1:20} AMOUNTS: {2}". format(idx, donor[0], str(donor[1]))) + + +def is_donor_in_list(donor_list, full_name): + ''' Checks if the donor, given by the string full_name, is in the donor_list. + :param donor_list: List object containing donors full name and list of donation amounts + :return: True if donor in list, otherwise, false. + ''' + found = False + for donor in donor_list: + if full_name == donor[0]: + found = True + break + return found + + +def find_donor_idx(donor_list, full_name): + ''' CHecks if the donor, given by the string full_name, is in the donor_list and returns its index if it is. + :param donor_list: List object containing donors full name and list of donatino amounts + :param full_name: Donors full name as a string. + :return: Integer index giving the location of the donor in donor_list + ''' + found_at_idx = None + for idx, donor in enumerate(donor_list): + if donor[0] == full_name: + found_at_idx = idx + break + return found_at_idx + + +def thank(donor_list): + ''' Carries out the tasks necessary to enter, possibly create a new donor, + add a donation amount to the donor, and create a thank-you letter. + :param donor_list: List object containing donor first name, last name, and list of donation amounts + :return: Nothing + ''' + while True: + print("") + cmd = input("[Full Name|'list'|'thank_all'|'back'] --> ").lower() + if cmd == "list": + print_donors(donors) + continue + elif cmd == "back": + break + elif cmd == "thank_all": + # The user wants to print thank-you's to all donors + # Loop over all the donors, find the total sum donated. Then craft + # a thank-you message and write it to both the terminal and to disk. + for donor in donor_list: + donor_name = donor[0] + donation_sum = sum(donor[1]) + + msg = ("\n" + "Dear {0}, \n" + "\n" + "Thank you for your generous donations totalling ${1}.\n" + "Trundle and Biffs all over the world will benefit from your kindness!\n" + "\n" + "Yours Truely,\n" + " Bing Flaherty").format(donor_name, donation_sum) + print(msg) + with open("{0}_thank_you.txt".format(donor_name), "w") as fd: + fd.writelines(msg) + + else: + # The user provided a name to add to the list. + # Adding a donation and printing a thank-you. + # First check if the donor is in the list already, if not add them. + full_name = cmd.title() + if not(is_donor_in_list(donors, full_name)): + donor_list.append([full_name, []]) + + # Get the donation amount... + while True: + amnt = safe_input("Donation amount --> ") + try: + amnt = int(amnt) + break + except: + print("Invalid donation amount. Please try again. Input only numbers") + finally: + pass + # Find the donor entry in the donor list and append the donation amount + donor_entry_idx = find_donor_idx(donor_list, full_name) + donor_entry = donor_list[donor_entry_idx] + donor_entry[1].append(amnt) + + # Compose thank-you message and print to the terminal and a file + msg = ("\n" + "Dear {0}, \n" + "\n" + "Thank you for your generous donation of ${1}.\n" + "Trundle and Biffs all over the world will benefit from your kindness!\n" + "\n" + "Yours Truely,\n" + " Bing Flaherty").format(full_name, amnt) + print(msg) + with open("{0}_thank_you.txt".format(full_name), "w") as fd: + fd.writelines(msg) + + + + + + +def report(donor_list): + '''Compute number of donations, total donation amount and average donation amount for each user. + and print results in tabular format to the screen. + ''' + report_table = [] + for donor in donor_list: + total_donations = sum(donor[1]) + avg_donations = round(total_donations / len(donor[1]), 2) + report_table.append([donor[0], total_donations, avg_donations]) + + # Sort the list by total donation amount + report_table.sort(key=report_table_sort_by_total_donation_amount_fn, reverse=True) + + # Print sorted donor list to screen + print("") + print("-"*80) + print("{0:20} | {1:>20} | {2:>20}".format("NAME", "TOTAL DONATIONS", "AVG DONATION")) + print("-"*80) + for donor in report_table: + print("{0:20} | ${1:>20,.2f} | ${2:>20,.2f}". format(donor[0], + donor[1], + donor[2])) + print("-"*80) + + +def report_table_sort_by_total_donation_amount_fn(item): + ''' Returns the second item from the list item given to it + :param item: A list item + :return: The second item from the list item + ''' + return item[1] + + + + +if __name__ == "__main__": + + # Print program banner + print("----------------") + print("--- Mailroom ---") + print("----------------") + + # Populate the starting donors database + donors = list() + donors.append(["Steve Robertson", [100, 50]]) + donors.append(["Jane Iverson", [10]]) + donors.append(["Pac Liquor", [1000, 5000]]) + donors.append(["Anita Henchman", [10, 25, 75]]) + donors.append(["Zack Wing", [25, 100, 250]]) + + # Main kernel of program + while True: + choice = show_main_menu() + if choice in [1]: + thank(donors) + elif choice in [2]: + report(donors) + else: + exit() diff --git a/students/MikeSchincariol/session6/safe_input.py b/students/MikeSchincariol/session6/safe_input.py new file mode 100644 index 0000000..7febdc0 --- /dev/null +++ b/students/MikeSchincariol/session6/safe_input.py @@ -0,0 +1,8 @@ +def safe_input(prompt): + try: + res = input(prompt) + except EOFError or KeyboardInterrupt as ex: + res = None + finally: + return res + diff --git a/students/MikeSchincariol/session6/scoring.py b/students/MikeSchincariol/session6/scoring.py new file mode 100644 index 0000000..c3613a7 --- /dev/null +++ b/students/MikeSchincariol/session6/scoring.py @@ -0,0 +1,17 @@ +def hand_weapon(): + return {'small': 1, + 'medium': 2, + 'large': 3} + +def gun(): + return {'small': 5, + 'medium': 8, + 'large': 13} + +def flower_power(): + return {'small': 21, + 'medium': 34, + 'large': 55} + +def score(weapon_type, weapon_size): + return weapon_type()[weapon_size] \ No newline at end of file diff --git a/students/MikeSchincariol/session6/test_cigar_party.py b/students/MikeSchincariol/session6/test_cigar_party.py new file mode 100644 index 0000000..260d5f4 --- /dev/null +++ b/students/MikeSchincariol/session6/test_cigar_party.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +# you can change this import to test different versions +from cigar_party import cigar_party +# from cigar_party import cigar_party2 as cigar_party +# from cigar_party import cigar_party3 as cigar_party + + +def test_1(): + assert cigar_party(30, False) is False + + +def test_2(): + assert cigar_party(50, False) is True + + +def test_3(): + assert cigar_party(70, True) is True + + +def test_4(): + assert cigar_party(30, True) is False + + +def test_5(): + assert cigar_party(50, True) is True + + +def test_6(): + assert cigar_party(60, False) is True + + +def test_7(): + assert cigar_party(61, False) is False + + +def test_8(): + assert cigar_party(40, False) is True + + +def test_9(): + assert cigar_party(39, False) is False + + +def test_10(): + assert cigar_party(40, True) is True + + +def test_11(): + assert cigar_party(39, True) is False diff --git a/students/MikeSchincariol/session6/test_safe_input.py b/students/MikeSchincariol/session6/test_safe_input.py new file mode 100644 index 0000000..f138c7d --- /dev/null +++ b/students/MikeSchincariol/session6/test_safe_input.py @@ -0,0 +1,4 @@ +import safe_input + +def test_valid_val0(): + assert safe_input diff --git a/students/MikeSchincariol/session6/test_scoring.py b/students/MikeSchincariol/session6/test_scoring.py new file mode 100644 index 0000000..312f78f --- /dev/null +++ b/students/MikeSchincariol/session6/test_scoring.py @@ -0,0 +1,12 @@ +from scoring import * + +def test_scoring(): + assert score(hand_weapon, 'small') == 1 + assert score(hand_weapon, 'medium') == 2 + assert score(hand_weapon, 'large') == 3 + assert score(gun, 'small') == 5 + assert score(gun, 'medium') == 8 + assert score(gun, 'large') == 13 + assert score(flower_power, 'small') == 21 + assert score(flower_power, 'medium') == 34 + assert score(flower_power, 'large') == 55 \ No newline at end of file diff --git a/students/MikeSchincariol/session6/test_trapz.py b/students/MikeSchincariol/session6/test_trapz.py new file mode 100644 index 0000000..9bddc75 --- /dev/null +++ b/students/MikeSchincariol/session6/test_trapz.py @@ -0,0 +1,41 @@ +from trapz import trapz + +# Curves to use during testing +def line(x): + return 5 + +def sloped_line(x, M, B): + return M*x+B + +def quadratic(x, A, B, C): + return A*x**2 + B * x + C + + +# Function for testing if 2 values are "close enough" to be considered +# the same +def isclose(a, b, tol=1e-9): + if (a-b) < tol: + return True + else: + return False + +# Tests that exercise the trapz() method with various curves +def test_trapz_line(): + assert trapz(line, 0, 10, 100) == 50 + +def test_Sloped_line(): + a = 0 + b = 10 + slope = 5 + offset = 10 + ans = slope*(b**2 - a**2)/2 + offset*(b - a) + assert isclose(trapz(sloped_line, a, b, 100, M=slope, B=offset), ans) + +def test_trapz_quadratic(**kwargs): + a = 0 + b = 10 + A = 1 + B = 2 + C = 3 + ans = A/3*(b**3 - a**3) + B/2*(b**2 - a**2) + C*(b - a) + assert isclose(trapz(quadratic, a, b, 1000, A=A, B=B, C=C), ans, 0.001) diff --git a/students/MikeSchincariol/session6/trapz.py b/students/MikeSchincariol/session6/trapz.py new file mode 100644 index 0000000..f76e585 --- /dev/null +++ b/students/MikeSchincariol/session6/trapz.py @@ -0,0 +1,32 @@ +def trapz(fun, a, b, num_steps, **kwargs): + """ + Compute the area under the curve defined by + y = fun(x), for x between a and b + + :param fun: the function to evaluate + :type fun: a function that takes a single parameter + + :param a: the start point for the integration + :type a: a numeric value + + :param b: the end point for the integration + :type b: a numeric value + + :param num_steps: The number of integratiion steps to undertake. + :type num_steps: a numeric integer value + + :param kwargs: Arguments passed to 'fun' when calling 'fun' + :type kwargs: Keyword arguments + """ + STEP_SIZE = (b-a)/num_steps + + sum = 0 + for i in range(0, num_steps): + left = a + (i * STEP_SIZE) + right = a + ((i+1) * STEP_SIZE) + sum += fun(left, **kwargs) + fun(right, **kwargs) + + sum = sum * STEP_SIZE / 2 + return sum + + diff --git a/students/MikeSchincariol/session7/.keep b/students/MikeSchincariol/session7/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session7/html_render.py b/students/MikeSchincariol/session7/html_render.py new file mode 100644 index 0000000..1d3415b --- /dev/null +++ b/students/MikeSchincariol/session7/html_render.py @@ -0,0 +1,200 @@ +import io + +class Element(object): + + @classmethod + def check_content_is_compat(cls, content): + if isinstance(content, str) or isinstance(content, Element): + return True + else: + return False + + + def __init__(self, content=None, **kwargs): + ''' + :param content: The string or element instance to initialize the element with. + :param kwargs: Attributes that are associated with the content + :return: Nothing + ''' + self.tag = 'tag' + self.data = [] + self.attr = kwargs + + if content is not None: + if Element.check_content_is_compat(content): + self.data.append(content) + else: + raise ValueError("The 'content' argument must be a string or another Element") + + + def append(self, content, **kwargs): + ''' + :param content: The string or element instance to add to the items already in the element + :param kwargs: Attributes that are associated with the content + :return: Nothing + ''' + + self.attr.update(kwargs) + if content is not None: + if Element.check_content_is_compat(content): + self.data.append(content) + else: + raise ValueError("The 'content' argument must be a string or another Element") + + + def _render_start_tag(self, file_out, ind, inline=True, self_closing=False): + try: + if not inline: + file_out.write("\n{0}".format(ind)) + file_out.write("<{0}".format(self.tag)) + for k,v in self.attr.items(): + file_out.write(' {0}="{1}"'.format(k, v)) + if self_closing: + file_out.write("/>") + else: + file_out.write(">") + except AttributeError: + raise ValueError("The 'file_out' argument must be a class or subclass of io.TextIOBase") + + + def _render_data(self, file_out, ind, inline=True): + sub_ind = " " * (len(ind) + 3) + + for idx, item in enumerate(self.data): + try: + # Assume it is an Element + item.render(file_out, sub_ind) + except AttributeError: + # Guess not...assume it is a string :) + try: + if not inline: + file_out.write("\n{0}".format(sub_ind)) + file_out.write("{0}".format(item)) + except AttributeError: + raise ValueError("The 'file_out' argument must be a class or subclass of io.TextIOBase") + + + def _render_end_tag(self, file_out, ind, inline=True): + try: + if not inline: + file_out.write("\n{0}".format(ind)) + file_out.write("".format(self.tag)) + except AttributeError: + raise ValueError("The 'file_out' argument must be a class or subclass of io.TextIOBase") + + + def render(self, file_out, ind = ""): + ''' + + :param file_out: A io.TextIOBase file object + :param ind: A string, which supplies the amount of indentation whitespace to use + :return: Nothing + ''' + self._render_start_tag(file_out, ind, False, False) + self._render_data(file_out, ind, False) + self._render_end_tag(file_out, ind, False) + + + +class Html(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "html" + self.data.append("") + + +class Body(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "body" + + +class P(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "p" + + +class Head(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "head" + +class Ul(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "ul" + +class Li(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "li" + + +class OneLineTag(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "head" + + def render(self, file_out, ind=""): + ''' + + :param file_out: A io.TextIOBase file object + :param ind: A string, which supplies the amount of indentation whitespace to use + :return: Nothing + ''' + self._render_start_tag(file_out, ind, False, False) + self._render_data(file_out, ind, True) + self._render_end_tag(file_out, ind, True) + + + +class Title(OneLineTag): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "title" + +class H(OneLineTag): + def __init__(self, hdr_lvl, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "h{0}".format(hdr_lvl) + + +class SelfClosingTag(Element): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "selfclosing" + + def render(self, file_out, ind = ""): + ''' + + :param file_out: A io.TextIOBase file object + :param ind: A string, which supplies the amount of indentation whitespace to use + :return: Nothing + ''' + self._render_start_tag(file_out, ind, True, True) + self._render_data(file_out, ind, True) + + + +class Hr(SelfClosingTag): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "hr" + +class Br(SelfClosingTag): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "br" + +class Meta(SelfClosingTag): + def __init__(self, content=None, **kwargs): + super().__init__(content, **kwargs) + self.tag = "meta" + self.attr['charset']="UTF-8" + + +class A(Element): + def __init__(self, link, content): + super().__init__(content, href=link) + self.tag = "a" \ No newline at end of file diff --git a/students/MikeSchincariol/session7/run_html_render.py b/students/MikeSchincariol/session7/run_html_render.py new file mode 100644 index 0000000..3bac11d --- /dev/null +++ b/students/MikeSchincariol/session7/run_html_render.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python + +""" +a simple script can run and test your html rendering classes. + +Uncomment the steps as you add to your rendering. + +""" + +from io import StringIO + +# importing the html_rendering code with a short name for easy typing. +import html_render as hr +# reloading in case you are running this in iPython +# -- we want to make sure the latest version is used +import importlib +importlib.reload(hr) + + +# writing the file out: +def render_page(page, filename): + """ + render the tree of elements + + This uses StringIO to render to memory, then dump to console and + write to file -- very handy! + """ + + f = StringIO() + page.render(f, " ") + + f.seek(0) + + print(f.read()) + + f.seek(0) + open(filename, 'w').write(f.read()) + + +# Step 1 +######### + +#page = hr.Element() +# +#page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text") +# +#page.append("And here is another piece of text -- you should be able to add any number") +# +#render_page(page, "test_html_output1.html") + +# ## Step 2 +# ########## +#page = hr.Html() +# +#body = hr.Body() +# +#body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +# +#body.append(hr.P("And here is another piece of text -- you should be able to add any number")) +# +#page.append(body) +# +#render_page(page, "test_html_output2.html") + +# # Step 3 +# ########## + +#page = hr.Html() +# +#head = hr.Head() +#head.append(hr.Title("PythonClass = Revision 1087:")) +# +#page.append(head) +# +#body = hr.Body() +# +#body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +#body.append(hr.P("And here is another piece of text -- you should be able to add any number")) +# +#page.append(body) +# +#render_page(page, "test_html_output3.html") + +# # Step 4 +# ########## + +#page = hr.Html() +# +#head = hr.Head() +#head.append(hr.Title("PythonClass = Revision 1087:")) +# +#page.append(head) +# +#body = hr.Body() +# +#body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) +# +#page.append(body) +# +#render_page(page, "test_html_output4.html") + +# # Step 5 +# ######### + +#page = hr.Html() +# +#head = hr.Head() +#head.append(hr.Title("PythonClass = Revision 1087:")) +# +#page.append(head) +# +#body = hr.Body() +# +#body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) +# +#body.append(hr.Hr()) +# +#page.append(body) +# +#render_page(page, "test_html_output5.html") + +# # Step 6 +# ######### + +#page = hr.Html() +# +#head = hr.Head() +#head.append(hr.Title("PythonClass = Revision 1087:")) +# +#page.append(head) +# +#body = hr.Body() +# +#body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) +# +#body.append(hr.Hr()) +# +#body.append("And this is a ") +#body.append( hr.A("http://google.com/", "link") ) +#body.append("to google") +# +#page.append(body) +# +#render_page(page, "test_html_output6.html") + +# # Step 7 +# ######### + +# page = hr.Html() + +# head = hr.Head() +# head.append(hr.Title("PythonClass = Revision 1087:")) + +# page.append(head) + +# body = hr.Body() + +# body.append( hr.H(2, "PythonClass - Class 6 example") ) + +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# style="text-align: center; font-style: oblique;")) + +# body.append(hr.Hr()) + +# list = hr.Ul(id="TheList", style="line-height:200%") + +# list.append( hr.Li("The first item in a list") ) +# list.append( hr.Li("This is the second item", style="color: red") ) + +# item = hr.Li() +# item.append("And this is a ") +# item.append( hr.A("http://google.com/", "link") ) +# item.append("to google") + +# list.append(item) + +# body.append(list) + +# page.append(body) + +# render_page(page, "test_html_output7.html") + +# # Step 8 +# ######## +page = hr.Html() + + +head = hr.Head() +head.append(hr.Meta(charset="UTF-8") ) +head.append(hr.Title("PythonClass = Revision 1087:")) + +page.append(head) + +body = hr.Body() + +body.append( hr.H(2, "PythonClass - Class 6 example") ) + +body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", + style="text-align: center; font-style: oblique;")) + +body.append(hr.Hr()) + +list = hr.Ul(id="TheList", style="line-height:200%") + +list.append( hr.Li("The first item in a list") ) +list.append( hr.Li("This is the second item", style="color: red") ) + +item = hr.Li() +item.append("And this is a ") +item.append( hr.A("http://google.com/", "link") ) +item.append("to google") + +list.append(item) + +body.append(list) + +page.append(body) + +render_page(page, "test_html_output8.html") diff --git a/students/MikeSchincariol/session7/test_html_render.py b/students/MikeSchincariol/session7/test_html_render.py new file mode 100644 index 0000000..b6d7baf --- /dev/null +++ b/students/MikeSchincariol/session7/test_html_render.py @@ -0,0 +1,27 @@ +import html_render as hr +import pytest + + + +def test_init_without_content(): + inst = hr.Element() + assert (len(inst.data) == 0) + + +def test_init_with_string_content(): + inst = hr.Element('abcd') + assert (inst.data[0] == 'abcd') + + +def test_append_string(): + inst = hr.Element('abcd') + inst.append('efgh') + assert (inst.data[0] == 'abcd' and + inst.data[1] == 'efgh') + + +def test_append_incompatible_data(): + inst = hr.Element('abcd') + with pytest.raises(ValueError): + inst.append(1) + diff --git a/students/MikeSchincariol/session8/.keep b/students/MikeSchincariol/session8/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/MikeSchincariol/session8/circle.py b/students/MikeSchincariol/session8/circle.py new file mode 100644 index 0000000..bcfd7ad --- /dev/null +++ b/students/MikeSchincariol/session8/circle.py @@ -0,0 +1,88 @@ +import math + +class Circle(object): + + @classmethod + def from_diameter(cls, diameter): + return cls(diameter/2) + + + def __init__(self, radius): + self.r = radius + + + @property + def radius(self): + return self.r + + @radius.setter + def radius(self, val): + self.r = val + + + @property + def diameter(self): + return 2 * self.r + + + @diameter.setter + def diameter(self, val): + self.r = val / 2 + + + @property + def area(self): + return 2 * math.pi * self.r + + def __repr__(self): + return 'Circle({})'.format(self.r) + + def __str__(self): + return 'Circle with radius: {:6f}'.format(self.r) + + def __add__(self, other): + if isinstance(other, Circle): + return Circle(self.r + other.r) + else: + raise ValueError("The other parameter must be a circle type") + + def __iadd__(self, other): + if isinstance(other, Circle): + self.r += other.r + return self + else: + raise ValueError("The other parameter must be a circle type") + + def __radd__(self, other): + return self.__add__(other) + + + def __mul__(self, other): + if isinstance(other, int): + return Circle(self.r * other) + else: + raise ValueError("The other parameter must be an int") + + def __imul__(self, other): + if isinstance(other, int): + self.r *= other + return self + else: + raise ValueError("The other parameter must be an int") + + + def __rmul__(self, other): + return self.__mul__(other) + + + def __gt__(self, other): + if isinstance(other, Circle): + return self.r > other.r + else: + raise ValueError("The other parameter must be a circle type") + + def __eq__(self, other): + if isinstance(other, Circle): + return self.r == other.r + else: + raise ValueError("The other parameter must be a circle type") diff --git a/students/MikeSchincariol/session8/quadratic.py b/students/MikeSchincariol/session8/quadratic.py new file mode 100644 index 0000000..8b3aacc --- /dev/null +++ b/students/MikeSchincariol/session8/quadratic.py @@ -0,0 +1,9 @@ +class Quadratic(object): + + def __init__(self, a, b, c): + self.a = a + self.b = b + self.c = c + + def __call__(self, x): + return self.a*x**2 + self.b*x + self.c diff --git a/students/MikeSchincariol/session8/sparsearray.py b/students/MikeSchincariol/session8/sparsearray.py new file mode 100644 index 0000000..d0e437a --- /dev/null +++ b/students/MikeSchincariol/session8/sparsearray.py @@ -0,0 +1,102 @@ + + +class Sparsearray(object): + + + def __init__(self, iterable): + self.max_idx = None # None means the array is empty + self.array = {} # The dict that holds the array data + + # Iterate over the supplied list of values and put the non-zero + # items in the dict + for idx,val in enumerate(iterable): + if val > 0: + self.array[idx] = val + + # Adjust the max index that the array knows about + # to account for the initial values + self.max_idx = len(iterable)-1 + + + def __len__(self): + """ Returns the length of the sparse array + """ + return self.max_idx+1 + + + def __contains__(self, x): + """ Returns True if the value 'x' is in the sparse array + """ + if self.max_idx is None: + return False + elif x == 0 and len(self) != len(self.array): + # Looking for a 0. Since this is a sparse array, we + # can't look in the array itself to see if the value '0' + # is present because it is not stored. The only way we + # can detect that a '0' is in the array is by a mismatch + # on the length of the array versus the last index of + # the array. + return True + else: + return x in self.array + + + def __setitem__(self, k, v): + """ Sets item 'k' equal to value 'v' + """ + # If the value is 0, we never store it and if item 'k' already + # existed as a non-zero value, we have to remove it. Finally, + # if the value is non-zero, store it in the array. + if v == 0 and k in self.array: + del self.array[k] + elif v > 0: + self.array[k] = v + + # Update the last index of the array + if k > self.max_idx: + self.max_idx = k + + + def __getitem__(self, k): + """ Returns the value of item 'k', if 'k' is in the array + """ + # If the item 'k' is outside the bounds of the array, then + # it was never added to the array. If 'k' is inside the + # bounds of the array, the array will have it if the value + # associated with the item 'k' is non-zero. + if k > self.max_idx: + return None + elif k in self.array: + return self.array[k] + else: + return 0 + + def __delitem__(self, k): + """ Removes item 'k' from the array + """ + if k in self.array: + del self.array[k] + + + + def __iter__(self): + """ Iterates over the list of items returning one at a time. + """ + for idx in range(len(self)): + if idx in self.array: + yield self.array[idx] + else: + yield 0 + + def __str__(self): + # Used the same string as returned by __repr__ + self.__repr__(self) + + def __repr__(self): + l = [x for x in self] + return "Sparsearray({})".format(l) + + + + + diff --git a/students/MikeSchincariol/session8/test_circle.py b/students/MikeSchincariol/session8/test_circle.py new file mode 100644 index 0000000..5c9a8aa --- /dev/null +++ b/students/MikeSchincariol/session8/test_circle.py @@ -0,0 +1,97 @@ +from circle import Circle +import math +import pytest + +def test_get_radius(): + c = Circle(5) + assert c.radius == 5 + +def test_get_diameter(): + c = Circle(4) + assert c.diameter == 2*4 + +def test_set_diameter(): + c = Circle(4) + c.diameter = 2 + assert c.diameter == 2 + assert c.radius == 1 + +def test_get_area(): + c = Circle(2) + assert c.area == 2 * math.pi * 2 + +def test_set_area(): + c = Circle(2) + with pytest.raises(AttributeError): + c.area = 42 + +def test_create_with_diameter(): + c = Circle.from_diameter(8) + assert c.diameter == 8 + assert c.radius == 4 + +def test_repr(): + c = Circle(4) + assert c.__repr__() == 'Circle(4)' + +def test_str(): + c = Circle(4) + assert c.__str__() == "Circle with radius: 4.000000" + +def test_add_circles(): + c1 = Circle(2) + c2 = Circle(4) + c = c1 + c2 + return c.radius == 4 + +def test_mult_circles0(): + c = Circle(2) + c *= 3 + return c.radius == Circle(12).radius + +def test_mult_circles1(): + c = Circle(2) + return (3 * c) == Circle(12) + +def test_gt(): + c1 = Circle(2) + c2 = Circle(4) + assert not (c1 > c2) + +def test_lt(): + c1 = Circle(2) + c2 = Circle(4) + assert (c1 < c2) + +def test_eq0(): + c1 = Circle(2) + c2 = Circle(4) + assert (c1 != c2) + +def test_eq0(): + c1 = Circle(2) + c2 = Circle(4) + c3 = Circle(4) + assert (c2 == c3) + +def test_sort_circles(): + circles = [Circle(6), Circle(7), Circle(8), Circle(4), Circle(0), Circle(2), Circle(3), Circle(5), Circle(9), Circle(1)] + circles.sort() + assert circles.__repr__() == "[Circle(0), Circle(1), Circle(2), Circle(3), Circle(4), Circle(5), Circle(6), Circle(7), Circle(8), Circle(9)]" + +def test_reflected_numerics(): + a_circle = Circle(2) + assert (a_circle * 3) == (3 * a_circle) + +def test_augmented_add(): + a_circle = Circle(2) + another_circle = Circle(4) + a_circle += another_circle + assert a_circle.r == 6 + +def test_augmented_mult(): + a_circle = Circle(4) + a_circle *= 2 + assert a_circle.r == 8 + + diff --git a/students/MikeSchincariol/session8/test_quadratic.py b/students/MikeSchincariol/session8/test_quadratic.py new file mode 100644 index 0000000..3502f27 --- /dev/null +++ b/students/MikeSchincariol/session8/test_quadratic.py @@ -0,0 +1,20 @@ +from quadratic import Quadratic as quad + + +def test_quad0(): + my_quad = quad(a=2, b=3, c=1) + assert my_quad(0) == 1 + +def test_quad1(): + my_quad = quad(a=2, b=3, c=1) + assert my_quad(1) == 6 + +def test_quad2(): + my_quad = quad(a=2, b=3, c=1) + assert my_quad(2) == 15 + +def test_quad3(): + my_quad = quad(a=2, b=3, c=1) + assert my_quad(3) == 28 + + diff --git a/students/MikeSchincariol/session8/test_sparsearray.py b/students/MikeSchincariol/session8/test_sparsearray.py new file mode 100644 index 0000000..456cb1d --- /dev/null +++ b/students/MikeSchincariol/session8/test_sparsearray.py @@ -0,0 +1,50 @@ +from sparsearray import Sparsearray + + +def test_sa_creation(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert sa.__repr__() == "Sparsearray([1, 2, 0, 0, 0, 0, 3, 0, 0, 4])" + +def test_sa_len(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert len(sa) == 10 + +def test_sa_setitem0(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + sa[5] = 12 + assert sa.__repr__() == "Sparsearray([1, 2, 0, 0, 0, 12, 3, 0, 0, 4])" + +def test_sa_setitem1(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + sa[3] = 0 + assert sa.__repr__() == "Sparsearray([1, 2, 0, 0, 0, 0, 3, 0, 0, 4])" + +def test_sa_setitem2(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + sa[0] = 0 + assert sa.__repr__() == "Sparsearray([0, 2, 0, 0, 0, 0, 3, 0, 0, 4])" + +def test_sa_getitem0(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert sa[13] == None + +def test_sa_getitem0(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert sa[0] == 1 + +def test_sa_getitem1(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert sa[1] == 2 + +def test_sa_getitem2(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert sa[2] == 0 + +def test_sa_getitem3(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + assert sa[9] == 4 + +def test_sa_delitem0(): + sa = Sparsearray([1,2,0,0,0,0,3,0,0,4]) + del sa[1] + assert sa.__repr__() == "Sparsearray([1, 0, 0, 0, 0, 0, 3, 0, 0, 4])" diff --git a/students/MikeSchincariol/session9/.keep b/students/MikeSchincariol/session9/.keep new file mode 100644 index 0000000..e69de29 diff --git a/students/README.rst b/students/README.rst index 498bb2a..0f1e956 100644 --- a/students/README.rst +++ b/students/README.rst @@ -13,4 +13,9 @@ Within your personal directory we recommend a series of sub directorys which mir Keep each week's work in the corresonding directory. -Use git to share your work with the the instructors and the rest of the class. \ No newline at end of file +<<<<<<< HEAD +Use git to share your work with the the instructors and the rest of the class.#Python Code for UWPCE-PYTHON cert class +======= +Use git to share your work with the the instructors and the rest of the class. + +>>>>>>> 30714c435ef20f301b6a7ff886c4ef0ce61ed417 diff --git a/students/RickRiehle/README.rst b/students/RickRiehle/README.rst new file mode 100644 index 0000000..45d62f5 --- /dev/null +++ b/students/RickRiehle/README.rst @@ -0,0 +1,4 @@ +hi + + +# where's all your homework? :p diff --git a/students/Thomas_Gaffney/README TEST PULL.rst b/students/Thomas_Gaffney/README TEST PULL.rst new file mode 100644 index 0000000..44ea22b --- /dev/null +++ b/students/Thomas_Gaffney/README TEST PULL.rst @@ -0,0 +1,2 @@ +# Python code for UWPCE-PythonCert class +TEST PULL REQUEST \ No newline at end of file diff --git a/students/Thomas_Gaffney/README.rst b/students/Thomas_Gaffney/README.rst new file mode 100644 index 0000000..897bbba --- /dev/null +++ b/students/Thomas_Gaffney/README.rst @@ -0,0 +1,9 @@ +# Python code for UWPCE-PythonCert class + + +TESTSTEESTST# Python code for UWPCE-PythonCert class +\ + + +TETSTEESETSETSTESET# Python code for UWPCE-PythonCert class +# Python code for UWPCE-PythonCert class diff --git a/students/Thomas_Gaffney/READMETEST2.rst b/students/Thomas_Gaffney/READMETEST2.rst new file mode 100644 index 0000000..16e7412 --- /dev/null +++ b/students/Thomas_Gaffney/READMETEST2.rst @@ -0,0 +1,2 @@ +# Python code for UWPCE-PythonCert class +print("THIS IS A TEST") \ No newline at end of file diff --git a/students/Thomas_Gaffney/READMETESTPULL.rst b/students/Thomas_Gaffney/READMETESTPULL.rst new file mode 100644 index 0000000..44ea22b --- /dev/null +++ b/students/Thomas_Gaffney/READMETESTPULL.rst @@ -0,0 +1,2 @@ +# Python code for UWPCE-PythonCert class +TEST PULL REQUEST \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_02/EnterACoin.py b/students/Thomas_Gaffney/session_02/EnterACoin.py new file mode 100644 index 0000000..3728f4e --- /dev/null +++ b/students/Thomas_Gaffney/session_02/EnterACoin.py @@ -0,0 +1,28 @@ +def enterACoin (coinName): + numberOfCoins = input("Enter the number of "+coinName+":") + try: + int(numberOfCoins) + return int(numberOfCoins) + except: + print("Please enter an integer") + return enterACoin(coinName) + +def isADollar(pennies, nickels, dimes, quarters): + value = pennies*.01+nickels*.05+dimes*.1+quarters*.25 + return value + +input("Try to enter a combination of coins that equals exactly $1. Press Enter to continue:") + +pennies = enterACoin("Pennies") +nickels = enterACoin("Nickels") +dimes = enterACoin("Dimes") +quarters = enterACoin("Quarters") + +value = isADollar(pennies=pennies, nickels = nickels, dimes = dimes, quarters = quarters) + +if(value == 1.0): + print("Congratualations, you win!") +elif(value > 1.0): + print("That adds up to "+str(value)+" which is greater than a dollar. You lost!") +elif(value < 1.0): + print("That adds up to "+str(value)+" which is less than a dollar. You lost!") diff --git a/students/Thomas_Gaffney/session_02/FizzBuzz b/students/Thomas_Gaffney/session_02/FizzBuzz new file mode 100644 index 0000000..ab885b2 --- /dev/null +++ b/students/Thomas_Gaffney/session_02/FizzBuzz @@ -0,0 +1,5 @@ +def fizzBuzz(): + for i in range(1:100): + print(i) + +fizzBuzz() \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_02/FizzBuzz.py b/students/Thomas_Gaffney/session_02/FizzBuzz.py new file mode 100644 index 0000000..cfbcd43 --- /dev/null +++ b/students/Thomas_Gaffney/session_02/FizzBuzz.py @@ -0,0 +1,7 @@ +def fizzBuzz(): + for i in range(1,101): + if((i%3 == 0) and (i%5 ==0)): print("FizzBuzz") + elif(i%3 == 0): print("Fizz") + elif(i%5 == 0): print("Buzz") + else: print(i) +fizzBuzz() diff --git a/students/Thomas_Gaffney/session_02/MoneyCounting b/students/Thomas_Gaffney/session_02/MoneyCounting new file mode 100644 index 0000000..1d8767f --- /dev/null +++ b/students/Thomas_Gaffney/session_02/MoneyCounting @@ -0,0 +1,10 @@ +def enterACoin (coinName) + input("Enter the number of "+coinName+":") + try: + int(input) + return int(input) + except: + print("Please enter an integer") + enterACoin(coinName) + +enterACoin("Nickels") \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_02/MoneyCounting.py b/students/Thomas_Gaffney/session_02/MoneyCounting.py new file mode 100644 index 0000000..3728f4e --- /dev/null +++ b/students/Thomas_Gaffney/session_02/MoneyCounting.py @@ -0,0 +1,28 @@ +def enterACoin (coinName): + numberOfCoins = input("Enter the number of "+coinName+":") + try: + int(numberOfCoins) + return int(numberOfCoins) + except: + print("Please enter an integer") + return enterACoin(coinName) + +def isADollar(pennies, nickels, dimes, quarters): + value = pennies*.01+nickels*.05+dimes*.1+quarters*.25 + return value + +input("Try to enter a combination of coins that equals exactly $1. Press Enter to continue:") + +pennies = enterACoin("Pennies") +nickels = enterACoin("Nickels") +dimes = enterACoin("Dimes") +quarters = enterACoin("Quarters") + +value = isADollar(pennies=pennies, nickels = nickels, dimes = dimes, quarters = quarters) + +if(value == 1.0): + print("Congratualations, you win!") +elif(value > 1.0): + print("That adds up to "+str(value)+" which is greater than a dollar. You lost!") +elif(value < 1.0): + print("That adds up to "+str(value)+" which is less than a dollar. You lost!") diff --git a/students/Thomas_Gaffney/session_02/PrintingAGrid b/students/Thomas_Gaffney/session_02/PrintingAGrid new file mode 100644 index 0000000..3ab9e6b --- /dev/null +++ b/students/Thomas_Gaffney/session_02/PrintingAGrid @@ -0,0 +1,2 @@ +print("+ - - - - + - - - - +") +print("| | |") \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_02/PrintingAGrid.Py b/students/Thomas_Gaffney/session_02/PrintingAGrid.Py new file mode 100644 index 0000000..db86376 --- /dev/null +++ b/students/Thomas_Gaffney/session_02/PrintingAGrid.Py @@ -0,0 +1,11 @@ +print("+ - - - - + - - - - +") +print("| | |") +print("| | |") +print("| | |") +print("| | |") +print("+ - - - - + - - - - +") +print("| | |") +print("| | |") +print("| | |") +print("| | |") +print("+ - - - - + - - - - +") diff --git a/students/Thomas_Gaffney/session_02/README.rst b/students/Thomas_Gaffney/session_02/README.rst new file mode 100644 index 0000000..44ea22b --- /dev/null +++ b/students/Thomas_Gaffney/session_02/README.rst @@ -0,0 +1,2 @@ +# Python code for UWPCE-PythonCert class +TEST PULL REQUEST \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_02/grid_printer.py b/students/Thomas_Gaffney/session_02/grid_printer.py new file mode 100644 index 0000000..d3e46f2 --- /dev/null +++ b/students/Thomas_Gaffney/session_02/grid_printer.py @@ -0,0 +1 @@ +print('Hello World') \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_02/series.py b/students/Thomas_Gaffney/session_02/series.py new file mode 100644 index 0000000..f0bdea8 --- /dev/null +++ b/students/Thomas_Gaffney/session_02/series.py @@ -0,0 +1,52 @@ +def fibonacci (n): + '''Calculates the Fibanocci sequence given the length of the series, n + Parameters + ========== + n : Int + The length of the the sequence + + Results + ========= + returns nth value of the Fibonacci series''' + if(n == 0): return 0 + if(n == 1): return 1 + else: return (fibonacci(n-2) + fibonacci(n-1)) + + +def lucas (n): + '''Calculates the Lucas sequence given the length of the series, n + Parameters + ========== + n : Int + The length of the the sequence + + Results + ========= + returns the nth value of the Lucas series''' + if(n == 0): return 2 + if(n == 1): return 1 + else: return (lucas(n-2) + lucas(n-1)) + + +def sum_series (n, startval = 0, secondval=1): + '''Calculates the a series given the length of the series, n + Parameters + ========== + n : Int + The length of the the sequence + startval : Int + The first value in the sequence + secondval : Int + The second value in the sequence + + Results + ========= + returns the nth value of the series''' + if(n == 0): return startval + if(n == 1): return secondval + else: return (sum_series(n-2, startval = startval, secondval = secondval) + sum_series(n-1,startval = startval, secondval = secondval)) + +assert fibonacci(6) == 8 +assert lucas(6) == 18 +assert sum_series(6, startval=0, secondval=1) == 8 +assert sum_series(6, startval=2, secondval=1) == 18 diff --git a/students/Thomas_Gaffney/session_02/test_python2.py b/students/Thomas_Gaffney/session_02/test_python2.py new file mode 100644 index 0000000..1e1d08c --- /dev/null +++ b/students/Thomas_Gaffney/session_02/test_python2.py @@ -0,0 +1 @@ +print("This is a test file") \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_03/Mailroom.py b/students/Thomas_Gaffney/session_03/Mailroom.py new file mode 100644 index 0000000..8dfc853 --- /dev/null +++ b/students/Thomas_Gaffney/session_03/Mailroom.py @@ -0,0 +1,51 @@ +def sendathankyou(donorDict): + userselection = input('Please input the name of the donor, or list to display a list of current users:') + if(userselection == 'list'): + print(donorDict.keys()) + sendathankyou(donorDict) + elif(userselection in donorDict.keys()): + user = userselection + else: + user = userselection + donorDict[user] = [] + donationamount = input('Please enter the donation amount for the selected user:') + + #Test if a number was given. + while (True): + try: + float(donationamount) + break + except: + donationamount = input('That was not a number, please try again:') + + donorDict[user].append(float(donationamount)) + thankyou = 'Dear {user}: \n \nThank You For Your Generous Donation of {donationamount}. \n \nThe Charity \n'.format(user = user, donationamount = donationamount) + print(thankyou) + +def printareport(donorDict): + str = "" + for key in donorDict: + str += '|{donor} |{donated} |{donations} |{avgdonation}|\n'.format(donor = key, + donated = sum(donorDict[key]), + donations = len(donorDict[key]), + avgdonation = sum(donorDict[key])/len(donorDict[key])) + print(str) + + +if __name__ == '__main__' : + donorDict = {'Tom Jones' : [25, 10, 15], + 'Brad Hardy' : [5, 9], + 'Manuel Miller' : [4, 21], + 'Josh Benson' : [1], + 'Ashley Scanlon' : [4, 9, 50]} + + while(True): + userinput = input('Welcome to the mailroom! Would you like to :\n \1. Send a Thank you \n 2. Create a report \n 3. Quit \nChoice 1, 2 or 3?:') + if (userinput == str(1)): + donorDict = sendathankyou(donorDict) + if (userinput == str(2)): + printareport(donorDict) + if (userinput == str(3)): + break + + diff --git a/students/Thomas_Gaffney/session_03/MailroomDraft.py b/students/Thomas_Gaffney/session_03/MailroomDraft.py new file mode 100644 index 0000000..8dfc853 --- /dev/null +++ b/students/Thomas_Gaffney/session_03/MailroomDraft.py @@ -0,0 +1,51 @@ +def sendathankyou(donorDict): + userselection = input('Please input the name of the donor, or list to display a list of current users:') + if(userselection == 'list'): + print(donorDict.keys()) + sendathankyou(donorDict) + elif(userselection in donorDict.keys()): + user = userselection + else: + user = userselection + donorDict[user] = [] + donationamount = input('Please enter the donation amount for the selected user:') + + #Test if a number was given. + while (True): + try: + float(donationamount) + break + except: + donationamount = input('That was not a number, please try again:') + + donorDict[user].append(float(donationamount)) + thankyou = 'Dear {user}: \n \nThank You For Your Generous Donation of {donationamount}. \n \nThe Charity \n'.format(user = user, donationamount = donationamount) + print(thankyou) + +def printareport(donorDict): + str = "" + for key in donorDict: + str += '|{donor} |{donated} |{donations} |{avgdonation}|\n'.format(donor = key, + donated = sum(donorDict[key]), + donations = len(donorDict[key]), + avgdonation = sum(donorDict[key])/len(donorDict[key])) + print(str) + + +if __name__ == '__main__' : + donorDict = {'Tom Jones' : [25, 10, 15], + 'Brad Hardy' : [5, 9], + 'Manuel Miller' : [4, 21], + 'Josh Benson' : [1], + 'Ashley Scanlon' : [4, 9, 50]} + + while(True): + userinput = input('Welcome to the mailroom! Would you like to :\n \1. Send a Thank you \n 2. Create a report \n 3. Quit \nChoice 1, 2 or 3?:') + if (userinput == str(1)): + donorDict = sendathankyou(donorDict) + if (userinput == str(2)): + printareport(donorDict) + if (userinput == str(3)): + break + + diff --git a/students/Thomas_Gaffney/session_03/MailroomFinal.py b/students/Thomas_Gaffney/session_03/MailroomFinal.py new file mode 100755 index 0000000..34b74b0 --- /dev/null +++ b/students/Thomas_Gaffney/session_03/MailroomFinal.py @@ -0,0 +1,63 @@ +#! /Users/ThomasGaffney/anaconda/bin/python3.5 + +def sendathankyou(donorDict): + while(True): + userselection = input('Please input the name of the donor, list to display a list of current users, or main to return to the main program:') + if(userselection.lower() == 'main'): break + elif(userselection.lower() == 'list'): + for keys in donorDict.keys(): + print(keys) + else: + if(userselection in donorDict.keys()): + user = userselection + else: + user = userselection + donorDict[user] = [] + donationamount = input('Please enter the donation amount for the selected user:') + + #Test if a number was given. + while (True): + try: + float(donationamount) + break + except: + donationamount = input('That was not a number, please try again:') + + donorDict[user].append(float(donationamount)) + thankyou = 'Dear {user}: \n \nThank You For Your Generous Donation of {donationamount}. \n \nThe Charity \n'.format(user = user, donationamount = donationamount) + print(thankyou) + + return donorDict + +def printareport(donorDict): + report_list = [] + for key in donorDict.keys(): + report_list.append([sum(donorDict[key]), key, len(donorDict[key]), sum(donorDict[key])/len(donorDict[key])]) + report_list.sort() + str = "|donor\t\t |donated\t |donations\t |avgdonation\t|\n" + for item in report_list: + str += '|{donor}\t |{donated}\t\t |{donations}\t\t |{avgdonation}\t\t|\n'.format(donor = item[1], + donated = item[0], + donations = item[2], + avgdonation = round(item[3],1)).expandtabs(8) + str.format('center align') + print(str) + + +if __name__ == '__main__' : + donorDict = {'Tom Jones' : [25, 10, 15], + 'Brad Hardy' : [5, 9], + 'Manuel Miller' : [4, 21], + 'Josh Benson' : [1], + 'Ashley Scanlon' : [4, 9, 50]} + + while(True): + userinput = input('Welcome to the mailroom! Would you like to :\n 1. Send a Thank you \n 2. Create a report \n 3. Quit \nChoice 1, 2 or 3?:') + if (userinput == str(1)): + donorDict = sendathankyou(donorDict) + if (userinput == str(2)): + printareport(donorDict) + if (userinput == str(3)): + break + + diff --git a/students/Thomas_Gaffney/session_03/ROT13.py b/students/Thomas_Gaffney/session_03/ROT13.py new file mode 100644 index 0000000..e64a139 --- /dev/null +++ b/students/Thomas_Gaffney/session_03/ROT13.py @@ -0,0 +1,11 @@ +__author__ = 'ThomasGaffney' +if __name__ == "__main__": + + translator = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', + 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm') + + print(str.translate('Zntargvp sebz bhgfvqr arne pbeare', translator)) + + assert str.translate('Zntargvp sebz bhgfvqr arne pbeare', translator) = 'Magnetic from outside near corner' + +else: raise Exception("This file was not created to be imported") \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_03/Session_03 Slicing Lab.py b/students/Thomas_Gaffney/session_03/Session_03 Slicing Lab.py new file mode 100644 index 0000000..615ca19 --- /dev/null +++ b/students/Thomas_Gaffney/session_03/Session_03 Slicing Lab.py @@ -0,0 +1,17 @@ +__author__ = 'ThomasGaffney' +def switchfirstandlast(stringtouse): + first = stringtouse[0] + last = stringtouse [-1] + middle = stringtouse [1:(len(stringtouse)-1)] + return (last+middle+first) + + +test = switchfirstandlast('abcdefghijkl') +print(test) + +def reversesequence(stringtouse): + emptystring = "" + for i in range(len(stringtouse)): + emptystring = emptystring + stringtouse[-(len(stringtouse)-i-1)] + +print(reversesequence('abcdefghijklmnop')) diff --git a/students/Thomas_Gaffney/session_03/Slicing.py b/students/Thomas_Gaffney/session_03/Slicing.py new file mode 100644 index 0000000..d90880f --- /dev/null +++ b/students/Thomas_Gaffney/session_03/Slicing.py @@ -0,0 +1,37 @@ + + +def switchfirstandlast(stringtouse): + first = stringtouse[0] + last = stringtouse [-1] + middle = stringtouse [1:(len(stringtouse)-1)] + return (last+middle+first) + + +print(switchfirstandlast("abcdefghijkl")) + +def everyotheritem(stringtouse): + newstring="" + for i in range(len(stringtouse)): + i=i+1 + if (i%2 != 0): newstring = newstring+stringtouse[i-1] + return newstring + +print(everyotheritem("abcdefghijkl")) + +def removefirstandlastfour(stringtouse): + newstring=stringtouse[4:(len(stringtouse)-4)] + newstring = everyotheritem(newstring) + return newstring + +print(removefirstandlastfour("abcdefghijklmnop")) + +def reversesequence(stringtouse): + newstring = "" + for i in range(len(stringtouse)): + newstring = newstring + stringtouse[-(len(stringtouse)-i-1)] + return newstring + +print(reversesequence('abcdefghijklmnop')) + + +#testing if will add. \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_03/slicingtwo.py b/students/Thomas_Gaffney/session_03/slicingtwo.py new file mode 100644 index 0000000..d90880f --- /dev/null +++ b/students/Thomas_Gaffney/session_03/slicingtwo.py @@ -0,0 +1,37 @@ + + +def switchfirstandlast(stringtouse): + first = stringtouse[0] + last = stringtouse [-1] + middle = stringtouse [1:(len(stringtouse)-1)] + return (last+middle+first) + + +print(switchfirstandlast("abcdefghijkl")) + +def everyotheritem(stringtouse): + newstring="" + for i in range(len(stringtouse)): + i=i+1 + if (i%2 != 0): newstring = newstring+stringtouse[i-1] + return newstring + +print(everyotheritem("abcdefghijkl")) + +def removefirstandlastfour(stringtouse): + newstring=stringtouse[4:(len(stringtouse)-4)] + newstring = everyotheritem(newstring) + return newstring + +print(removefirstandlastfour("abcdefghijklmnop")) + +def reversesequence(stringtouse): + newstring = "" + for i in range(len(stringtouse)): + newstring = newstring + stringtouse[-(len(stringtouse)-i-1)] + return newstring + +print(reversesequence('abcdefghijklmnop')) + + +#testing if will add. \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_04/dicionarylab.py b/students/Thomas_Gaffney/session_04/dicionarylab.py new file mode 100644 index 0000000..d3f5a12 --- /dev/null +++ b/students/Thomas_Gaffney/session_04/dicionarylab.py @@ -0,0 +1 @@ + diff --git a/students/Thomas_Gaffney/session_04/dict_lab.py b/students/Thomas_Gaffney/session_04/dict_lab.py new file mode 100644 index 0000000..4e56911 --- /dev/null +++ b/students/Thomas_Gaffney/session_04/dict_lab.py @@ -0,0 +1,42 @@ +startdict = {'Name' : "Chris", "City" : "Seattle", "Cake" : "Chocoolate"} + +print(startdict['Name']) + +startdict.pop('Cake') + +print(startdict) + +startdict['fruit'] = 'Mango' + +print(startdict.keys()) +print(startdict.values()) +print('cake' in startdict.keys()) +print('Mango' in startdict.values()) + + +newdict ={} +for keys in startdict.keys(): + print(keys) + newdict[keys] = startdict[keys].count('t')+startdict[keys].count('T') + +print(newdict) + +s2 = set(range(0,21, 2)) +s3 = set(range(0,21,3)) +s4 = set(range(0,21,4)) +print(s2) +print(s3) +print(s4) + +print(s3.issubset(s2)) +print(s4.issubset(s2)) + +pythonset = set(['p', 'y', 't', 'h', 'o', 'n']) +pythonset.update(['i']) +print(pythonset) + +frozenset = set(['m','a','r','a','t','h','o','n']) +print(frozenset) + +print(pythonset.union(frozenset)) +print(pythonset.intersection(frozenset)) \ No newline at end of file diff --git a/students/Thomas_Gaffney/session_05/Mailroomwio.py b/students/Thomas_Gaffney/session_05/Mailroomwio.py new file mode 100644 index 0000000..bbd28f6 --- /dev/null +++ b/students/Thomas_Gaffney/session_05/Mailroomwio.py @@ -0,0 +1,74 @@ +#!pythonpath + +def sendathankyou(donorDict): + while(True): + userselection = input('Please input the name of the donor, list to display a list of current users, or main to return to the main program:') + if(userselection.lower() == 'main'): break + elif(userselection.lower() == 'list'): + for keys in donorDict.keys(): + print(keys) + else: + if(userselection in donorDict.keys()): + user = userselection + else: + user = userselection + donorDict[user] = [] + donationamount = input('Please enter the donation amount for the selected user:') + + #Test if a number was given. + while (True): + try: + float(donationamount) + break + except: + donationamount = input('That was not a number, please try again:') + + donorDict[user].append(float(donationamount)) + thankyou = 'Dear {user}: \n \nThank You For Your Generous Donation of {donationamount}. \n \nThe Charity \n'.format(user = user, donationamount = donationamount) + print(thankyou) + + return donorDict + +def printareport(donorDict): + report_list = [] + for key in donorDict.keys(): + report_list.append([sum(donorDict[key]), key, len(donorDict[key]), sum(donorDict[key])/len(donorDict[key])]) + report_list.sort() + str = "|donor\t\t |donated\t |donations\t |avgdonation\t|\n" + for item in report_list: + str += '|{donor}\t |{donated}\t\t |{donations}\t\t |{avgdonation}\t\t|\n'.format(donor = item[1], + donated = item[0], + donations = item[2], + avgdonation = round(item[3],1)).expandtabs(8) + str.format('center align') + print(str) + +def store_thank_you(donorDict): + for key in donorDict.keys(): + user = key + donationamount = sum(donorDict[key]) + thankyou = 'Dear {user}: \n \nThank You For Your Generous Total Donations of {donationamount}. \n \nThe Charity \n'.format(user = user, donationamount = donationamount) + filepath = key+'thankyou'+'.txt' + print(filepath) + with open(filepath, 'w') as file: + file.write(thankyou) + + +if __name__ == '__main__' : + donorDict = {'Tom Jones' : [25, 10, 15], + 'Brad Hardy' : [5, 9], + 'Manuel Miller' : [4, 21], + 'Josh Benson' : [1], + 'Ashley Scanlon' : [4, 9, 50]} + + while(True): + userinput = input('Welcome to the mailroom! Would you like to :\n ' + '1. Send a Thank you \n ' + '2. Create a report \n ' + '3. Send a thank you to all users. \n ' + '4. Quit \n ' + 'Choice 1, 2, 3 or 4?:') + if (userinput == str(1)): donorDict = sendathankyou(donorDict) + elif (userinput == str(2)): printareport(donorDict) + elif (userinput == str(3)): store_thank_you(donorDict) + elif (userinput == str(4)): break diff --git a/students/Thomas_Gaffney/session_05/session_5_files_lab.py b/students/Thomas_Gaffney/session_05/session_5_files_lab.py new file mode 100644 index 0000000..583198f --- /dev/null +++ b/students/Thomas_Gaffney/session_05/session_5_files_lab.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Feb 4 22:12:54 2016 + +@author: tom.gaffney +""" + +language_list = [] +dict_of_languages ={} +with open('students.txt', 'r') as f: + for line in f: + colon_sep = line.rstrip().split(':') + languages = colon_sep[1].split(',') + for language in languages: + try: dict_of_languages[language] = dict_of_languages[language]+1 + except: dict_of_languages[language] = 1 + language_list.extend(languages) + +languages = list(set(language_list)) +print(languages) diff --git a/students/aderdouri/README.rst b/students/aderdouri/README.rst new file mode 100644 index 0000000..47d8a6e --- /dev/null +++ b/students/aderdouri/README.rst @@ -0,0 +1 @@ +# Python code for UWPCE-PythonCert class diff --git a/students/aderdouri/session02/Lab01_FizzBuzz/FizzBuzz.py b/students/aderdouri/session02/Lab01_FizzBuzz/FizzBuzz.py new file mode 100644 index 0000000..dbd701f --- /dev/null +++ b/students/aderdouri/session02/Lab01_FizzBuzz/FizzBuzz.py @@ -0,0 +1,25 @@ +# +# Date: Wednesday 20 January 2016 +# File name: FizzBuzz.py +# Version: 1 +# Author: Abderrazak DERDOURI +# Course: PYTHON 100 A: Programming In Python +# +# Description: Week 2 Lab#1 FizzBuzz +# +# Write a function to print out the numbers from 1 to n, but replace numbers divisible by 3 with "Fizz", numbers divisible by 5 with "Buzz". +# Numbers divisible by both factors should display "FizzBuzz". +# The function should be named FizzBuzz and be able to accept a natural number as argument. +# + + +def FizzBuzz(n): + for i in range(1, n+1): + if (0==i%3 and 0==i%5): + print ("FizzBuzz") + elif (0==i%3): + print ("Fizz") + elif (0==i%5): + print ("Buzz") + else: + print (i) diff --git a/students/aderdouri/session02/Lab01_FizzBuzz/main.py b/students/aderdouri/session02/Lab01_FizzBuzz/main.py new file mode 100644 index 0000000..9296622 --- /dev/null +++ b/students/aderdouri/session02/Lab01_FizzBuzz/main.py @@ -0,0 +1,37 @@ +# +# Date: Wednesday 20 January 2016 +# File name: main.py +# Version: 1 +# Author: Abderrazak DERDOURI +# Course: PYTHON 100 A: Programming In Python +# +# Description: FizzBuzz test +# +# + + + +import sys +from FizzBuzz import FizzBuzz + +def main(): + + print("-------------------------------") + print("play FizzBuzz") + print("-------------------------------") + + playFizzBuzz = True + while playFizzBuzz: + try: + input_var = input("Please enter a natural number : ") + if ("q"==input_var): + playFizzBuzz = False + else: + FizzBuzz(int(input_var)) + except ValueError: + print("Invalid entry") + + playFizzBuzz = True + +if __name__ == "__main__": + sys.exit(int(main() or 0)) \ No newline at end of file diff --git a/students/aderdouri/session02/Lab02_MoneyCounting/MoneyCounting.py b/students/aderdouri/session02/Lab02_MoneyCounting/MoneyCounting.py new file mode 100644 index 0000000..0f52ece --- /dev/null +++ b/students/aderdouri/session02/Lab02_MoneyCounting/MoneyCounting.py @@ -0,0 +1,24 @@ +# +# Date: Wednesday 20 January 2016 +# File name: MoneyCounting.py +# Version: 1 +# Author: Abderrazak DERDOURI +# Course: PYTHON 100 A: Programming In Python +# +# Description: Week 2 Lab#2 Money Counting +# +# Write a program to determine whether a mix of coins can make EXACTLY one dollar. +# Your program should prompt users to enter the number of pennies, nickels, dimes, and quarters. +# If the total value of the coins entered is equal to one dollar, the program should congratulate users for winning the game. +# Otherwise, the program should display a message indicating whether the amount entered was more than or less than a dollar. +# + + +def MoneyCounting(pennies, nickels, dimes, quarters): + amount = 0.01*pennies + 0.05*nickels + 0.1*dimes + 0.25*quarters + if(1==amount): + print ("Congratulation you are the winner") + elif (1>amount): + print ("Amount less than one dollar: ", amount) + elif (1: ") + if ("q"==pennies): + break + intPennies = int(pennies) + + nickels = input("Please enter the number of nickels : ") + if ("q"==nickels): + break + intNickels = int(nickels) + + dimes = input("Please enter the number of dimes : ") + if ("q"==dimes): + break + intDimes = int(dimes) + + quarters = input("Please enter the number of quarters : ") + if ("q"==quarters): + break + + intQuarters = int(quarters) + MoneyCounting(int(pennies), int(nickels), int(dimes), int(quarters)) + + except ValueError: + print("Invalid entry") + + playMoneyCounting = True + +if __name__ == "__main__": + sys.exit(int(main() or 0)) diff --git a/students/brandon_aleson/README.rst b/students/brandon_aleson/README.rst new file mode 100644 index 0000000..3eb5ef4 --- /dev/null +++ b/students/brandon_aleson/README.rst @@ -0,0 +1,3 @@ +# README + +Brandon Aleson's directory for Intro to Python 2016 diff --git a/students/brandon_aleson/lightening/readme.txt b/students/brandon_aleson/lightening/readme.txt new file mode 100644 index 0000000..fb7684c --- /dev/null +++ b/students/brandon_aleson/lightening/readme.txt @@ -0,0 +1,2 @@ +https://drive.google.com/file/d/0B_YO76AcjQ7bZUNkeVd3bFFhR00/view?usp=drive_web + diff --git a/students/brandon_aleson/session02/fizzBuzz.py b/students/brandon_aleson/session02/fizzBuzz.py new file mode 100644 index 0000000..76cfac6 --- /dev/null +++ b/students/brandon_aleson/session02/fizzBuzz.py @@ -0,0 +1,14 @@ +# Brandon Aleson +# Intro to Python +# 1/27/16 +# fizzbuzz + +for thing in range(1, 101): + if (thing % 3 == 0 and thing % 5 == 0): + print('fizzbuzz') + elif (thing % 3 == 0): + print('fizz') + elif (thing % 5 == 0): + print('buzz') + else: + print(thing) diff --git a/students/brandon_aleson/session02/series.py b/students/brandon_aleson/session02/series.py new file mode 100644 index 0000000..c7888b8 --- /dev/null +++ b/students/brandon_aleson/session02/series.py @@ -0,0 +1,45 @@ +# Brandon Aleson +# Intro to Python +# 1/27/16 +# series + + +def fibonacci(n): + """ This function returns the nth value in the fibonacci series """ + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return fibonacci(n - 1) + fibonacci(n - 2) + + +def lucas(n): + """ This function returns the nth value in the lucas series """ + if n == 0: + return 2 + elif n == 1: + return 1 + else: + return lucas(n - 1) + lucas(n - 2) + + +def sum_series(n, i=0, j=1): + """ + Calling this function with no optional parameters will print numbers from the fibonacci series. + Calling it with the optional parameters 2 and 1 will print values from the lucas series. + Other values for the optional parameters will print other series. + """ + if n == 0: + return i + elif n == 1: + return j + else: + return sum_series(n - 1) + sum_series(n - 2) + + +# these assert statements test the preceding functions +assert fibonacci(10) == 55 +assert lucas(10) == 123 +assert sum_series(10) == 55 +assert sum_series(10, 2, 1) == 123 diff --git a/students/brandon_aleson/session03/list_lab.py b/students/brandon_aleson/session03/list_lab.py new file mode 100755 index 0000000..5430fe5 --- /dev/null +++ b/students/brandon_aleson/session03/list_lab.py @@ -0,0 +1,67 @@ +#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 +# Brandon Aleson +# Intro to Python +# 1/27/16 +# list lab + + +# 1st section +fruit = ['apples', 'pears', 'oranges', 'peaches'] +print(fruit) + +fruit.append(input("What is another fruit that you like?\n")) +print(fruit) + +fruitIndex = int(input("Pick a number between 1 and 5\n")) +print('You picked', end=" ") +print(fruit[(fruitIndex-1)]) + +fruit = ['cherries'] + fruit +print(fruit) + +fruit.insert(0, 'blueberries') +print(fruit) + +for fruits in fruit: + if fruits[0] == 'p': + print(fruits) + + +# 2nd section +fruity = fruit[:] +print(fruity) + +del fruity[-1] +print(fruity) + +fruity.remove(input("What is your least favorite fruit from the list above?\n")) +print('It\'s gone! ', end="") +print(fruity) + + +# 3rd section +fruities = fruit[:] +for fruitiez in fruities[:]: + preference = input("Do you like {}?\n".format(fruitiez)) + while (preference != 'yes' and preference != 'no'): + preference = input("It's a simple yes or no question\n") + if preference == 'no': + fruities.remove(fruitiez) + print("removing {} from your list of fruits your majesty".format(fruitiez)) + +if fruities: + print('so you like these fruits: ') + print(fruities) +else: + print('you must not like fruit very much') + + +# 4th section +fruitz = fruit[:] +fruitzCopy = [] +for sweetThing in fruitz[:]: + sweetThing = sweetThing[::-1] + fruitzCopy.append(sweetThing) +del fruitz[-1] +print(fruitz) +print(fruitzCopy) diff --git a/students/brandon_aleson/session03/slicingLab.py b/students/brandon_aleson/session03/slicingLab.py new file mode 100644 index 0000000..eeaa59b --- /dev/null +++ b/students/brandon_aleson/session03/slicingLab.py @@ -0,0 +1,41 @@ +# Brandon Aleson +# Intro to Python +# 1/27/16 +# slice lab + + +# return a sequence with the first and last items exchanged. +def switch(n): + first = n[0] + last = n[-1] + n[0] = last + n[-1] = first + return n + # better solution: + # newList = n[-1]+n[1:-1]+n[0] + # return newList + + +# return a sequence with every other item removed +def skip(n): + skipped = n[::2] + return skipped + + +# return a sequence with the first and last 4 items removed, and every other item in between +def chop(n): + chopped = n[4:(len(n)-4):2] + return chopped + + +# return a sequence reversed +def reverse(n): + n = n[::-1] + return n + + +# return a sequence with the middle third, then last third, then the first third in the new order +def thirds(n): + third = int(len(n)/3) + thirds = n[third:(third*2)] + n[(third*2):(len(n))] + n[:third] + return thirds diff --git a/students/brandon_aleson/session04/dict_lab.py b/students/brandon_aleson/session04/dict_lab.py new file mode 100755 index 0000000..8743079 --- /dev/null +++ b/students/brandon_aleson/session04/dict_lab.py @@ -0,0 +1,59 @@ +#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 +# Brandon Aleson +# Intro to Python +# 1/28/16 +# dictionary lab + + +# 1st series +chrisDict = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'} +print(chrisDict) + +chrisDict.pop('cake') +print(chrisDict) + +chrisDict['fruit'] = 'mango' +print(chrisDict) + +print(chrisDict.keys()) +print(chrisDict.values()) +print('cake' in chrisDict) + +chrisValues = chrisDict.values() +print('Chris likes mangoes!') if ('mango' in chrisValues) else print('Chris would prefer not to have a mango thank you very much') + + +# 2nd series +chrisCopy = {} +for k, v in chrisDict.items(): + chrisCopy[k] = v.count('t') + + +# 3rd series +s2 = set() +s3 = set() +s4 = set() +for i in range(21): + if i % 2 == 0: + s2.add(i) + if i % 3 == 0: + s3.add(i) + if i % 4 == 0: + s4.add(i) +print(s2) +print(s3) +print(s4) + +print(s3.issubset(s2)) +print(s4.issubset(s2)) + + +# 4th section +ipython = set('python') +ipython.add('i') +marathon = frozenset('marathon') + +print(ipython.union(marathon)) +print(marathon.union(ipython)) +print(ipython.intersection(marathon)) +print(marathon.intersection(ipython)) diff --git a/students/brandon_aleson/session04/mailroom.py b/students/brandon_aleson/session04/mailroom.py new file mode 100755 index 0000000..5dfe78e --- /dev/null +++ b/students/brandon_aleson/session04/mailroom.py @@ -0,0 +1,123 @@ +#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 +# Brandon Aleson +# Intro to Python +# 1/29/16 +# mailroom + + +donorList = ['Brandon Aleson', 'Paulina Ploszajska', 'Jesse Montini-Vose', 'Mary Montini', 'Shirley Aleson'] +amountList = [[120000], [4000], [500, 300, 800], [1467, 1467], [8, 5, 25]] +donors = {} + + +def initializeDict(): + for i, j in zip(donorList, amountList): + donors[i] = j + return donors + + +# control flow handler +def choose(): + print('What would you like to do?') + action = input('(type \'s\' to send a thank you message, \'c\' to create a report, or \'q\' to quit)\n') + while (action != 's' and action != 'c' and action != 'q'): + action = input('I\'m not doing anything until you give me one of those three letters\n') + if action == 's': + sendThanks() + return True + elif action == 'c': + createReport() + return True + elif action == 'q': + return False + + +# main function for sending thank you email +def sendThanks(): + input('Let\'s send some thanks!\n') + name, amount = donorInput() + sendEmail(name, amount) + input() + + +# receive input on which donor to thank +# if donor doesn't exist, add to the dictionary +def donorInput(): + name = input('Give me a full name, or type \'l\' to list the current donors on file\n') + while name == 'l': + printDonors() + name = input('Choose one of the above, or give me a new name\n') + donors.setdefault(name, []) + while True: + try: + amount = input('How much did they give?\n') + amount = int(amount) + print() + break + except ValueError: + print('That\'s not nice, you almost broke me') + print('Donations are usually positive integers') + donors[name].append(amount) + return (name, amount) + + +# print current list of donors +def printDonors(): + print('Here are the current donors:') + for d in donors: + print(d) + return "" + + +# send formatted thank you email +def sendEmail(name, amount): + print('What a nice person!') + input('Let\'s send them this heartfelt email:\n') + print('Dear {},\nThank you for your donation of ${:,}.\nYou\'re great!'.format(name, amount)) + + +# sorting key function for return value of computeSortedStats() +def statSorter(sorter): + return sorter[3] + + +# compile relevant donor statistcs into a sorted list for printReport() +def computeSortedStats(): + stats = [] + for d, a in donors.items(): + stats.append([d, a]) + for item in stats: + item.append(len(item[1])) + item.append(int((sum(item[1]))/(len(item[1])))) + item.append(sum(item[1])) + del item[1] + return sorted(stats, key=statSorter) + + +# print formatted donor report +def printReport(statList): + print('{:-^80}'.format('DONOR REPORT')) + print('{:<20}{:<20}{:<20}{:<20}'.format('DONOR NAME', '# OF DONATIONS', 'AVERAGE AMOUNT', 'TOTAL DONATED')) + for item in statList: + print('{:<20}{:<20}${:<20}${:,}'.format(item[0], item[1], item[2], item[3])) + print('{:-^80}'.format('--')) + + +# main function for creating donor report +def createReport(): + input('crunching the numbers...\n') + statList = computeSortedStats() + printReport(statList) + input() + + +if __name__ == '__main__': + initializeDict() + loop = True + + input('Welcome to the mailroom!\n') + + while loop: + loop = choose() + + print('I\'ll be here when you need me') diff --git a/students/calvinfannin/README.rst b/students/calvinfannin/README.rst new file mode 100644 index 0000000..4215210 --- /dev/null +++ b/students/calvinfannin/README.rst @@ -0,0 +1,3 @@ +#Python Code for UWPCE-PYTHON cert class + +added more stuff diff --git a/students/calvinfannin/session_01/booleans.py b/students/calvinfannin/session_01/booleans.py new file mode 100644 index 0000000..e69de29 diff --git a/students/calvinfannin/session_01/fizzbuzz.py b/students/calvinfannin/session_01/fizzbuzz.py new file mode 100644 index 0000000..89f3950 --- /dev/null +++ b/students/calvinfannin/session_01/fizzbuzz.py @@ -0,0 +1,12 @@ +# Calvin Fannin +# fizzbuzz lab + +for x in range(1, 101): + if x % 15 == 0: + print('FizzBuzz') + elif x % 3 == 0: + print('Fizz') + elif x % 5 == 0: + print('Buzz') + else: + print(x) diff --git a/students/calvinfannin/session_02/grid_printer.py b/students/calvinfannin/session_02/grid_printer.py new file mode 100644 index 0000000..9774215 --- /dev/null +++ b/students/calvinfannin/session_02/grid_printer.py @@ -0,0 +1,9 @@ +# Calvin Fannin +# Grid Printer Exercise + +for x in range(1, 12): + if x in (1, 6, 11): + print('+', '-' * 4, '+', '-' * 4, '+') + else: + print('|', ' ' * 4, '|', ' ' * 4, '|') +print() \ No newline at end of file diff --git a/students/calvinfannin/session_02/series.py b/students/calvinfannin/session_02/series.py new file mode 100644 index 0000000..29b177b --- /dev/null +++ b/students/calvinfannin/session_02/series.py @@ -0,0 +1,3 @@ +# Calvin Fannin +# fibonacci series lab +def fibonacci (n): diff --git a/students/calvinfannin/session_04/dict_lab.py b/students/calvinfannin/session_04/dict_lab.py new file mode 100755 index 0000000..8c3ffe1 --- /dev/null +++ b/students/calvinfannin/session_04/dict_lab.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +''' +Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate”. +Display the dictionary. +Delete the entry for “cake”. +Display the dictionary. +Add an entry for “fruit” with “Mango” and display the dictionary. +Display the dictionary keys. +Display the dictionary values. +Display whether or not “cake” is a key in the dictionary (i.e. False) (now). +Display whether or not “Mango” is a value in the dictionary (i.e. True). +''' +dict = {'Name': 'Chris', 'City': 'Seattle', 'Cake': 'Chocolate'}; +print(dict) +dict.pop('Cake') +print(dict) +dict['Fruit']='Mango' +print(dict) +for x in dict.values(): + print(x) + +print('Mango' in dict.values()) +print('Cake' in dict.keys()) + + diff --git a/students/gmckeag/EddieFace.jpg b/students/gmckeag/EddieFace.jpg new file mode 100644 index 0000000..c6bca93 Binary files /dev/null and b/students/gmckeag/EddieFace.jpg differ diff --git a/students/gmckeag/README.rst b/students/gmckeag/README.rst new file mode 100644 index 0000000..7a41d00 --- /dev/null +++ b/students/gmckeag/README.rst @@ -0,0 +1,7 @@ +Greg McKeag's Python 100 folder + +.. image:: EddieFace.jpg + :height: 100 + :width: 100 + :scale: 50 + :alt: Eddie Codes \ No newline at end of file diff --git a/students/gmckeag/session2/fizbuz.py b/students/gmckeag/session2/fizbuz.py new file mode 100755 index 0000000..37aa025 --- /dev/null +++ b/students/gmckeag/session2/fizbuz.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +def FizBuz(n): + """ FizBuz """ + + for i in range(n): + if i % 3 == 0 and i % 5 == 0: + print('FizBuz') + elif i % 3 == 0: + print('Fiz') + elif i % 5 == 0: + print('Buz') + else: + print(i) + +if __name__ == '__main__': + FizBuz(100) diff --git a/students/gmckeag/session2/grid.py b/students/gmckeag/session2/grid.py new file mode 100644 index 0000000..c21e09d --- /dev/null +++ b/students/gmckeag/session2/grid.py @@ -0,0 +1,16 @@ +def grid(n): + """ Returns grid string """ + horizontal_border = '+' + n * ' -' + ' + ' + n * '- ' + '+\n' + vertical_border = '|' + n * ' ' + ' | ' + n * ' ' + '|\n' + + grid = str() + for i in range(2*n+1): + if i == 0 or i == n or i == 2*n: + grid += horizontal_border + else: + grid += vertical_border + return grid + +if __name__ == '__main__': + n = int(input('Enter an int: ')) + print(grid(n)) diff --git a/students/gmckeag/session2/series.py b/students/gmckeag/session2/series.py new file mode 100644 index 0000000..7b94176 --- /dev/null +++ b/students/gmckeag/session2/series.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 + +def fib(n): + """ Return nth fibonacci number - iteratively + """ + a, b = 0, 1 + for i in range(n): + a, b = b, a + b + return a + +def fibonacci(n): + """ Returns nth fibonacci number - recursively + """ + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return fibonacci(n-1) + fibonacci(n-2) + + +def lucas(n): + """ Returns nth lucas number + """ + a, b = 2, 1 + for i in range(n): + a, b = b, a + b + return a + +def series_sum(n, first=0, second=1): + """ Returns nth series sum given first and second series elements + """ + a, b = first, second + for i in range(n): + a, b = b, a + b + return a + + +if __name__ == '__main__': + assert fibonacci(0) == 0 + assert fibonacci(1) == 1 + assert fibonacci(2) == 1 + assert fibonacci(3) == 2 + assert fibonacci(4) == 3 + + assert series_sum(0) == 0 + assert series_sum(1) == 1 + assert series_sum(2) == 1 + assert series_sum(3) == 2 + assert series_sum(4) == 3 + + assert lucas(0) == 2 + assert lucas(1) == 1 + assert lucas(2) == 3 + assert lucas(3) == 4 + assert lucas(4) == 7 + + assert series_sum(0, 2, 1) == 2 + assert series_sum(1, 2, 1) == 1 + assert series_sum(2, 2, 1) == 3 + assert series_sum(3, 2, 1) == 4 + assert series_sum(4, 2, 1) == 7 + + + n = int(input('Enter n: ')) + print("Fibonacci(", n, ") = ", fibonacci(n)) + print("Fibonacci(", n, ") = ", series_sum(n, 0, 1)) + print("Lucas(", n, ") = ", lucas(n)) + print("Lucas(", n, ") = ", series_sum(n, 2, 1)) + + + + diff --git a/students/gmckeag/session3/list_lab.py b/students/gmckeag/session3/list_lab.py new file mode 100755 index 0000000..74c9c30 --- /dev/null +++ b/students/gmckeag/session3/list_lab.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +# +# list_lab.py +# + +if __name__ == '__main__': + + # Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. + fruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] + + # Display the list. + print(fruit) + + # Ask the user for a number and display the number back to the user and the fruit corresponding to that number + # (on a 1-is-first basis). + index = int(input('Enter fruit list index:')) + print(fruit[index - 1]) + + # Add another fruit to the beginning of the list using “+” and display the list. + fruit = ['Kiwi'] + fruit + print(fruit) + + # Add another fruit to the beginning of the list using insert() and display the list. + fruit.insert(0, 'Banana') + print(fruit) + + # Display all the fruits that begin with “P”, using a for loop. + for item in fruit: + if 'P' in item: print(item) + + # + # Using the list created in series 1 above: + # + # Display the list. + # Remove the last fruit from the list. + # Display the list. + # Ask the user for a fruit to delete and find it and delete it. + + print(fruit) + fruit.pop() + print(fruit) + item = input('Enter fruit to be deleted:') + if item in fruit: + fruit.remove(item) + print(fruit) + + + # Again, using the list from series 1: + # + # Ask the user for input displaying a line like “Do you like apples?” + # for each fruit in the list (making the fruit all lowercase). + + for item in fruit[:]: + done = False + while not done: + prompt = 'Do you like ' + item.lower() + '? Yes or no? ' + response = input(prompt) + + # For each “no”, delete that fruit from the list. + if 'no' in response.lower(): + fruit.remove(item) + done = True + if 'yes' in response.lower(): + done = True + # Display the list. + print(fruit) + + + # Once more, using the list from series 1: + # + # Make a copy of the list and reverse the letters in each fruit in the copy. + + fruit_reversed = [] + for item in fruit[:]: + item_reversed = item[::-1] + fruit_reversed.append(item_reversed) + + + # Delete the last item of the original list. Display the original list and the copy. + fruit.pop() + print(fruit) + print(fruit_reversed) diff --git a/students/gmckeag/session3/rot13.py b/students/gmckeag/session3/rot13.py new file mode 100755 index 0000000..ae974d7 --- /dev/null +++ b/students/gmckeag/session3/rot13.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +def rot13(s): + """ + Encode/Decode ROT-13 string + + :param s - string to be encoded ROT-13: + :return string + """ + + from_table += 'abcdefghijklmnopqrstuvwxyz' + from_table += from_table.upper() + + to_table += 'nopqrstuvwxyzabcdefghijklm' + to_table += to_table.upper() + + rot13_encoding_table = str.maketrans(from_table, to_table) + + encoded_char_list = [c.translate(rot13_encoding_table) for c in s] + + return ''.join(encoded_char_list) + + +if __name__ == '__main__': + s1 = 'abcdEFG This is a Little Thing with 3423t23t0~~2#@ junk IN the Middle 123\n' + assert rot13(rot13(s1)) == s1 + print(rot13('Zntargvp sebz bhgfvqr arne pbeare')) + + +# nicely done! diff --git a/students/gmckeag/session3/slicing.py b/students/gmckeag/session3/slicing.py new file mode 100644 index 0000000..9af2984 --- /dev/null +++ b/students/gmckeag/session3/slicing.py @@ -0,0 +1,27 @@ +def first_and_last(s): + return [s[0], s[-1]] + +def every_other_removed(s): + return s[::2] + +def loose_first_last4_and_every_other_between(s): + return s[1:-4:2] + +def reverse(s): + return s[::-1] + +def thirds(s): + third = len(s) // 3 + return s[third:] + s[:third] + + +if __name__ == '__main__': + s = [1,2,3,4,5,6,7,8,9,10,11,12] + print('List = ', s) + print('First and last = ', first_and_last(s)) + print('Every other removed =', every_other_removed(s)) + print('First removed, last 4 removed and every other between removed = ', loose_first_last4_and_every_other_between(s)) + print('Reversed = ', reverse(s)) + print('Middle Last, First = ', thirds(s)) + + diff --git a/students/gmckeag/session4/dict_lab.py b/students/gmckeag/session4/dict_lab.py new file mode 100644 index 0000000..a3a9faa --- /dev/null +++ b/students/gmckeag/session4/dict_lab.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 + +# Add the file to your clone of the repository and commit changes frequently while working on the following tasks. +# When you are done, push your changes to GitHub and issue a pull request. +# +# (if you are struggling with git – just write the code for now) +# +# When the script is run, it should accomplish the following four series of actions: +# +# Create a dictionary containing “name”, “city”, and “cake” for “Chris” from “Seattle” who likes “Chocolate”. + +aDict = { "name": 'Chris', 'city': "Seattle", 'cake': 'Chocolate'} + + +# Display the dictionary. + +print(aDict) + +# Delete the entry for “cake”. + +del aDict['cake'] + +# Display the dictionary. + +print(aDict) + +# Add an entry for “fruit” with “Mango” and display the dictionary. + +aDict['fruit'] = 'Mango' + +# Display the dictionary keys. + +print(aDict.keys()) + +# Display the dictionary values. + +print(aDict.values()) + +# Display whether or not “cake” is a key in the dictionary (i.e. False) (now). + +print('cake' in aDict) + +# Display whether or not “Mango” is a value in the dictionary (i.e. True). + +print('Mango' in aDict.values()) + + +# Using the dictionary from item 1: Make a dictionary using the same keys but with the number of ‘t’s in each value. + +aDict2 = {} +for k in aDict: + aDict2[k] = aDict[k].count('t') +print(aDict2) + +# Create sets s2, s3 and s4 that contain numbers from zero through twenty, divisible 2, 3 and 4. + +s2 = set([i for i in range(21) if i % 2 == 0]) +s3 = set([i for i in range(21) if i % 3 == 0]) +s4 = set([i for i in range(21) if i % 4 == 0]) + + +# Display the sets. + +print(s2) +print(s3) +print(s4) + +# Display if s3 ise a subset of s2 (False) + +if s3.issubset(s2): print('s3 is a subset of s2', s2) + + +# and if s4 is a subset of s2 (True). + +if s4.issubset(s2): print('s4 is a subset of s2', s4) + +# Create a set with the letters in ‘Python’ and add ‘i’ to the set. + +p = set('Python') +p.add('i') +print(p) + +# Create a frozenset with the letters in ‘marathon’ + +f = frozenset('marathon') + +# display the union and intersection of the two sets. +# + +print(p.union(f)) +print(p.intersection(f)) + diff --git a/students/gmckeag/session4/mailroom.py b/students/gmckeag/session4/mailroom.py new file mode 100755 index 0000000..2df3d1b --- /dev/null +++ b/students/gmckeag/session4/mailroom.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +from operator import itemgetter +import json +import os.path + +user_option_dict = {0: 'Unknown', 'SendThankYou': 'Send Thank You', 'CreateDonorReport': "Create Report", 'Quit': 'Quit', 'list': 'List donor names'} + +default_donor_dict = { + 'Fred Barnes': [200, 550, 125], + 'Mary Jane': [2500, 25], + 'Eric Idol': [400000, 250, 1], + 'Lucy Love': [25, 25], + 'Mr Trump': [1] +} +donor_dict = None + + +def get_top_level_menu_response(): + """ Display top level menur and query user for response """ + prompt = """ + *** Mailroom Menu Options *** + + Select from the following: + 1 --- Send a thank you + 2 --- Create a report + Q --- To Quit + > Enter 1, 2 or Q : """ + + selection = user_option_dict[0] + while selection == user_option_dict[0]: + + user_input = input(prompt) + + if user_input == '1': + selection = user_option_dict['SendThankYou'] + elif user_input == '2': + selection = user_option_dict['CreateDonorReport'] + elif user_input[0].upper() == 'Q': + selection = user_option_dict['Quit'] + else: + selection = user_option_dict[0] + print(' Unrecognized input, please try again\n') + + print('\n You selected: {}\n'.format(selection)) + + return selection + + +def thank_donor(donor): + """ Display thank you email message to donor """ + print(""" + Dear {name}, + + Thank you for your generous gift of ${amount}. + + """.format(name=donor, amount=donor_dict[donor][-1])) + + +def list_donors(): + """ Display list of donors """ + print('\n Donors') + print(' -------------------') + for donor in donor_dict: + print(' {:16s}'.format(donor)) + + +def get_thank_you_menu_response(): + """ Display 'send thank you menu and prompt for response """ + prompt = """ + ** Send Thank You Menu Options ** + + Enter one of the following: + To send thank you ....... Enter: donor's full name + To list donors .......... Enter: list + To return to top menu ... Enter: Q + > Enter: """ + + selection = user_option_dict[0] + while selection == user_option_dict[0]: + + prompt_for_donation = False + + user_input = input(prompt) + + if user_input.lower() == 'list': + list_donors() + elif user_input in donor_dict: + prompt_for_donation = True + elif user_input[0].upper() == 'Q': + selection = user_option_dict['Quit'] + else: + prompt_for_donation = True + + if prompt_for_donation: + donation_amount = input('Enter amount of donation (or Q to quit) $: ') + if donation_amount[0].upper() != 'Q': + selection = user_input + if user_input not in donor_dict: + donor_dict[user_input] = [] + + try: + donation_amount = int(donation_amount) + donor_dict[user_input].append(donation_amount) + except: + selection = user_option_dict[0] + else: + selection = user_option_dict['Quit'] + + return selection + + +def run_send_thank_you_menu(): + """ get response to send thank you menu and if a new donation is entered thank the donow """ + selection = get_thank_you_menu_response() + if selection != user_option_dict['Quit']: + thank_donor(selection) + + +def display_donor_report(): + """ + Print donor report + + Print table of donors in descending order of total donations given + """ + donor_list = [] + for donor in donor_dict: + donor_list.append((donor, sum(donor_dict[donor]))) + + donor_list = sorted(donor_list, key=itemgetter(1), reverse=True) + + print(" Name $ Total Donations $ Average") + print(" --------------------------------------------------------") + + for record in donor_list: + donor = record[0] + print(" {name:16s} {total:10,.2f} {count:2} {avg:10,.2f}".format( + name=donor, + count=len(donor_dict[donor]), + avg=sum(donor_dict[donor]) / float(len(donor_dict[donor])), + total=sum(donor_dict[donor]))) + + +def load_donor_data(filename): + """ load donor data from json file """ + global donor_dict + if not os.path.exists(filename): + donor_dict = default_donor_dict + else: + with open(filename) as donor_data_file: + json_string = donor_data_file.read() + donor_dict = json.loads(json_string) + donor_data_file.close() + + +def save_donor_data(filename): + """ save donor data to json file """ + global donor_dict + with open(filename, 'w') as donor_data_file: + json_string = json.dumps(donor_dict) + donor_data_file.write(json_string) + donor_data_file.close() + + +def run_mailroom_loop(): + """ Mailroom run loop """ + user_selection = user_option_dict[0] + while user_selection != user_option_dict['Quit']: + user_selection = get_top_level_menu_response() + if user_selection == user_option_dict['Quit']: + done = True + elif user_selection == user_option_dict['SendThankYou']: + run_send_thank_you_menu() + elif user_selection == user_option_dict['CreateDonorReport']: + display_donor_report() + + +def main(): + """ main """ + DONOR_DATA_FILENAME = 'donor_data.json' + + load_donor_data(DONOR_DATA_FILENAME) + run_mailroom_loop() + save_donor_data(DONOR_DATA_FILENAME) + +if __name__ == "__main__": + main() diff --git a/students/jjstiehl/README_JS.rst b/students/jjstiehl/README_JS.rst new file mode 100644 index 0000000..9907942 --- /dev/null +++ b/students/jjstiehl/README_JS.rst @@ -0,0 +1,18 @@ +IntroToPython +============== + +This is for Julie Stiehl + +students directory + +Make for yourself a personal directory within this directory. + +Within your personal directory we recommend a series of sub directorys which mirror the layout of the class: + +* session01 +* session02 +* session03 + +Keep each week's work in the corresonding directory. + +Use git to share your work with the the instructors and the rest of the class. \ No newline at end of file diff --git a/students/jjstiehl/Session02/FizzBuzzLab.py b/students/jjstiehl/Session02/FizzBuzzLab.py new file mode 100644 index 0000000..9db0f57 --- /dev/null +++ b/students/jjstiehl/Session02/FizzBuzzLab.py @@ -0,0 +1,32 @@ +''' +Author: Julie Stiehl +Week 2 Lab#1 FizzBuzz +Notes: this is close but not quite correct +''' +''' +def fizzbuzz(n): + a = 0 # can you use range here to apply this function to integers between 1 and 100? + while a 1: + print("Too high. Try again.") +else: + print("Start over.") diff --git a/students/kbindhu/.ipynb_checkpoints/Untitled-checkpoint.ipynb b/students/kbindhu/.ipynb_checkpoints/Untitled-checkpoint.ipynb new file mode 100644 index 0000000..1ee3049 --- /dev/null +++ b/students/kbindhu/.ipynb_checkpoints/Untitled-checkpoint.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a = ['a', 'b', 'c']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b = 3" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a[0:2]" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'int' object is not subscriptable", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: 'int' object is not subscriptable" + ] + } + ], + "source": [ + "a[0:2]+b[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b = ['d', 'e']" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'d'" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b', 'd']" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a[0:2]+b[0:1]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/kbindhu/Untitled.ipynb b/students/kbindhu/Untitled.ipynb new file mode 100644 index 0000000..1ee3049 --- /dev/null +++ b/students/kbindhu/Untitled.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a = ['a', 'b', 'c']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b = 3" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a[0:2]" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'int' object is not subscriptable", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: 'int' object is not subscriptable" + ] + } + ], + "source": [ + "a[0:2]+b[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "b = ['d', 'e']" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'d'" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b', 'd']" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a[0:2]+b[0:1]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/kbindhu/readme.rst b/students/kbindhu/readme.rst new file mode 100644 index 0000000..45b983b --- /dev/null +++ b/students/kbindhu/readme.rst @@ -0,0 +1 @@ +hi diff --git a/students/kbindhu/session02/Fizzbuzz.py b/students/kbindhu/session02/Fizzbuzz.py new file mode 100644 index 0000000..f799bb5 --- /dev/null +++ b/students/kbindhu/session02/Fizzbuzz.py @@ -0,0 +1,11 @@ +#!/usr/bin/python +for i in range(1,101): + if i%3==0: # can you simplify this using 'OR' and 'AND' ? + if i%5==0: + print ("FizzBuzz") + else: + print("Fizz") + elif (i%5==0): + print("Buzz") + else: + print(i) diff --git a/students/kbindhu/session02/Grid.py b/students/kbindhu/session02/Grid.py new file mode 100644 index 0000000..5908848 --- /dev/null +++ b/students/kbindhu/session02/Grid.py @@ -0,0 +1,71 @@ +#!/usr/bin/python + +"""remove comments to run the function""" +#part1 of grid excercise + +def grid_part1(): + plus= '+' + minus='-' + bar='|' + for i in range(3): + """below prints +----+----+""" + print(plus+4*minus+plus+4*minus+plus) + if(i==2): + """this break is make sure only +----+ will be printed last doesnt need the |---|---|""" + break + for j in range(4): + """print | | | four times""" + print(bar+4*" "+bar+4*" "+bar) + +#call function for testing +#grid_part1() + +#Part2 of grid exercise generalized function + +def grid_part2(n): + plus= '+' + minus='-' + bar='|' + mult=n//2 + for i in range(3): + """below prints +----+----+""" + print(plus+mult*minus+plus+mult*minus+plus) + if(i==2): + """this break is make sure only +----+ will be printed last doesnt need the |---|---|""" + break + for j in range(mult): + """print | | | mult times""" + print(bar+mult*" "+bar+mult*" "+bar) + +#call function for testing +#grid_part2(15) + + +#part3 of grid execise +# my comments assume grid(3,4) ie 3 rows and 4 columns +def grid_part3(rows,columns): + plus= '+' + minus='-' + bar='|' + for l in range(rows): + for i in range(rows): + """ print (+ and columns*-)eg:grid(3,4) below + loop prints "+---- "for 3 times (rows) ie +----+----+----+""" + print(plus+columns*minus,end='') + print(plus) + """below loop prints bar followed by spaces*no of columns. + Inner j loop prints 'bar followed by 4 spaces(columns) + outerloop with k iterator print tha bar folllowed by 4 spaces it for no of rows""" + for k in range(columns): + for j in range (rows+1): + print(bar+columns*" ",end='') + """newline""" + print() + """ below loop print last line of grid which is a +- pattern""" + for m in range(rows): + print(plus+columns*minus,end='') + print(plus) + + +#call for function +#grid_part3(5,3) diff --git a/students/kbindhu/session02/series.py b/students/kbindhu/session02/series.py new file mode 100644 index 0000000..53849b9 --- /dev/null +++ b/students/kbindhu/session02/series.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +#fibonacci +def fibonacci(n): + """Returning base case for recursion ie 0 and 1 case""" + if(n==0): + return 0 + elif(n==1): + return 1 + else: + """recursively calling fibonacci function for numbers other than 0 and 1 + suppose n=3,the following take place + fibonacci(3)=fibonacci(1)+fibonacci(2),which breaks + 1+(fibonacci(0)+fibonacci(1)),which is + 1+0+1=2""" + return(fibonacci(n-2)+fibonacci(n-1)) + +#print (fibonacci(6)) + +#lucas function +def lucas(n): + """Returning base case for recursion ie 0 and 1 case""" + if(n==0): + return 2 + elif(n==1): + return 1 + else: + """recursively calling fibonacci function for numbers other than 0 and 1 + suppose n=3,the following take place + lucas(3)=lucas(1)+lucas(2),which breaks + 1+(lucas(0)+lucas(1)),which is + 1+2+1=4""" + return(lucas(n-2)+lucas(n-1)) +#print(lucas(4)) + +#generiliazed function +def sum_series(reqd,op1=0,op2=1): + """base values in series are set by optional parameters + eg if op1 is 0 and op2 is 1 the series will be fibonacci and if op1 and op2 are 2 and 1 respectively series will be lucas + """ + if(reqd==0): + return op1 + elif(reqd==1): + return op2 + else: + """other vlaues are printed by below statement here function call requires op1 and op2 since they are set from out of + function""" + return(sum_series(reqd-2,op1,op2)+sum_series(reqd-1,op1,op2)) + +#print(sum_series(4,2,1)) + + +#function call +print ("fibonacci vlaue of 6 is",fibonacci(6)) +print("lucas value of 4 is",lucas(4)) +print("value of series for (4 3 1 )is",sum_series(4,3,1)) +#assertion block +#test for fibonacci series +#testing a passing case for fibonacci +assert fibonacci(6)==8 +# testing a failing case for lucas +assert lucas(4)==4 +#testing sum series case +#pass case +assert sum_series(4,3,1)==9 +#fail case +assert sum_series(3,3,1)==4 diff --git a/students/kbindhu/session03/rot_13.py b/students/kbindhu/session03/rot_13.py new file mode 100644 index 0000000..7cf3b40 --- /dev/null +++ b/students/kbindhu/session03/rot_13.py @@ -0,0 +1,45 @@ +#!/usr/bin/python +#Author:kbindhu +#Date:1/27/2016 +#ROT13 encryption +"""Below program takes any amount of text and returns the text with each letter replaced +by letter 13 away from it.""" +"""Algorithm is to convert each letter in the input text to ascii code with ord function. +Then for alphabets a-m and A-M add 13 to ascii values and for n-z and N-Z subtract 13 from ascii values.All other +characters are printed like space are printed as such""" +import codecs +def rot13( myString): + out_str='' + for i in myString: + encp=ord(i) + """checking that ascii corresponds to alaphbets a-m or A-M add 13 to it and find the corresponding letter""" + if(97<=encp<110) or (65<=encp<78): + encp=encp+13 + #print(chr(encp),end='') + out_str+=chr(encp) + """if ascii corresponds to alphabets above m subtract 13 from the ascii and findcorresponding letter""" + elif(110<=encp<=122) or(78<=encp<=90): + encp =encp-13 + #print(chr(encp),end='') + out_str+=chr(encp) + else: + #print(i,end='') + out_str+=chr(encp) + return out_str + + +#Test block +if __name__ == '__main__': + print("Main module is being run directly ") + Myoutstrng=rot13("Hello") + #using the rot_13 algorithm to test my code + assert (Myoutstrng) == codecs.encode('Hello', 'rot_13') + Myoutstrng=rot13("Zntargvp sebz bhgfvqr arne pbeare") + assert (Myoutstrng) == codecs.encode('Zntargvp sebz bhgfvqr arne pbeare', 'rot_13') + Myoutstrng=rot13("Zntargvpjij**") + + assert(Myoutstrng)=='deewhuhfu',"Asssertion Error,Expected is :%s" %codecs.encode('Zntargvpjij**', 'rot_13') +else: + print("rot_13.py is being imported into another module ") + +# nicely done! diff --git a/students/kbindhu/session03/slicing.py b/students/kbindhu/session03/slicing.py new file mode 100644 index 0000000..154462f --- /dev/null +++ b/students/kbindhu/session03/slicing.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +#Author Krishna Bindhu +#Date 1/26/2015 + +#creating a list +l=[ ] +for i in range(1,20): + l.append(i) +print("Input List") +print (l) + + +#Swap function for exchanging last and first value +def Swap(a): + a[0],a[-1]=a[-1],a[0] + return a + #Function call +print("Swapped List") +print(Swap(l)) + +#Had to create list again as older lsit get rewritten every time with return value +l=[ ] +for i in range(1,20): + l.append(i) +print("Input List") +print (l) + +# below function removes every other item from list +def ItemRemoved(a): + return a[0:-1:2] +print("sequence with every other item removed") +print (ItemRemoved(l)) + + +l=[ ] +for i in range(1,20): + l.append(i) +print("Input List") +print (l) + +#Below function removes last 4 items from list and every other item +def LastFourRemoved(l): + a=l[0:-4:2] + return(a) +print("sequence with the first and last 4 items removedand every other item in between") +print(LastFourRemoved(l)) + +l=[ ] +for i in range(1,20): + l.append(i) +print("Input List") +print (l) + + +#function to reverse a string +def Reverse(l): + a=l[::-1] + return(a) +print("Sequence Reversed") +print(Reverse(l)) + +l=[ ] +for i in range(1,20): + l.append(i) +print("Input List") +print (l) + + +#Function to return a sequence with the middle third, then last third, then the first third in the new order +def EveryThird(l): + a=list() #Newlist + s=int(len(l)/3) #s has index for last element of first third + s1=int(len(l)*2/3) #s1 has index for last elemnet of second third + FirstThird=l[:s] #slice to print from index zero to s + MidThird=l[s:s1] #slice to print from index s to seconf third + LastThird=l[s1:] + a.extend(MidThird) + a.extend(LastThird) + a.extend(FirstThird) + return(a) +print("sequence with the middle third, then last third then the first third in the new order") +print (EveryThird(l)) diff --git a/students/kbindhu/session04/Mailroom.py b/students/kbindhu/session04/Mailroom.py new file mode 100644 index 0000000..5957049 --- /dev/null +++ b/students/kbindhu/session04/Mailroom.py @@ -0,0 +1,156 @@ +#!/usr/bin/python +#kbindhu +#Date created:1/20/2015 + + +#function to display menu +def MenuDisp(): + print("Main Menu") + print("1. Send a Thank you") + print("2. Create Report") + print("3.Exit") + + +#function for thank u card +def ThankYouCard(): + keep_going=True + while keep_going: + name=input('Please enter full name or type list to see full list of donors: ') + if(name.casefold()=='list'): + #call display function to display all donors + DonorNameDisp() + elif(name.casefold() not in don_dict): + #call function to add the name to dict + AddDonorToDict(name) + #call function for calculation of donation amount + Amount=DonationAmountReceive() + #add amout donated and number of donations to existing history + don_dict[name.lower()][0]=don_dict[name.lower()][0]+1 + don_dict[name.lower()][1]=don_dict[name.lower()][1]+Amount + keep_going = False + elif(name.casefold() in don_dict): + print("Hello {},Welcome Back".format(name.capitalize())) + #call function for prompt a donation amount + Amount=DonationAmountReceive() + #add amout donated and number of donations to existing history + don_dict[name.lower()][0]=don_dict[name.lower()][0]+1 + don_dict[name.lower()][1]=don_dict[name.lower()][1]+Amount + keep_going=False + else: + print("Invalid option ....Try again") + ThankEmail(name) + return don_dict + + +#thanku email generation +def ThankEmail(name): + print('') + print("Email to Donor") + print("From:kbindhu@example.com") + print("To:{}@example.com".format(name)) + print("Subject:Donation") + print("Hi {},".format(name.capitalize())) + print('{:>50}'.format('Thank for your donation at example charity.')) + print('{:<30}'.format('Regards')) + print('{:<30}'.format('krishna Bindhu')) + print('') + + + + +#function which print donor names as a list +def DonorNameDisp(): + for key in don_dict.keys(): + print(key.capitalize()) + +#function to add new donors to dictionary +def AddDonorToDict(name): + name = name.lower() + don_dict.setdefault(name, []).append(0) + don_dict.setdefault(name, []).append(0) + +#function to prompt for a donation amount +def DonationAmountReceive(): + while True: + donationAmount=input('Enter amount for donation: ') + #checking validity of amount enetered + try: + donationAmount=float(donationAmount) + break + except ValueError: + print("Input must be integer,try again") + return donationAmount + + +def CreateReport(don_dict): + # writing keys and values of dictionary to list which can be easy to sort + don_dict_list=[] + for k in don_dict.keys(): + Num_of_donations=don_dict[k][0] + Amt_of_don=don_dict[k][1] + #calculating average + Avg=don_dict[k][1]/don_dict[k][0] + don_dict_list.append([k.capitalize(),Num_of_donations,Amt_of_don,Avg]) + +#sorting the list using amout donated using itemgetter + from operator import itemgetter + sorted_don_dict_list= sorted(don_dict_list,key=itemgetter(2)) + +#printing to a table + + from tabulate import tabulate + print("") + print (tabulate(sorted_don_dict_list,headers=["DonorName","Number of Donations","Amount Donated(dollars)","Average"])) + print('') + + + +#main function +if __name__ == "__main__": + keep_going = True + #creating a dictionary + don_dict=dict() + #populating dictionary with no of donations and donors names + don_dict.setdefault('adam', []).append(5) + don_dict.setdefault('bob', []).append(3) + don_dict.setdefault('cathy', []).append(4) + don_dict.setdefault('andy', []).append(1) + don_dict.setdefault('phil', []).append(2) + #populating dictionary with amount of donations + don_dict.setdefault('adam', []).append(100) + don_dict.setdefault('bob', []).append(400) + don_dict.setdefault('cathy', []).append(20) + don_dict.setdefault('andy', []).append(10) + don_dict.setdefault('phil', []).append(250) + MenuDisp() + +#Main Program + while True: + menu= input('Enter 1 for option1 , 2 for option2 or 3 for option3: ') + if(menu=='1'): + #call thank u function + don_dict_new=ThankYouCard() + don_dict=don_dict_new + MenuDisp() + elif(menu=='2'): + #call create report function + CreateReport(don_dict) + MenuDisp() + elif(menu=='3'): + from sys import exit + exit() + else: + print("Wrong option selected") + + + + + + + + + + + + + diff --git a/students/kbindhu/session05/file_path.py b/students/kbindhu/session05/file_path.py new file mode 100644 index 0000000..b76d871 --- /dev/null +++ b/students/kbindhu/session05/file_path.py @@ -0,0 +1,21 @@ +#!/usr/bin/python +#kbindhu +#Date created:2/10/2015 + +import os +print("-"*80) +print("Print all abs path of all files in a given directory") +print("-"*80) +for root, dirs, files in os.walk('.'): + for file in files: + p=os.path.join(root,file) + print (os.path.abspath(p)) + +"""a program which copies a file from a source, to a destination line by line using file""" +f=open('src.txt','r') +f1=open('dest.txt','w') +for line in f.readline(): + f1.write(line) +f1.close() +f.close() + diff --git a/students/kbindhu/session06/color.py b/students/kbindhu/session06/color.py new file mode 100644 index 0000000..fe598e7 --- /dev/null +++ b/students/kbindhu/session06/color.py @@ -0,0 +1,13 @@ +def color(fore_color='red',back_color='white',link_color='blue',visited_color='yellow',**kwargs): + print("Fore_color is: {}".format(fore_color)) + print("back_color is: {}".format(back_color)) + print("link_color is: {}".format(link_color)) + print("visited_color is: {}".format(visited_color)) + print("The keyword arguments are :",kwargs) + +""" print the colors""" +color() +"""Call with a couple different parameters set""" +color('orange','grey') +"""pull out Have it pull the parameters out with *args, **kwargs """ +color(other_color='navy') \ No newline at end of file diff --git a/students/kbindhu/session06/test_scoring.py b/students/kbindhu/session06/test_scoring.py new file mode 100644 index 0000000..f30263f --- /dev/null +++ b/students/kbindhu/session06/test_scoring.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +from weapon import score +from weapon import hand_weapon +from weapon import gun +from weapon import flower_power + + + +#TESTS +def test_scoring(): + assert score(hand_weapon, 'small') == 1 + assert score(hand_weapon, 'medium') == 2 + assert score(hand_weapon, 'large') == 3 + assert score(gun, 'small') == 5 + assert score(gun, 'medium') == 8 + assert score(gun, 'large') == 13 + assert score(flower_power, 'small') == 21 + assert score(flower_power, 'medium') == 34 + assert score(flower_power, 'large') == 55 diff --git a/students/kbindhu/session06/test_trapezoidal.py b/students/kbindhu/session06/test_trapezoidal.py new file mode 100644 index 0000000..7a88ead --- /dev/null +++ b/students/kbindhu/session06/test_trapezoidal.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +from trapezoidal import trapz +import math as mt + +#definition of function to be passed to trapezoidal function +def line(x): + return 5 +def slopedLine(x,m=0,B=0): + return m*x+B +def quadratic(x,A=0,B=0,C=0): + return A*x**2+B*x+C +def sine(x,A=0,w=0,t=0): + return A*(mt.sin(w*t)) + + +#calculate area of different curves uisng actual formula +def val_line_func(m=0,B=0,a=0,b=0): + area = .5*m*(b**2-a**2)+B*(b-a) + return area +def val_sloped_line_func(m=0,B=0,a=0,b=0): + area = .5*m*(b**2-a**2)+B*(b-a) + return area +def quadratic_func(A=0,B=0,C=0,a=0,b=0): + area=.33*A*(b*b*b-a*a*a)+.5*B*(b**2-a**2)+C*(b-a) + return area +def sin_func(A=0,w=0,t=0,a=0,b=0): + area=A*(mt.cos(w*a)-mt.cos(w*b))*.33 + return area + +#TESTS +def test_line(): + area1 =trapz(line,0,100) + area2=val_line_func(B=5,a=0,b=100) + t=isclose(area1,area2) + print (t) + +def test_slopedline(): + area1=trapz(slopedLine,0,100,m=2,B=2) + area2=val_sloped_line_func(m=2,B=2,a=0,b=100) + t=isclose(area1,area2) + print (t) + +def test_quadratic(): + area1=trapz(quadratic,0,100,A=1,B=1,C=2) + area2=quadratic_func(A=1,B=1,C=2,a=0,b=100) + t=isclose(area1,area2) + print (t) + +def test_sine(): + area1=trapz(sine,0,100,A=2,w=1,t=1) + area2=sin_func(A=2,w=1,t=1,a=0,b=100) + t=isclose(area1,area2) + print (t) + +def isclose(area1,area2): + if (abs(area2-area1)<1e-2): + return True diff --git a/students/kbindhu/session06/trapezoidal.py b/students/kbindhu/session06/trapezoidal.py new file mode 100644 index 0000000..3826a31 --- /dev/null +++ b/students/kbindhu/session06/trapezoidal.py @@ -0,0 +1,26 @@ +#define trapez function + +"""Compute the area under the curve defined by +y = fun(x), for x between a and b + +:param fun: the function to evaluate +:type fun: a function that takes a single parameter + +:param a: the start point for teh integration +:type a: a numeric value + +:param b: the end point for the integration +:type b: a numeric value""" + +def trapz(func,a,b,**kwargs): + N=100 + sum=0 + for i in range (1,N): + i=i/10 + sum = sum+func(a+i*(b-a)/N,**kwargs) + midpoint=(func(a,**kwargs)+func(b,**kwargs))/2 + area=(b-a)/N*(midpoint+sum) + return area + + + diff --git a/students/kbindhu/session06/weapon.py b/students/kbindhu/session06/weapon.py new file mode 100644 index 0000000..c744117 --- /dev/null +++ b/students/kbindhu/session06/weapon.py @@ -0,0 +1,37 @@ +def score(weapon_type,weaponsize): + score_val=weapon_type(weaponsize) + return score_val + + +"""hand weapon""" +def hand_weapon(weapon_size): + if(weapon_size.casefold()=='small'): + return 1 + elif(weapon_size.casefold()=='medium'): + return 2 + elif(weapon_size.casefold()=='large'): + return 3 + else: + print("invalid size") +"""gun function""" +def gun(weapon_size): + if(weapon_size.casefold()=='small'): + return 5 + elif(weapon_size.casefold()=='medium'): + return 8 + elif(weapon_size.casefold()=='large'): + return 13 + else: + print("invalid size") +"""flower_power function""" +def flower_power(weapon_size): + if(weapon_size.casefold()=='small'): + return 21 + elif(weapon_size.casefold()=='medium'): + return 34 + elif(weapon_size.casefold()=='large'): + return 55 + else: + print("invalid size") + + diff --git a/students/mike_newton/Lightning Talk/.ipynb_checkpoints/matplotlib Lightning Talk -- 09 March 2016-checkpoint.ipynb b/students/mike_newton/Lightning Talk/.ipynb_checkpoints/matplotlib Lightning Talk -- 09 March 2016-checkpoint.ipynb new file mode 100644 index 0000000..b52cbb8 --- /dev/null +++ b/students/mike_newton/Lightning Talk/.ipynb_checkpoints/matplotlib Lightning Talk -- 09 March 2016-checkpoint.ipynb @@ -0,0 +1,105 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = np.random.rand(15,1)\n", + "y = np.random.rand(15,1)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "plt.scatter(x,y)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = np.arange(0,2*np.pi,0.001)\n", + "y = np.sin(x)\n", + "plt.plot(x,y)\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/mike_newton/Lightning Talk/matplotlib Lightning Talk -- 09 March 2016.ipynb b/students/mike_newton/Lightning Talk/matplotlib Lightning Talk -- 09 March 2016.ipynb new file mode 100644 index 0000000..b52cbb8 --- /dev/null +++ b/students/mike_newton/Lightning Talk/matplotlib Lightning Talk -- 09 March 2016.ipynb @@ -0,0 +1,105 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = np.random.rand(15,1)\n", + "y = np.random.rand(15,1)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "plt.scatter(x,y)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = np.arange(0,2*np.pi,0.001)\n", + "y = np.sin(x)\n", + "plt.plot(x,y)\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/students/mike_newton/Lightning Talk/matplotlib lightning talk ipython notebook link.txt b/students/mike_newton/Lightning Talk/matplotlib lightning talk ipython notebook link.txt new file mode 100644 index 0000000..677937d --- /dev/null +++ b/students/mike_newton/Lightning Talk/matplotlib lightning talk ipython notebook link.txt @@ -0,0 +1 @@ +http://localhost:8888/notebooks/IntroPython2016a/students/mike_newton/Lightning%20Talk/matplotlib%20Lightning%20Talk%20--%2009%20March%202016.ipynb \ No newline at end of file diff --git a/students/mike_newton/Lightning Talk/matplotlib_lightning_talk.mp4 b/students/mike_newton/Lightning Talk/matplotlib_lightning_talk.mp4 new file mode 100644 index 0000000..83fe776 Binary files /dev/null and b/students/mike_newton/Lightning Talk/matplotlib_lightning_talk.mp4 differ diff --git a/students/mike_newton/Lightning Talk/matplotlib_lightning_talk.pptm b/students/mike_newton/Lightning Talk/matplotlib_lightning_talk.pptm new file mode 100644 index 0000000..8b00d6b Binary files /dev/null and b/students/mike_newton/Lightning Talk/matplotlib_lightning_talk.pptm differ diff --git a/students/mike_newton/Mailroom/mailroom.py b/students/mike_newton/Mailroom/mailroom.py new file mode 100644 index 0000000..dbe0eff --- /dev/null +++ b/students/mike_newton/Mailroom/mailroom.py @@ -0,0 +1,209 @@ +'''______________________________________________________ +Mike Newton +newton33@uw.edu +Intro To Python 100A +University of Washington, Winter 2016 +Last Updated: 02 February 2016 +Python Version 3.5.1 + +Mailroom Exercise +http://uwpce-pythoncert.github.io/IntroPython2016a/exercises/mailroom.html + +______________________________________________________''' + + +#------------ Introduction ------------------- +#Explain to the user what the script will accomplish +print("This script will read in a file containing data describing the frequency and amount of donations provided" + " by specific individuals. If the file does not exist, you will be prompted to enter donor information in'" + " order to create the list. You will then be allowed to edit this data or send a Thank You email to '" + "each donor.\n\n" "You may type the word 'quit' at any time to exit the program.\n") + + +#-------------- Get Data ------------------------ +#define a function to read the To Do list +#@staticmethod +def read_Donations(file): + donation_data = [] #initialize a list of dictionaries + raw_donor_data = [] + #loop through DonorList.txt and places the data into dictionaries + for line in file: + #read in the raw data from the file + raw_donor_data.append([(line.strip().split(",")[0]), float((line.strip().split(",")[1]))]) + + #now form the key-value pairs in raw_donor_data into a dictionary of lists + #I'll try the defaultdict subclass in the collections module. I've never tried that before. + from collections import defaultdict + donation_data = defaultdict(list) + for k, v in raw_donor_data: + donation_data[k].append(v) + + return donation_data + +#-------------- Process Data ------------------------ +#define a function that will accept the donor data and determine the following values +#1. number of donations made +#2. total amount of donations +#3. average donation amount +def do_math(data): + donor_math = {} + for k, v in data.items(): + # v is the list of donations for each donor (k) + total = sum(v) + num = len(v) + avg = total/num + donor_math[k] = num, total, avg + + return donor_math + +#-------------- Present Data ------------------------ +#create a function that will format data and display it in a pleasing fashion +def display_donor_data(data): + + #in order to make the user diplay more visually appealing, we need to figure out + # the max lengths in each 'column' + name_len = [] + num_len = [] + total_len = [] + avg_len = [] + + #loop through key/value pairs to determine max length in each field + for k, v in data.items(): + + name_len.append(len(k)) + num_len.append(len(str(v[0]))) + total_len.append(len(str(v[1]))) + avg_len.append(len(str(v[2]))) + + #now determine if data field lengths are greater than the header lengths. whichever length is greater will be + #our column widths. there must be a more elegant way of doing this but it works for now. + # any advice would be appreciated. + if max(name_len) > len("Donor Name"): + name_col_width = max(name_len) + else: name_col_width = len("Donor Name") + if max(num_len) > len("Number of Donations"): + num_col_width = max(num_len) + else: num_col_width = len("Number of Donations") + if max(total_len) > len("Total Donations($)"): + total_col_width = max(total_len) + else: total_col_width = len("Total Donations($)") + if max(avg_len) > len("Average Donation"): + avg_col_width = max(avg_len) + else: avg_col_width = len("Average Donation") + + #in order to use the python .format method to format the string. + # this took me a while to truly figure out. + header_format_string = "{0:^" + str(name_col_width+5) + "s} {1:^" + str(num_col_width+5) + "s}" \ + " {2:^" + str(total_col_width+5) + "s} {3:^" + str(avg_col_width+5) + "s}" + data_format_string = "{0:^" + str(name_col_width+5) + "s} {1:^" + str(num_col_width+5) + "s} " \ + "{2:^" + str(total_col_width+5) + "s} {3:^" + str(avg_col_width+5) + "s}" + + + #first display some headers so the data doesn't look like random words and numbers + print(header_format_string.format("Donor Name", "Number of Donations", "Total Donations($)", "Average Donation")) + print(header_format_string.format("----------", "-------------------", "------------------", "----------------")) + + #data should be sorted by total donation amount. dictionaries aren't ordered so a different approach is needed. + #we'll need a list representation of our data. a list of tuples, i believe is how this works out. + sorted_data = sorted(data.items(), key=lambda v: v[1][1], reverse = True) + + #loop through data to print to terminal. it's probably better to format the data in a different fashion prior this + #point but here we are. + for i, f in enumerate(sorted_data): + print(data_format_string.format(sorted_data[i][0], str(sorted_data[i][1][0]), str(sorted_data[i][1][1]), str(sorted_data[i][1][2]))) + + +def display_donor_list(data): + #this function will display a list donor names to the user + + #in order to make the user diplay more visually appealing, we need to figure out + # the max lengths in each 'column' + name_len = [] + #loop through key/value pairs to determine max length in each field + for k, v in data.items(): + name_len.append(len(k)) + + if max(name_len) > len("Donor Name"): + name_col_width = max(name_len) + else: name_col_width = len("Donor Name") + + #in order to use the python .format method to format the string. + # this took me a while to truly figure out. + header_format_string = "{0:^" + str(name_col_width+5) + "s}" + data_format_string = "{0:^" + str(name_col_width+5) + "s}" + + #first display some headers so the data doesn't look like random words and numbers + print(header_format_string.format("Donor Name")) + print(header_format_string.format("----------")) + + #now display the donor names + for k in data: + print(data_format_string.format(k)) + +def add_to_donor_data(data, name, donation): + #create a function add a new donor to the list or add a new donation for an existing donor + if name in data: + data[name].append(donation) + else: + data[name] = donation + + return data + +def send_thanks_option(data): + #create a function which will add new donors/donations to the data and send a thank you email + print("You've chosen to enter a new donation and send a 'Thank You' email.\n") + #user may now enter the name or donor or type 'list' to see a list of previous donors + while True: + user_name_input = input("Enter the name of the donor or type 'list' to see a list of previous donors.\n") + if user_name_input.lower() == "list": + display_donor_list(data) + else: + break + + #now user should enter a donation amount. if the input isn't a number, an exception will be raised + while True: + try: + donation_amt = float(input("How much did " + user_name_input + " donate?\n")) + break + except ValueError: + print("I don't think that was a dollar amount. Try again.") + #add this new donation to the donor data + data = add_to_donor_data(data, user_name_input, donation_amt) + + print(data) + + +#-------------- Main User Interactions ------------------------ +if __name__ == '__main__': + + #------------ Open/Create The Current Donor List ------------------- + #open the Donations.txt file which resides int he same folder on the C: drive as this script + save_dir = "C:\Python Certificate\Python_100A\Mailroom" + print("Retrieving file from " + save_dir + " directory\n") + # open/create the Donations.txt file in the given directory + file = open(save_dir + "\Donations.txt", 'r+') + + #----------interact with user and do stuff with data---------- + #read donations file before doing anything + donor_data = read_Donations(file) + + #now ask the user what to do. the options are to enter a donation and send a thank you email + #or generate a report of historical donations + + option = input("Greetings! What would you like to do?\n" + "[1] Enter a new donation amount and send a 'Thank You' email?\n" + "[2] Generate a historical report of donations\n" + "Type 1 or 2 and press enter for one of the options above or type quit to exit.\n") + + #if option == 1: + + + #donor_math = do_math(donor_data) + #display_donor_data(donor_math) + #display_donor_list(donor_data) + + + #donor_data = add_to_donor_data(donor_data, user_name_input, donation_amt) + send_thanks_option(donor_data) + print(donor_data) + file.close() \ No newline at end of file diff --git a/students/mike_newton/Module2/FizzBuzz.py b/students/mike_newton/Module2/FizzBuzz.py new file mode 100644 index 0000000..128d0b3 --- /dev/null +++ b/students/mike_newton/Module2/FizzBuzz.py @@ -0,0 +1,41 @@ +'''______________________________________________________ +Mike Newton +newton33@uw.edu +Intro To Python 100A +University of Washington, Winter 2016 +Last Updated: 18 January 2016 +Python Version 3.5.1 + +FizzBuzz +Write a function to print out the numbers from 1 to n, +but replace numbers divisible by 3 with "Fizz", numbers divisible +by 5 with "Buzz". Numbers divisible by both factors should display "FizzBuzz. + +The function should be named FizzBuzz and be able to accept a natural +number as argument. +______________________________________________________''' + +#Explain to the user what the script will accomplish +print("This script will accept a user defined natural number and count to that" + "number starting at 1. If the number is divisible by 3 'Fizz' will be displayed." + "If the number is divisble by 5, 'Buzz' will be displayed. If the number by both 3 and 5," + "'FizzBuzz' will be displayed\n") + +#Ask user to input an integer +while True: + try: + N = int(input("Please enter an integer value of N that you would like to count to: ")) + break + #If user doesn't input an integer value, prompt them to try again + except ValueError: + print("That wasn't an integer! Try again...") # what if I just press Enter without entering anything? + +for i in range(1,N+1): + if i % 5 == 0 and i % 3 == 0: + print("FizzBuzz") + elif i % 5 == 0: + print("Fizz") + elif i % 3 == 0: + print("Buzz") + else: + print(i) diff --git a/students/mike_newton/README.rst b/students/mike_newton/README.rst new file mode 100644 index 0000000..7d34ea1 --- /dev/null +++ b/students/mike_newton/README.rst @@ -0,0 +1,2 @@ +# Python code for UWPCE-PythonCert class +#Python code for UWPCE-PythonCERT class diff --git a/students/mike_newton/Trapezoidal_Integrator/trapz.py b/students/mike_newton/Trapezoidal_Integrator/trapz.py new file mode 100644 index 0000000..37b66ff --- /dev/null +++ b/students/mike_newton/Trapezoidal_Integrator/trapz.py @@ -0,0 +1,38 @@ +import math + +#trapz will be passed the function name, a dictionary of arguments/coefficients required for that function, +#a starting point (a) and a stopping point (b). if no arguments or coefficients are requirements, +#the user will simply pass the word None in the args place when calling trapz. + +#each individual function will be responsible for unpacking and using the arguments passed to it from trapz + +def trapz(funct, args, a, b): + N = 100 #number of steps + step = (b-a)/N #step size + + y = [] #initialize a list of values of y + + for i in range(1,N-1) #loop through values of x while omitting the first and last points + + x = a + (step * i) #each subsequent x value will be increased by the step size + + y.append(funct(x,args)) # call the desired function and pass it the required arguments and x value + + mid = math.fsum(y) #sum the values of y + + area = step * ((funct(b,args) - funct(a,args))/2 + mid) #find the area under the curve with the trapezoid + #rule for numerical itnegration + + return area #return the value of area back to the calling function + + + +def squared(x,args) + y = x**2 + return y + +def quadratic(x, args) + y = args['A']*x**2 + args['B']*x + args['C'] + return y + +make args a dictionary. user must know what args are required for the function being called diff --git a/students/pradeep/fizzbuzz.py b/students/pradeep/fizzbuzz.py index d190b94..2f51d6e 100755 --- a/students/pradeep/fizzbuzz.py +++ b/students/pradeep/fizzbuzz.py @@ -1,6 +1,6 @@ #!/usr/bin/python import sys -def FizzBuzz(n): +def FizzBuzz(n): #great job! for i in range(1,n+1): if i%3 == 0 and i%5 ==0: print "FizBuzz" @@ -11,7 +11,7 @@ def FizzBuzz(n): else: print i -if __name__ == "__main__": +if __name__ == "__main__": if(len(sys.argv) != 2) : print "Please enter one and only one number as parameter" exit() diff --git a/students/robert/README.rst b/students/robert/README.rst new file mode 100644 index 0000000..47d8a6e --- /dev/null +++ b/students/robert/README.rst @@ -0,0 +1 @@ +# Python code for UWPCE-PythonCert class diff --git a/students/robert/Session 2/FizzBuzz.py b/students/robert/Session 2/FizzBuzz.py new file mode 100644 index 0000000..9d37032 --- /dev/null +++ b/students/robert/Session 2/FizzBuzz.py @@ -0,0 +1,10 @@ +def FizzBuzz(n): + for i in range(1,n+1): + if i % 3 == 0 and i % 5 == 0: + print ("FizzBuzz") + elif i % 3 == 0: + print ("Fizz") + elif i % 5 == 0: + print ("Buzz") + else: + print (i) diff --git a/students/robert/Session 2/OneDollarGame.py b/students/robert/Session 2/OneDollarGame.py new file mode 100644 index 0000000..e96a969 --- /dev/null +++ b/students/robert/Session 2/OneDollarGame.py @@ -0,0 +1,12 @@ +def OneDollarGame(): + p = int(input("Enter # of pennies: ")) + n = int(input("Enter # of nickels: ")) + d = int(input("Enter # of dimes: ")) + q = int(input("Enter # of quarters: ")) + total = p + 5 * n + 10 * d + 25 * q + if total == 100: + print ("Congrats, you won 'One Dollar' Game!") + elif total > 100: + print ("Sorry it's more than a Dollar") + else: + print ("Sorry it's less than a dollar") diff --git a/students/robert/Session 4/mailroom.py b/students/robert/Session 4/mailroom.py new file mode 100644 index 0000000..3bb5e3b --- /dev/null +++ b/students/robert/Session 4/mailroom.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python + +def main_command(): + while True: + user_choice = input("Type 1 for Send a Thank You; Type 2 for Create Report: Type 3 to quit: ->") + try: + user_choice = int(user_choice) + if user_choice not in [1, 2, 3]: + print("Invalid selection. Please try again.") + else: + break + except: + print("Invalid selection. Please try again.") + finally: + pass + return user_choice + + + +def donor_name(): + for i in dln.keys(): + print(i) + +def Sending_a_Thank_You(): + prompt = True + while prompt: + full_name = input("Full Name: |'list'| ->") + if full_name == 'list': + donor_name() + prompt = True + elif full_name == 'main': + break + elif full_name in dln.keys(): + prompt = False + else: + dln[full_name] = [] + prompt = False + promptN = True + while promptN: + donation = input("Donation Amount: ->") + try: + val = int(donation) + except ValueError: + promptN == True + continue + else: + break + dln[full_name] += [int(donation)] + print ("Thank you, {name}, for your generous donation of {amount}".format(name = full_name, amount = int(donation))) + +def getKey(item): + return item[1] + +def Creating_a_Report(): + list = [] + for k,v in dln.items(): + list += [[k,sum(v),len(v),sum(v)/len(v)]] + listN = sorted(list,key=getKey) + for x in listN: + print ("{DN} {TD} {ND} {ADA}".format(DN = x[0], TD = x[1], ND = x[2], ADA = x[3])) + + +if __name__ == "__main__": + +#Create a list with 5 donors and info + dln = {'donor1':[10],'donor2':[20,30],'donor3':[40],'donor4':[50,60,70],'donor5':[80]} + + while True: + choice = main_command() + if choice in [1]: + Sending_a_Thank_You() + elif choice in [2]: + Creating_a_Report() + else: + break + + diff --git a/students/robert/Session 5/Paths and File Processing.py b/students/robert/Session 5/Paths and File Processing.py new file mode 100644 index 0000000..70aad3b --- /dev/null +++ b/students/robert/Session 5/Paths and File Processing.py @@ -0,0 +1,25 @@ +#!/usr/bin/python + + +#Find and print file locations +import pathlib +pth = pathlib.Path('./') +abpth = pth.absolute() +for fn in pth.iterdir(): + print(str(abpth) + '\\' + str(fn)) + +# Copy file to designated location +file_name = input ('file_name with file type: ') +#'classinfo.txt' +out_loc = input('Copy location (/): ') +#'/Python Class/Copied Files/' +with open(file_name, 'r') as f: + read_data = f.read() + f.closed +#'/Python Class/Copied Files/classinfo_copy.txt' + out_file = out_loc + "/" + file_name + with open(out_file, 'w') as f1: + for line in read_data: + f1.write(line) + + diff --git a/students/robert/Session 6/Lab_Keyword_Argument.py b/students/robert/Session 6/Lab_Keyword_Argument.py new file mode 100644 index 0000000..a4efda7 --- /dev/null +++ b/students/robert/Session 6/Lab_Keyword_Argument.py @@ -0,0 +1,32 @@ +HW +""" +Write a function that has four optional parameters (with defaults): +fore_color +back_color +link_color +visited_color +Have it print the colors (use strings for the colors) +Call it with a couple different parameters set +Have it pull the parameters out with *args, **kwargs - and print those +""" + +#function to print colors +def print_color(fore_color = 'Blue', back_color = 'Green', link_color = 'Grey', visited_color = 'Black'): + print(fore_color,back_color,link_color,visited_color) + +#Test +print_color('red','yellow',visited_color = 'purple',link_color = 'orange') + +#function to pass it with args and print +def print_color(args): + print ("{} {} {} {}".format(*args)) + +args = ['red','yellow','orange','purple'] +print_color(args) + +#function to pass it with kwargs and print +def print_color(kwargs): + print ("{fore_color} {back_color} {link_color} {visited_color}".format(**kwargs)) + +kwargs = {'fore_color':'red','back_color':'yellow','link_color':'orange','visited_color':'purple'} +print_color(kwargs) \ No newline at end of file diff --git a/students/robert/Session 6/Trapezoidal_Rule.py b/students/robert/Session 6/Trapezoidal_Rule.py new file mode 100644 index 0000000..35b99b8 --- /dev/null +++ b/students/robert/Session 6/Trapezoidal_Rule.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +#import math + +""" +def line(x): + function = 2*x + 5 + return function + +def line(x,A,w) + function = A*math.sin(w*x) + return function +""" + +def quadratic(x, A=0, B=0, C=0): + return A * x**2 + B * x + C + +def trapz(quadratic,a,b,n,A,B,C): +#def trapz(line,a,b): + """ + Compute the area under the curve defined by + y = fun(x), for x between a and b + + :param fun: the function to evaluate + :type fun: a function that takes a single parameter + + :param a: the start point for teh integration + :type a: a numeric value + + :param b: the end point for the integration + :type b: a numeric value + """ + f1 = 0 + for i in range(n-1): + f1 += quadratic(a+ (b-a)/n*(i + 1),A,B,C) +# f1 += line(a+ (b-a)/100*(i + 1)) + area = (b-a)/n*((quadratic(a,A,B,C)+quadratic(b,A,B,C))/2+f1) +# area = (b-a)/100*((line(a)+line(b))/2+f1) + return area +# pass + +""" + area = (b-a)*line + return area + line = line() + +""" +coef = {'A':1,'B':3,'C':2} +area = trapz(quadratic,0,10,1000000,**coef) +#area = trapz(line,0,10) + +print(area) + + diff --git a/students/robert/Session 6/Trapz_Test.py b/students/robert/Session 6/Trapz_Test.py new file mode 100644 index 0000000..376c720 --- /dev/null +++ b/students/robert/Session 6/Trapz_Test.py @@ -0,0 +1,9 @@ +#from Trapezoidal_Rule_N import quadratic +#from Trapezoidal_Rule_N import trapz +from Trapezoidal_Rule import quadratic +from Trapezoidal_Rule import trapz + +import math + +def test_1(): + assert math.isclose(int(trapz(quadratic,0,10,1000000,1,3,2)), int((1/3)*(10**3)+(3/2)*(10**2)+2*10),rel_tol=1e-9, abs_tol=0.0) is True diff --git a/students/robert/Session 6/cigar_party.py b/students/robert/Session 6/cigar_party.py new file mode 100644 index 0000000..61e1035 --- /dev/null +++ b/students/robert/Session 6/cigar_party.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. +Return True if the party with the given values is successful, +or False otherwise. +""" + +def cigar_party(c,w): + if w: + return True + else: + if c >=40 and c <=60: + return True + else: + return False diff --git a/students/robert/Session 6/test_cigar_party.py b/students/robert/Session 6/test_cigar_party.py new file mode 100644 index 0000000..dab9cb1 --- /dev/null +++ b/students/robert/Session 6/test_cigar_party.py @@ -0,0 +1,48 @@ +# you can change this import to test different versions +from cigar_party import cigar_party +# from cigar_party import cigar_party2 as cigar_party +# from cigar_party import cigar_party3 as cigar_party + + +def test_1(): + assert cigar_party(30, False) is False + + +def test_2(): + assert cigar_party(50, False) is True + + +def test_3(): + assert cigar_party(70, True) is True + + +def test_4(): + assert cigar_party(30, True) is True + + +def test_5(): + assert cigar_party(50, True) is True + + +def test_6(): + assert cigar_party(60, False) is True + + +def test_7(): + assert cigar_party(61, False) is False + + +def test_8(): + assert cigar_party(40, False) is True + + +def test_9(): + assert cigar_party(39, False) is False + + +def test_10(): + assert cigar_party(40, True) is True + + +def test_11(): + assert cigar_party(39, True) is True diff --git a/students/robert/Session 7/html_render.py b/students/robert/Session 7/html_render.py new file mode 100644 index 0000000..37c93c0 --- /dev/null +++ b/students/robert/Session 7/html_render.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python + +#import io + +class Element(object): +# tag_indent = {'html':0,'head':4,'meta':8,'title':8,'body':4,'h2':8,'p':8,'hr':8,'ul':8,'li':12} + tag = 'html' + indent = ' ' +# content =[] + + def __init__ (self,content=None,**attributes): + self.cont = [] + self.attributes = attributes + if content is not None: + self.cont.append(content) + + def content_add(self,content): + self.cont.append(content) + + def render_tag(self,current_ind): + attrs = "".join([' {} ="{}"'.format(key,val) for key, val in self.attributes.items()]) + tag_str = "{}<{}{}>".format(current_ind, self.tag, attrs) + return tag_str + + def render(self, file_out,ind = ""): + file_out.write(self.render_tag(current_ind)) + file_out.write('\n') + for con in self.content: + try: + file_out.write(current_ind +self.indent+con+'\n') + except TypeError: + con.render(file_out, current_ind+self.indent) + file_out.write("{}\n".format(current_ind, self.tag)) + +class Html(Element): + def __init__ (self,content=None,**attributes): + self.tag = 'html' + + def render(self, file_out,ind = ""): + file_out.write('') + super(Html,self).render(self, file_out,ind = "") + + +class Body(Element): + def __init__ (self,content=None,**attributes): + self.tag = 'body' + +class P(Element): + def __init__ (self,content=None,**attributes): + self.tag = 'p' + +class Head(Element): + def __init__ (self,content=None,**attributes): + self.tag = 'head' + +class OneLineTag(Element): + def render(self, file_out,ind = ""): + self.render_tag(current_ind) + file_out.write('<{}>{}'.format(self.tag,current_ind)) + try: + file_out.write(current_ind +self.indent+self.content) + except TypeError: + con.render(file_out, current_ind+self.indent) + file_out.write("{}\n".format(current_ind, self.tag)) + +class Title(OneLineTag): + def __init__ (self,content=None,**attributes): + self.tag = 'title' + +class SelfClosingTag(Element): + + def render(self, file_out,ind = ""): + self.render_tag(current_ind) + file_out.write('<{}{}/>\n'.format(self.tag,current_ind)) + +class meta(SelfClosingTag): + def render(self, file_out,ind = ""): + self.render_tag(current_ind) + file_out.write('<{}{}'.format('meta',current_ind)) + try: + file_out.write(current_ind +self.indent+self.content) + except TypeError: + con.render(file_out, current_ind+self.indent) + file_out.write("{}/>\n".format(current_ind)) + +class Hr(SelfClosingTag): + def __init__ (self,content=None,**attributes): + self.tag = 'hr' + + +class Br(SelfClosingTag): + def __init__ (self,content=None,**attributes): + self.tag = 'br' + +class A(Element): + def A__init__ (self,link,content=None): + super(A, self).__init__(content=None,href=link) + +class Ul(Element): + def __init__ (sself,content=None,**attributes): + self.tag = 'ul' + + +class Li(Element): + def __init__ (self,content=None,**attributes): + self.tag = 'li' + +class Header(OneLineTag): + def __init__(self,hl,content=None): + self.tag = 'h' + hl + super(Header,self).__init__(content=None,**attributes) + + diff --git a/students/robert/Test.rst b/students/robert/Test.rst new file mode 100644 index 0000000..5848ec9 --- /dev/null +++ b/students/robert/Test.rst @@ -0,0 +1 @@ +Testing! diff --git a/students/robert/Test_Excel.xlsx b/students/robert/Test_Excel.xlsx new file mode 100644 index 0000000..a2bd30e Binary files /dev/null and b/students/robert/Test_Excel.xlsx differ diff --git a/students/susanRees/README.rst b/students/susanRees/README.rst new file mode 100644 index 0000000..239ec8d --- /dev/null +++ b/students/susanRees/README.rst @@ -0,0 +1 @@ +This is Susan's ReadMe file. \ No newline at end of file diff --git a/students/susanRees/session01/BreakMe.py b/students/susanRees/session01/BreakMe.py new file mode 100644 index 0000000..41a752f --- /dev/null +++ b/students/susanRees/session01/BreakMe.py @@ -0,0 +1,28 @@ +# write four simple Python functions: +# Each function, when called, should cause an exception to happen +# NameError, TypeError, SyntaxError, AttributeError + +# the interpreter will quit when it hits a Exception +# comment out all but the one you are testing at the moment +# Use Python standard library reference on Built In Exceptions +# https://docs.python.org/3/library/exceptions.html + +# NameError +def nameError(): + print (cats) +nameError() + +#TypeError +def typeError(): + print (1+"one") +typeError() + +#AttributeError +list.attributeError + +#SyntaxError +def syntaxError() + print (unicorns) +syntaxError() + + diff --git a/students/susanRees/session01/thinkPythonExercise3-3.py b/students/susanRees/session01/thinkPythonExercise3-3.py new file mode 100644 index 0000000..bb7254a --- /dev/null +++ b/students/susanRees/session01/thinkPythonExercise3-3.py @@ -0,0 +1,4 @@ +def right_justify(s): + print (' '*(70-len(s))+s) + +right_justify('allen') \ No newline at end of file diff --git a/students/susanRees/session01/thinkPythonExercise3-4.py b/students/susanRees/session01/thinkPythonExercise3-4.py new file mode 100644 index 0000000..4855af6 --- /dev/null +++ b/students/susanRees/session01/thinkPythonExercise3-4.py @@ -0,0 +1,17 @@ +def do_twice(f, g): + f(g) + f(g) + +def print_twice(g): + print(g) + print(g) + +do_twice(print_twice, 'spam') +print('') + +def do_four(f, g): + do_twice(f, g) + do_twice(f, g) + +do_four(print_twice, 'spam') +print('') \ No newline at end of file diff --git a/students/susanRees/session01/thinkPythonExercise3-5-1.py b/students/susanRees/session01/thinkPythonExercise3-5-1.py new file mode 100644 index 0000000..f8e46c8 --- /dev/null +++ b/students/susanRees/session01/thinkPythonExercise3-5-1.py @@ -0,0 +1,26 @@ +def do_twice(f): + f() + f() + +def do_four(f): + do_twice(f) + do_twice(f) + +def print_row(): + print ('+ - - - - + - - - - +'), + +def print_column(): + print ('| | |') + +def print_columns(): + do_four(print_column) + +def print_rows(): + print_row() + print_columns() + +def print_grid(): + do_twice(print_rows) + print_row() + +print_grid() \ No newline at end of file diff --git a/students/susanRees/session01/thinkPythonExercise3-5-2.py b/students/susanRees/session01/thinkPythonExercise3-5-2.py new file mode 100644 index 0000000..2ecba5d --- /dev/null +++ b/students/susanRees/session01/thinkPythonExercise3-5-2.py @@ -0,0 +1,26 @@ +def do_twice(f): + f() + f() + +def do_four(f): + do_twice(f) + do_twice(f) + +def print_row(): + print ('+ - - - - + - - - - + - - - - + - - - - +'), + +def print_column(): + print ('| | | | |') + +def print_columns(): + do_four(print_column) + +def print_rows(): + print_row() + print_columns() + +def print_grid(): + do_four(print_rows) + print_row() + +print_grid() \ No newline at end of file diff --git a/students/susanRees/session02/FizzBuzz.py b/students/susanRees/session02/FizzBuzz.py new file mode 100644 index 0000000..cb224e0 --- /dev/null +++ b/students/susanRees/session02/FizzBuzz.py @@ -0,0 +1,14 @@ +# Write a program that prints the numbers from 1 to 100 inclusive. +# for multiples of three print “Fizz” instead of number +# For multiples of five print “Buzz”. +# multiples of both three and five print “FizzBuzz” + +for i in range(1, 101): + if i % 3 == 0 and i % 5 == 0: + print('FizzBuzz') + elif i % 3 == 0: + print('Fizz') + elif i % 5 == 0: + print('Buzz') + else: + print(i) diff --git a/students/susanRees/session02/MoneyCounting.py b/students/susanRees/session02/MoneyCounting.py new file mode 100644 index 0000000..6a6fb9f --- /dev/null +++ b/students/susanRees/session02/MoneyCounting.py @@ -0,0 +1,31 @@ +# determine whether a mix of coins can make EXACTLY one dollar. +# prompt users to enter the number of pennies, nickels, dimes, and quarters +# If the total value of the coins entered is equal to one dollar, congrat users +# Else display a message saying if amount entered was more or less than dollar +print("Let's play a game where I don't tell you the rules. Doesn\'t that sound fun?") + +print("Please enter a number for pennies") +num_pennies = input() + +print("Please enter a number for nickels") +num_nickels = input() + +print("Please enter a number for dimes") +num_dimes = input() + +print("Please enter a number for quarters") +num_quarters = input() + +quarters = int(num_quarters) * 25 +dimes = int(num_dimes) * 10 +nickels = int(num_nickels) * 5 +pennies = int(num_pennies) * 1 + +change = (quarters + dimes + nickels + pennies) + +if (int(change) == 100): + print("Congratulations! The Price is Right! You win at life!") +elif (int(change) > 100): + print("You are a loser. Hint: You bid over the Right Price") +else: + print("You are a loser. Hint: You bid under the Right Price") diff --git a/students/susanRees/session02/PrintGrid.py b/students/susanRees/session02/PrintGrid.py new file mode 100644 index 0000000..f8c8fbe --- /dev/null +++ b/students/susanRees/session02/PrintGrid.py @@ -0,0 +1,43 @@ +def print_grid(n): + x = int(n/2) + def print_row(): + print('+', end=' '), + print('-' * x, end=' '), + print('+', end=' '), + print('-' * x, end=' '), + print('+') + def print_column(): + y = (x + 1) + i = (y - 1) + for i in range(0, i): + print('|', end=' '), + print(' ' * x, end=' '), + print('|', end=' '), + print(' ' * x, end=' '), + print('|') + print_row() + print_column() + print_row() + print_column() + print_row() + + +print_grid(10) + + +def second_grid(x, y): + n = (y-1) + for n in range(0, n): + def print_rows(): + print('+', end=' '), + print('-' * y, end=' '), + print_rows() + print('+') + def print_columns(): + print('|', end=' '), + print(' ' * y, end=' '), + print_columns() + print('|') + print_rows() + print('+') +second_grid(3, 4) diff --git a/students/susanRees/session02/series.py b/students/susanRees/session02/series.py new file mode 100644 index 0000000..1708d55 --- /dev/null +++ b/students/susanRees/session02/series.py @@ -0,0 +1,47 @@ +# add a function called fibonacci. +# The function should have one parameter n. +# The function should return the nth value in the fibonacci series. +# Ensure that your function has a well-formed docstring + +# Add a series of statements proving functions work +# Add comments about what tests are doing +# push your changes to GitHub and make a pull request + + +def fib(n): + """Iterate next number in Fibonacci series""" + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return fib(n - 1) + fib(n - 2) + + +def lucas(n): + """Iterate next number in Lucas series""" + if n == 0: + return 2 + elif n == 1: + return 1 + else: + return lucas(n - 1) + lucas(n - 2) + + +def sum_series(n, a=0, b=1): + """Run Fibonacci or Lucas function depending on optional parameters""" + if a == 0 and b == 1: + return fib(n) + elif a == 2 and b == 1: + return lucas(n) + else: + return None + +# test fib function +print(fib(5)) +# test lucas function +print(lucas(5)) +# test sum_series function running fib function +print(sum_series(5)) +# test sum_series function running lucas function +print(sum_series(5, 2, 1)) diff --git a/students/susanRees/session03/Lists.py b/students/susanRees/session03/Lists.py new file mode 100644 index 0000000..cd42047 --- /dev/null +++ b/students/susanRees/session03/Lists.py @@ -0,0 +1,110 @@ +# Create a list with “Apples”, “Pears”, “Oranges” and “Peaches” +a = "Apples" +b = "Pears" +c = "Oranges" +d = "Peaches" +fruits = [a, b, c, d] + +# Display the list. +print(fruits) + +# ask the user for new fruit and add it to end of the list. +print("Please type in a type of fruit") +e = input() +fruits.append(e) + +# Display the list. +print(fruits) + +# Ask the user for a number +print("Please type in a type number") +num = input() + +# display the number and that number's fruit (on a 1-is-first basis). +tada = fruits[int(num) - 1] +print(num, tada) + +# Add fruit to the beginning of the list using “+” +fruits2 = ["kiwi"] + fruits + +# display the list. +print(fruits2) + +# Add fruit to the beginning of the list using insert() +fruits2.insert(0, "pineapple") + +# display the list. +print(fruits2) + +# Display all the fruits that begin with “P”, using a for loop. +p_fruits = [] +for pfruit in fruits2: + if pfruit[0] == "p" or pfruit[0] == "P": + p_fruits.append(pfruit) +print(p_fruits) + +# Display the list. +print(fruits2) + +# Remove the last fruit from the list. +fruits2.pop(-1) + +# Display the list. +print(fruits2) + +# Ask the user for a fruit to delete +print(fruits2) +print("Please select a fruit from the list to delete. Your typed response should be case sensitive and match the listed item exactly.") +rotten_fruit = input() + +# find it and delete it. +shazaam = [] +for find_it in fruits2: + if find_it != rotten_fruit: + shazaam.append(find_it) +print(shazaam) + + +# (Bonus: Multiply the list times two. +# Keep asking until a match is found. +# Once found, delete all occurrences.) + + +# Ask user for input "Do you like apples?” +# for each fruit in the list (making the fruit all lowercase). +likes = [] +for opinions in fruits2: + print("Do you like " + opinions + "?") + yes_no = input() + str.lower(yes_no) + yes = "yes" + no = "no" +# For any answer that is not “yes” or “no”, prompt user to answer yes or no + if yes_no == yes: + print("Thank you.") + likes.append(opinions) +# For each “no”, delete that fruit from the list. + elif yes_no == no: + print("Okay. We will take that one off the list.") + while yes_no != yes or no: + print("Please answer yes or no.") + break +# Display the list. +print("Please see the fruits you like listed below.") +print(likes) + + +# Make a copy of the original list +backwards_fruits = fruits[0:-1] + +# reverse the letters in each fruit in the copy. +# for bwards in backwards_fruits: + +# print(backwards_fruits) + +# Delete the last item of the original list. +# fruits.pop(-1) + +# Display the original list and the copy. +# print(fruits) +# print(backwards_fruits) diff --git a/students/susanRees/session03/ROT13.py b/students/susanRees/session03/ROT13.py new file mode 100644 index 0000000..8bcc356 --- /dev/null +++ b/students/susanRees/session03/ROT13.py @@ -0,0 +1,22 @@ +# each letter in a text is replace by +# theletter 13 away from it + +# write function called rot13 +# takes text and returns it encrypted by ROT13. +# preserve whitespace, punctuation and caps. + +# include an if __name__ == '__main__': block +# with tests (asserts) to show it works + +# try decrypting this: +# “Zntargvp sebz bhgfvqr arne pbeare" + +import codecs + +def rot13(): + print("Please input text to be encoded") + secrets = input() + str(secrets) + print(codecs.encode(secrets, "rot-13")) + +rot13() \ No newline at end of file diff --git a/students/susanRees/session03/Slicing.py b/students/susanRees/session03/Slicing.py new file mode 100644 index 0000000..19055c8 --- /dev/null +++ b/students/susanRees/session03/Slicing.py @@ -0,0 +1,16 @@ +s = "thequickbrownfox" + +#return a sequence with the first and last items exchanged. +s[-1]+s[1:-1]+s[0] + +#return a sequence with every other item removed +s[::2] + +#return a sequence with the first and last 4 items removed, and every other item in between +s[1:-5:2] + +#return a sequence reversed (just with slicing) +s[-1], s[-2], s[-3], s[-4], s[-5], s[-6], s[-7], s[-8], s[-9], s[-10], s[-11], s[-12], s[-13], s[-14], s[-15], s[-16] + +#return a sequence with the middle third, then last third, then the first third in the new order +s[5:11], s[11:16], s[0:5] \ No newline at end of file diff --git a/students/susanRees/session04/DictionaryLab.py b/students/susanRees/session04/DictionaryLab.py new file mode 100644 index 0000000..e8f93b5 --- /dev/null +++ b/students/susanRees/session04/DictionaryLab.py @@ -0,0 +1,51 @@ +# Create a dictionary containing “name”, “city”, and “cake” +# for “Chris” from “Seattle” who likes “Chocolate”. +dict = {'name': "Chris", 'city': "Seattle", 'cake': "Chocolate"} + +# Display the dictionary. +print(dict) + +# Delete the entry for “cake”. +dict.pop('cake') + +# Display the dictionary. +print(dict) + +# Add an entry for “fruit” with “Mango” and display the dictionary. +dict.update({'fruit': "Mango"}) + +print(dict) + +# Display the dictionary keys. +print(dict.keys()) + + +# Display the dictionary values. +print(dict.values()) + +# Display whether or not “cake” is a key in the dictionary (i.e. False) (now). +print("True" if 'cake' in dict else "False") + +# Display whether or not “Mango” is a value in the dictionary (i.e. True). +print("True" if "Mango" in dict.values() else "False") + +# Using the dictionary from item 1: +# Make a dictionary using same keys but with the number of ‘t’s in each value. +# Not sure I understand the assingment... + +# Create sets s2, s3 and s4 containing numbers from 0-20, divisible 2, 3 and 4. +s2 = set([1:20]) +s3 = set([1:20]) +s4 = set([1:20]) + +# Display the sets. + +# Display if s3 is a subset of s2 (False) + +# and if s4 is a subset of s2 (True). + +# Create a set with the letters in ‘Python’ and add ‘i’ to the set. + +# Create a frozenset with the letters in ‘marathon’ + +# display the union and intersection of the two sets. \ No newline at end of file diff --git a/students/susanRees/session04/Mailroom.py b/students/susanRees/session04/Mailroom.py new file mode 100644 index 0000000..e31faab --- /dev/null +++ b/students/susanRees/session04/Mailroom.py @@ -0,0 +1,101 @@ +# list 5 donors, amounts donated (1-3 donations each). +donors = {"ender wiggin": [100, 150, 50], "bill wilson": [25, 50], "oliver queen": [1000, 2500, 500], "buffy summers": [25], "adrienne rich": [300, 50, 250]} + +# Sending a Thank You +# user selects ‘Send a Thank You’, prompt for a Full Name. +def thank(): + while True: + fullName = input('Please input the full name of the donor you wish to thank. To see a list of donors, type "list". To return to the main menu, type "main"') + fullName = str.lower(fullName) +# user types ‘list’, show them a list of the donor names and re-prompt + if fullName == "list": + for key in sorted(donors.items()): + print("{}".format(key)) +# At any point, user should be able to quit and return to original prompt. + elif fullName == "main": + print("I don't actually know how to return you to the main menu. Um. Pick something else?") +# user types a name not in the list, add that name and use it. + elif fullName not in donors: + donors[fullName] = [] + print("This is a new donor, who has now been added to the donor list.") +# user types a name in the list, use it. +# once name selected, prompt for a donation amount. + else: +# Verify that the amount is in fact a number, if not re-prompt. + while True: + amount = input('Please input the amount of the donation.') + try: + amount = int(amount) + except ValueError: + print("Please input a valid number") + else: +# Once amount given, add amount to donation history of user. + donors[fullName].append(amount) + print("This donation has been added to the donor record.") + print("Please find your thank you letter printed below.") +# use string formatting to compose an email thanking the donor +# Print email to terminal and return to original prompt. + print("\nDear {},\n\tThank you for your generous support! Your donation of ${} will go a long way towards saving the world one gay at a time. \n\tSincerely,\n\t\tGay City\n".format(str.title(fullName), amount)) + break + break + +# Creating a Report +# If user selects ‘Create a Report’ +# Print list of donors, sorted by total donation amount. +# Donor Name, total donated, number donations, avg donation as value in row. +# Using string formatting, format the output rows +# should be tabular (values in each column should align with above and below) +def report(): + for key, values in (donors.items()): + totalDonated = sum(values) + numDonations = len(key) + avgDonation = int(totalDonated/numDonations) + for key in sorted(donors.items()): + print("{}\t{}\t{}\t{}".format(key, totalDonated, numDonations, avgDonation)) +# After printing this report, return to the original prompt. + +if __name__ == '__main__': +# prompt the user to ‘Send a Thank You’ or ‘Create a Report’ + while True: + selection = input('To send a thank you letter, type "thank". To create a report, type "report".' 'To exit, type "exit".') + selection = str.lower(selection) + if selection == "thank": + thank() + break + elif selection == "report": + report() + elif selection == "exit": + exit() + else: + print('Invalid selection. Please type "thank" or "report".') + +# Guidelines +# First, factor your script into separate functions. CHECK +# each tasks can be accomplished by a series of steps. CHECK +# Write functions for individual steps and call them. CHECK +# Second, use loops to control the logical flow. CHECK +# Interactive programs are a classic use-case for the while loop. CHECK +# Of course, input() will be useful here. CHECK +# Put the functions into the script at the top. +# Put your main interaction into an if __name__ == '__main__' block. CHECK +# Finally, use only functions and data types Learned so far. CHECK +# At any point, user should be able to quit and return to original prompt. CHECK +# From original prompt, user should be able to quit the script cleanly CHECK + +# Next steps +# Update mailroom with dicts and exceptions CHECK +# Text and files and dicts, and... +# Coding Kata 14 - Dave Thomas +# http://codekata.com/kata/kata14-tom-swift-under-the-milkwood/ +# and in this doc: +# Kata Fourteen: Tom Swift Under Milk Wood +# and on github here +# http://uwpce-pythoncert.github.io/IntroToPython/exercises/kata_fourteen.html +# Use The Adventures of Sherlock Holmes as input: +# ./exercises/sherlock.txt +# and on github here: +# http://uwpce-pythoncert.github.io/IntroToPython/_downloads/sherlock.txt +# This is intentionally open-ended and underspecified. +# There are many interesting decisions to make. +# Experiment with different lengths for the lookup key. +# (3 words, 4 words, 3 letters, etc) diff --git a/students/susanRees/session05/StringFormatting.py b/students/susanRees/session05/StringFormatting.py new file mode 100644 index 0000000..adb5aff --- /dev/null +++ b/students/susanRees/session05/StringFormatting.py @@ -0,0 +1,19 @@ +# Write a format string that will take: +# ( 2, 123.4567, 10000) +# and produce: +# 'file_002 : 123.46, 1e+04' +"file_{:03d}".format(2) + +"{:06.2f}".format(123.4567) + +"{:e}".format(10000) + +# Rewrite: "the first 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3) +# to take an arbitrary number of values +# Trick: You can pass in a tuple of values to a function with a *: +# code-block:: ipython +# In [52]: t = (1,2,3) +# In [53]: “the first 3 numbers are: {:d}, {:d}, {:d}”.format(* t) +# Out[53]: ‘the first 3 numbers are: 1, 2, 3’ +t = (1, 2, 3) +"the first 3 numbers are: {:d}, {:d}, {:d}".format(* t) \ No newline at end of file diff --git a/students/susanRees/session05/file.py b/students/susanRees/session05/file.py new file mode 100644 index 0000000..01b24b5 --- /dev/null +++ b/students/susanRees/session05/file.py @@ -0,0 +1,14 @@ +# Write a little script that reads that file +# generates a list of all the languages that have been used. + +# Extra credit: track how many students specified each language + +language_set = set() +with open('students.txt', 'r') as f: + pulled_data = f.readlines() + for line in pulled_data: + student_languages = line.split(":")[1] + language_list = student_languages.split(",") + for language in language_list: + language_set.add(language) +print(language_set) diff --git a/students/susanRees/session05/students.txt b/students/susanRees/session05/students.txt new file mode 100644 index 0000000..fe6b413 --- /dev/null +++ b/students/susanRees/session05/students.txt @@ -0,0 +1,24 @@ +Bindhu, Krishna: +Bounds, Brennen: English +Gregor, Michael: English +Holmer, Deana: SQL, English +Kumar, Pradeep: English, Hindi, Python, shell, d2k, SQL, Perl +Rees, Susan: English, Latin, HTML, CSS, Javascript, Ruby, SQL +Rudolph, John: English, Python, Sass, R, Basic +Solomon, Tsega: C, C++, Perl, VHDL, Verilog, Specman +Warren, Benjamin: English +Aleson, Brandon: English +Chang, Jaemin: English +Chinn, Kyle: English +Derdouri, Abderrazak: English +Fannin, Calvin: C#, SQL, R +Gaffney, Thomas: SQL, Python, R, VBA, English +Glogowski, Bryan: Basic, Pascal, C, Perl, Ruby +Ganzalez, Luis: Basic, C++, Python, English, Spanish +Ho, Chi Kin: English +McKeag, Gregory: C, Lisp, C++, Objective-C, SQL, R, Pascal, Ada, Perl, Prolog, Scheme, Assembley +Myerscough, Damian: +Newton, Michael: Python, Perl, Matlab +Sarpangala, Kishan: +Schincariol, Mike: Python, C#, C, Tcl, VBA, Perl, Bash, VHDL, Verilog, Matlab +Zhao, Yuanrui: \ No newline at end of file diff --git a/students/susanRees/session06/cigar_party.py b/students/susanRees/session06/cigar_party.py new file mode 100644 index 0000000..baee654 --- /dev/null +++ b/students/susanRees/session06/cigar_party.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + +def cigar_party(cigars. is_weekend): + num_cigars = input("How many cigars?") + int(num_cigars) + is_weekend = input("Is it the weekend?") + if is_weekend == str.lower("yes"): + num_cigars + num_cigars < 40 or > 60: + return True + + + + diff --git a/students/susanRees/session06/exceptions.py b/students/susanRees/session06/exceptions.py new file mode 100644 index 0000000..e69de29 diff --git a/students/susanRees/session06/test_cigar_party.py b/students/susanRees/session06/test_cigar_party.py new file mode 100644 index 0000000..260d5f4 --- /dev/null +++ b/students/susanRees/session06/test_cigar_party.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +# you can change this import to test different versions +from cigar_party import cigar_party +# from cigar_party import cigar_party2 as cigar_party +# from cigar_party import cigar_party3 as cigar_party + + +def test_1(): + assert cigar_party(30, False) is False + + +def test_2(): + assert cigar_party(50, False) is True + + +def test_3(): + assert cigar_party(70, True) is True + + +def test_4(): + assert cigar_party(30, True) is False + + +def test_5(): + assert cigar_party(50, True) is True + + +def test_6(): + assert cigar_party(60, False) is True + + +def test_7(): + assert cigar_party(61, False) is False + + +def test_8(): + assert cigar_party(40, False) is True + + +def test_9(): + assert cigar_party(39, False) is False + + +def test_10(): + assert cigar_party(40, True) is True + + +def test_11(): + assert cigar_party(39, True) is False diff --git a/students/tsegas/fbizz_func.py b/students/tsegas/fbizz_func.py new file mode 100644 index 0000000..63cc239 --- /dev/null +++ b/students/tsegas/fbizz_func.py @@ -0,0 +1,35 @@ +### lab-1 FizzBizz program: determine if a list of numbers is +### divisible by 3/5/both/niether and print out the results + +#FIZZBUZZ function +def fizzbuzz(number): + + #if divisible by three or five + dthr = 0 + dfiv = 0 + + # print the number range + print('The numbers to use from 1 to {0} are'.format(number)) + + for n in range(1,number+1): + # check if numbers are divisible by 3 or 5 or both or niether + if (n % 3) == 0: + dthr = 1 + dfiv = 0 + if (n % 5) == 0: + dfiv = 1 + elif (n % 5) == 0: + dfiv = 1 + dthr = 0 + else: + print(n) + dthr = 0 + dfiv = 0 + if (dthr == 1 and dfiv ==0): # can you combine the print statments with the if/elif/else above to simplify? + print('FIZZ') + if (dthr == 0 and dfiv ==1): + print('BUZZ') + if (dthr == 1 and dfiv ==1): + print('FIZZBUZZ') +#call the function +fizzbuzz(number=30) diff --git a/students/tsegas/lab1_slice1.py b/students/tsegas/lab1_slice1.py new file mode 100755 index 0000000..b1aba7a --- /dev/null +++ b/students/tsegas/lab1_slice1.py @@ -0,0 +1,17 @@ +# return sequence with last and first items changed + +seq1 = [4,5,6,7,8,9] + +temp = seq1[0] +length = len(seq1) +temp1 = seq1[length-1] + +print("original sequence",seq1) + +seq1.pop(0) +seq1.pop(length-2) +print("sequence with first and last element removed",seq1) +seq1.append(temp) +seq1.insert(0,temp1) +print("sequence with the first and last items exchanged",seq1) + diff --git a/students/tsegas/session03/list_lab.py b/students/tsegas/session03/list_lab.py new file mode 100755 index 0000000..3a19c3e --- /dev/null +++ b/students/tsegas/session03/list_lab.py @@ -0,0 +1,168 @@ +# list lab execises from session-03 + +import random +import string +import sys +import os + +# List of fruits +mylist = ["apples", "pears","oranges","peaches"] + +# Display the list +print('\n',"List of fruit",mylist,'\n') + +# Prompt for another type of fruit +newfruit = input('Enter a type of fruit:') + +mylist.append(newfruit) + +mylen = len(mylist) + +# Display the list with the new fruit added +print("List of fruit with the {} added".format(newfruit),mylist,'\n') + +# Prompt for a number +num = int(input('Enter a number from 1 to {:d}:'.format(mylen))) +#int(input("Please enter an integer: ")) + +for i in range(0,mylen): + if (i == num-1): + print("The fruit at that number is",mylist[i],'\n') + +addfruit = ["lemon"] +mylist = addfruit + mylist + +# Display the list with lemon added +print("List of fruit with lemon added",mylist) + +mylist.insert(0,"kiwi") + +# Display the list with kiwi added +print("List of fruit with kiwi added",mylist,'\n') + +for i in mylist: + # find fruits that start with a 'P' + if (i[0] == "p"): + print("This fruit starts with p",i,'\n') + + +############################## Series 2 ---- actions ####################################### +# Display the list +print("List of fruit:",mylist,'\n') + +# Remove the last fruit +mylist.pop() + +# Display the list +print("List of fruit with the last item removed:",mylist,'\n') + +# Double the elements in the list +mylist = mylist + mylist +# Display the list +print("List of fruit.... multiplied by 2:",mylist,'\n') + +# Prompt for a fruit to delete +delfruit = input('Enter a fruit to be deleted:') + +temp = mylist.copy() +lenth = len(temp) + +# for loop to go through the list and delete occurances of the seleted fruit +for i in range(0,(lenth-1)): + if (temp[i] == delfruit): + #delete the spcified fruit + mylist.remove(temp[i]) + else: + print("This fruit was not selected for removal",temp[i],'\n') + +# Display the list with the selected fruit removed +print("List of fruit with all occurances of {} removed".format(delfruit),mylist,'\n') + +############################## Series 3 ---- actions ####################################### + +# Change each fruit's first letter to capital +ntemp = mylist.copy() +for i, elem in enumerate(ntemp): + s = elem + mylist.remove(elem) + # Set the first letter in each item in the list to upper case + s = s.capitalize() + elem = s + # insert the the capitalized item right back in its place + mylist.insert(i,elem) + +# Display the list with each item capitalized +print("List of fruit with each item capitalized ...:",mylist,'\n') + +# Change each fruit's first letter to lower case +ntemp = mylist.copy() +for i, elem in enumerate(ntemp): + s = elem + mylist.remove(elem) + # Set the first letter in each item in the list to lower case + s = s.lower() + elem = s + # insert the the capitalized item right back in its place + mylist.insert(i,elem) + +# Display the list with each item in lower case +print("List of fruit with each item in lower case ...:",mylist,'\n') + +tlist = mylist.copy() +# Loop through the list and ask the user if they like the fruit item +for i in tlist: + # Prompt for a fruit to delete + answ = (input('Do you like {}:'.format(i))) + if (answ == "no"): + # Remove the item + mylist.remove(i) + elif (answ == "yes"): + print('you like this fruit:',i,'\n') + # insist on a "yes" or "no" answer + else: + answ = input('Enter "yes" or "no" Please:') + if (answ == "no"): + # Remove the item + mylist.remove(i) + elif (answ == "yes"): + print('you like this fruit:',i,'\n') + +# Display the list of liked fruits +print("List of fruit with the ones you don't like removed:",mylist,'\n') + +############################## Series 4 ---- actions ####################################### + +# copy the last list +nextlist = mylist.copy() +print("List of fruit displayed... ",nextlist,'\n') +nlist = [] +ilist = [] +# loop through the list of fruit items +for i in nextlist: + n = 1 + strg = '' + # Loop through each fruit item to get each letter that needs to be reversed + for j in i: + ln = len(i) + last = (i[ln-n]) + n = n+1 + if (n > 1): + strg = ''.join((strg,last)) + ilist = [strg] + nlist = nlist + ilist + +# Display the list of liked fruits +print("List of fruit with letters in each fruit reversed...",nlist,'\n') + +# copy the list +lastlist = nextlist.copy() + +# Remove last item in the list +lastlist.pop() + +# Display the original list +print("The original list of fruit displayed... ",nextlist,'\n') + + +# Display the original list +print("The original list of fruit with the last item deleted... ",lastlist,'\n') diff --git a/students/tsegas/session03/slice_lab1.py b/students/tsegas/session03/slice_lab1.py new file mode 100644 index 0000000..91de405 --- /dev/null +++ b/students/tsegas/session03/slice_lab1.py @@ -0,0 +1,31 @@ +#return sequence with last and first items changed + +#original seuqence +seq1 = [4,5,6,7,8,9] + +# assign the first element to temp +temp = seq1[0] + +#length of the sequence +length = len(seq1) + +#assign the lat element to temp1 +temp1 = seq1[length-1] + +#print the original sequence +print("original sequence",seq1) + +#remove the first element +seq1.pop(0) + +#remove the last element +seq1.pop(length-2) +print("sequence with first and last element removed",seq1) + +#append the first element which was stored in temp +seq1.append(temp) + +#insert the last element which was stored in temp1 +seq1.insert(0,temp1) +print("sequence with the first and last items exchanged",seq1) + diff --git a/students/tsegas/session03/slice_lab2.py b/students/tsegas/session03/slice_lab2.py new file mode 100644 index 0000000..ec298b4 --- /dev/null +++ b/students/tsegas/session03/slice_lab2.py @@ -0,0 +1,23 @@ +#return sequence with every other items removed + +#original seuqence +seq1 = [4,5,6,7,8,9] + +#length of the sequence +length = len(seq1) + +#print the original sequence +print("original sequence",seq1) + +n = 1 +lim = abs(length/2) +# if sequence length is half the number of original items stop looping +while (length > lim): + + seq1.pop(n) + n=n+1 + if (n > lim): + print("sequence with every other item removed...",seq1) + + + diff --git a/students/tsegas/session03/slice_lab3.py b/students/tsegas/session03/slice_lab3.py new file mode 100644 index 0000000..e199583 --- /dev/null +++ b/students/tsegas/session03/slice_lab3.py @@ -0,0 +1,29 @@ +#return a sequence with the first and last 4 items removed, +#and every other item in between + +#original seuqence +seq1 = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d'] + +#length of the sequence +length = len(seq1) + +#print the original sequence +print("original sequence",seq1) + +# remove the first 4 items and the last four items from the sequence +seq2 = seq1[4:(length-4)] +print("sequence with first and last 4 items removed",seq2) + +n = 1 +length2 = len(seq2) +lim = abs(length2/2) +# if sequence length is half the number of original items stop looping +while (length2 > lim): + + seq2.pop(n) + n=n+1 + if (n > lim): + print("sequence with every other item in between...",seq2) + + + diff --git a/students/tsegas/session03/slice_lab4.py b/students/tsegas/session03/slice_lab4.py new file mode 100644 index 0000000..761498e --- /dev/null +++ b/students/tsegas/session03/slice_lab4.py @@ -0,0 +1,12 @@ +#return a sequence reversed (just with slicing) + +#original seuqence +seq1 = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d'] + +#print the original sequence +print("original sequence",seq1) + +seq2 = seq1[::-1] +print("sequence reversed is:.......",seq2) + + diff --git a/students/tsegas/session03/slice_lab5.py b/students/tsegas/session03/slice_lab5.py new file mode 100644 index 0000000..e648965 --- /dev/null +++ b/students/tsegas/session03/slice_lab5.py @@ -0,0 +1,27 @@ +#return a sequence with the middle third, then last third, then the first third in the new order + +#original seuqence +seq1 = [1,2,3,4,5,6,7,8,9,10,'a','b'] + +length = len(seq1) + +#print the original sequence +print("original sequence",seq1) + +#a third of the length of the list is +third = int(abs(length/3)) + +# split the sequence into three equal parts +seq2 = seq1[0:(third)] +seq3 = seq1[third:(third*2)] +seq4 = seq1[(third*2):(third*3)] + +print("first ..........3rd",seq2) +print("2nd ..........3rd",seq3) +print("3rd ..........3rd",seq4) + +# combine the sequence in a different order +nseq = seq3 + seq4 +seq2 +print("new sequence:..........",nseq) + + diff --git a/students/tsegas/session03/str_format_lab.py b/students/tsegas/session03/str_format_lab.py new file mode 100644 index 0000000..92f81fc --- /dev/null +++ b/students/tsegas/session03/str_format_lab.py @@ -0,0 +1,42 @@ +# String format lab execises from session-03 +# produce 'file_002 : 123.46, 1e+04' + +import random +import string +import sys +import os +import math + +#passnum function to pass the 3 numbers +def passnum(x,y,z): + print("The first 3 numbers are: {:d}, {:d}, {:d}".format(x,y,z)) + n = ('{:d}{:d}{:d}'.format(x,y,z)) + return n + +#call the function +n=passnum(x=7,y=8,z=9) + +# Convert the returned value to an integer +n = int(n) +f1 = '{:.4f}'.format(.4567).lstrip('0') + +# Convert to float +f = float(f1) + +m = ('{:d}{:.4f}'.format(n,f).lstrip('0')) + +# Convert to float +m = float(m) +# This was the only way for now I could get rid of the leading zero +m = (m/10)+0.41103 + +strg = (2,m,10000) +print("Change this............",strg) + +a = ('{:d}'.format(strg[0])) +b = ('{:05.2f}'.format(strg[1])) +# Format the last value as an exponent +c = ('{:01.0e}'.format(strg[2])) + +print("To this................ file_00{} : {},".format(a,b),c,'\n') + diff --git a/students/tsegas/session04/dict_lab.py b/students/tsegas/session04/dict_lab.py new file mode 100755 index 0000000..ca460d9 --- /dev/null +++ b/students/tsegas/session04/dict_lab.py @@ -0,0 +1,12 @@ +# dict_lab.py --- + +my = dict(name='Chris', city='Seattle', cake='chocolate') + +print("print the dict",my) +my.pop('cake') +print("print the dict",my) +my['fruit'] = 'mango' +print("print the dict",my) + +cpy_my = my.copy() +print("print the dict",cpy_my) \ No newline at end of file diff --git a/students/tsegas/session04/mailroom.py b/students/tsegas/session04/mailroom.py new file mode 100755 index 0000000..4f8805f --- /dev/null +++ b/students/tsegas/session04/mailroom.py @@ -0,0 +1,100 @@ +# mailroom script: Writes emails thanking donors for donation amounts and generates report of donations +# +import random +import string +import sys +from collections import Counter + +# Initial Dictionary of doners nd amounts +d = {'Chris C': 200, 'John J': 300, 'Matt M': 400, 'Luke L': 100, 'Eli E': 500} +a = {'amount1': 1,'amount2': 2,'amount3': 3,'amount4': 4,'amount5': 5} + +#print("The doners are:",d) +#print("print the amounts",a) + +# function to get doner and the amount +def donfunc(option,name,amount): + #if thanks you: + if option == 'yes': + #print("print doner",name) + if name == "list": + print("printing the list of doners.... ",d) + don_again = input('Enter full name of doner:') + dname = don_again + else: + dname = name + + if amount.isdigit() == True: + #print("print new amount",amount) + amount = int(amount) + else: + # print("enter a number please:") + amount = input('enter a number please:') + amount = int(amount) + #a['amount6'] = amount + if dname in (d): + d[dname] = d[dname] + amount + else: + d[dname] = amount + #print("print the list of doners",d) + #print("print the list of amounts",a) + + #print("Dear %s,\n",%dname) + print('Dear {0},'.format(dname)) + print("Thank you for your ${0}.00 donation".format(amount),'\n') + #don = input('Enter full name of doner or list:') + +def repeats(name,comp): + if (name == comp): + match = 1 + return match + +def repfunc(count,dn): + #if opt2 == 'yes': + #for i, item in enumerate(d): + #print(a) + l = len(d) + #print(l) + #ak = list(a)[i] + #print(ak) + tot = sum(d.values()) + #print('total..........',tot) + avg = tot/l + numd = count + n = ('{:s} ${:d}.00 {} ${:06.2f}.00'.format(dn,d[dn],numd,avg)) + print(n) + +m = repeats(name="temp",comp="temp") + +#function to print out the report +def report (): + h = ('Doner Total Donation Count Average Donation') + print(h) + for i, item in enumerate(d): + f = list(d)[i] + cnt = 0 + for i in d.keys(): + #print('iiiiiii',i) + #print(cnt) + m = repeats(name=f,comp=i) + #print(m) + if m == 1: + cnt = cnt + 1 + #print('count........',cnt) + #print("the %ith item is: %s with count %i"%(i, d.get(item),cnt)) + ndict = ('{:s}(count:{:d})'.format(f,cnt)) + repfunc(count=ndict,dn=f) + + +opt1 = input('Send a Thank You?:') +opt2= input('Create a Report?:') + + +if opt1 == 'yes': + don = input('Enter full name of doner or list:') + amou = input('enter the donation amount:') + #call the function + donfunc(option=opt1,name=don,amount=amou) +if opt2 == 'yes': + #call the function + report() diff --git a/students/tsegas/session07/data.txt b/students/tsegas/session07/data.txt new file mode 100644 index 0000000..1b3989e --- /dev/null +++ b/students/tsegas/session07/data.txt @@ -0,0 +1,104 @@ +-- +-- Package File Template +-- +-- Purpose: This package defines supplemental types, subtypes, +-- constants, and functions +-- +-- To use any of the example code shown below, uncomment the lines and modify as necessary +-- + +library IEEE; +use IEEE.STD_LOGIC_1164.all; + +package project_components_pkg is + + component character_decoder is + generic (CLOCK_FREQUENCY : integer := 40_000_000); + Port ( clk : in STD_LOGIC; + charFromUART_valid : in STD_LOGIC; + charFromUART : in STD_LOGIC_VECTOR(7 downto 0); + LED_hi : out STD_LOGIC; + LED_lo : out STD_LOGIC; + send_character : out STD_LOGIC; + character_to_send : out STD_LOGIC_VECTOR (7 downto 0) + ); + end component character_decoder; + + component decoder is + generic (CLOCK_FREQUENCY : integer := 40_000_000); + Port ( clk : in STD_LOGIC; + charFromUART_valid : in STD_LOGIC; + charFromUART : in STD_LOGIC_VECTOR(7 downto 0); + LED_hi : out STD_LOGIC; + LED_lo : out STD_LOGIC; + send_character : out STD_LOGIC; + character_to_send : out STD_LOGIC_VECTOR (7 downto 0) + ); + end component decoder; + + component character_encoder is + Port ( clk : in STD_LOGIC; + character_decoded : in STD_LOGIC; + character_to_send : in STD_LOGIC_VECTOR (7 downto 0); + tx_ready : in STD_LOGIC; + parallelDataIn : out STD_LOGIC_VECTOR (7 downto 0); + transmitRequest : out STD_LOGIC; + DIP_dbncd : in STD_LOGIC_VECTOR (3 downto 0) + ); + end component character_encoder; + + component debouncer is + generic (DELAY_VALUE : integer := 4_000_000); -- 100 ms at 40 MHz + Port ( clk : in STD_LOGIC; + signal_in : in STD_LOGIC; + signal_out : out STD_LOGIC + ); + end component debouncer; + + component UART is + generic (BAUD_RATE : integer := 19200; + CLOCK_RATE : integer := 100000000); + port ( reset : in STD_LOGIC; + clock : in STD_LOGIC; + serialDataIn : in STD_LOGIC; + parallelDataOut : out STD_LOGIC_VECTOR (7 downto 0); + dataValid : out STD_LOGIC; + parallelDataIn : in STD_LOGIC_VECTOR (7 downto 0); + transmitRequest : in STD_LOGIC; + txIsReady : out STD_LOGIC; + serialDataOut : out STD_LOGIC + ); + end component UART; + + component UART_baudRateGenerator is + generic (BAUD_RATE : integer := 19200; + CLOCK_RATE : integer := 100000000); + port ( reset : in STD_LOGIC; + clock : in STD_LOGIC; + baudRateEnable : out STD_LOGIC; + baudRateEnable_x16 : out STD_LOGIC + ); + end component UART_baudRateGenerator; + + component UART_transmitter is + Port ( reset : in STD_LOGIC; + clock : in STD_LOGIC; + baudRateEnable : in STD_LOGIC; + parallelDataIn : in STD_LOGIC_VECTOR (7 downto 0); + transmitRequest : in STD_LOGIC; + ready : out STD_LOGIC; + serialDataOut : out STD_LOGIC + ); + end component UART_transmitter; + + component UART_receiver is + Port ( reset : in STD_LOGIC; + clock : in STD_LOGIC; + baudRateEnable_x16 : in STD_LOGIC; + serialDataIn : in STD_LOGIC; + parallelDataOut : out STD_LOGIC_VECTOR (7 downto 0); + dataValid : out STD_LOGIC + ); + end component UART_receiver; + +end project_components_pkg; diff --git a/students/tsegas/session07/lightningTalk_tsegas.py b/students/tsegas/session07/lightningTalk_tsegas.py new file mode 100755 index 0000000..8160048 --- /dev/null +++ b/students/tsegas/session07/lightningTalk_tsegas.py @@ -0,0 +1,37 @@ +# +# This script takes a files and changes a specified line in that files by finding a +# string in the line and changing it in place. It also backs up the original files content. + +import os +import sys + +# This function takes an input file and changes a specified line in that files and it +# also backs up the original files content +def change_string(filename, bachup_file, old_string, new_string): + datafile= filename + try: + with open(datafile) as f: print("looking for file...") + except IOError as e: + print("Error: %s not found." % datafile) + return + + os.rename(filename,bachup_file) + f1 = open(bachup_file, 'r') + f2 = open(filename, 'w') + for line in f1: + if "component character_decoder is" in line: + print("the line that was found:",line) + f2.write(line) + f2.write(' ' +next(f1, '').strip().replace(old_string, new_string) + '\n') + else: + f2.write(line) + f1.close() + f2.close() +fname = input('enter filename?:') +back_fname = input('enter backup filename?:') +ostring = input('enter old string?:') +nstring = input('enter new string?:') +#call function change_string with the file specific parameters +change_string(filename=fname,bachup_file=back_fname,old_string=ostring,new_string=nstring) +#change_string(filename='data.txt',bachup_file='data_back.txt',old_string="integer := 40_000_000",new_string="integer := 20_000_000") +# \ No newline at end of file