├── Examples
├── Session04
│ ├── junk2.txt
│ ├── junkfile.txt
│ ├── test_file2.txt
│ ├── simple_text_file.txt
│ ├── format_test.py
│ ├── format_example.py
│ └── __main__example.py
├── README.rst
├── Session03
│ ├── test_script.py
│ ├── module_reload.py
│ ├── slicing_lab.py
│ └── mailroom_start.py
├── Session05
│ ├── arg_test.py
│ ├── codingbat.py
│ ├── test_codingbat.py
│ ├── test_pytest_parameter.py
│ ├── test_random_pytest.py
│ └── test_random_unitest.py
├── Suppliments
│ ├── text.utf16
│ ├── text.utf32
│ ├── ICanEatGlass.utf16.txt
│ ├── example.cfg
│ ├── hello_unicode.py
│ ├── unicode_exception_test.py
│ ├── text.utf8
│ ├── ICanEatGlass.utf8.txt
│ ├── latin1_test.py
│ ├── add_book_data_flat.py
│ ├── unicodify.py
│ └── add_book_data.py
├── Session07
│ ├── html_render
│ │ ├── .DS_Store
│ │ ├── test_html_output1.html
│ │ ├── html_render.py
│ │ ├── test_html_output2.html
│ │ ├── test_html_output4.html
│ │ ├── test_html_output5.html
│ │ ├── test_html_output3.html
│ │ ├── test_html_output6.html
│ │ ├── sample_html.html
│ │ ├── test_html_output7.html
│ │ └── test_html_output8.html
│ ├── class.py
│ └── class_demo.py
├── Session01
│ ├── test.py
│ └── schedule.py
├── Session02
│ ├── factorial.py
│ └── codingbat.rst
├── Session08
│ ├── circle.py
│ ├── static_method.py
│ ├── class_method.py
│ ├── properties_example.py
│ └── vector.py
├── Session10
│ ├── timer.py
│ ├── property_ugly.py
│ ├── timer_context.py
│ ├── p_wrapper.py
│ ├── test_p_wrapper.py
│ ├── memoize.py
│ ├── context_managers.py
│ └── decorators.py
├── Session06
│ ├── cigar_party.py
│ ├── closure.py
│ ├── safe_input.py
│ ├── test_pytest_parameter.py
│ ├── codingbat.py
│ ├── test_random_unitest.py
│ ├── test_codingbat.py
│ ├── test_random_pytest.py
│ └── test_cigar_party.py
└── Session09
│ ├── yield_example.py
│ ├── closure.py
│ ├── iterator_1.py
│ ├── my_for.py
│ └── test_generator.py
├── slides_sources
├── old_versions
│ ├── week-05
│ │ ├── presentation-week-05.snm
│ │ ├── code
│ │ │ ├── text.utf16
│ │ │ ├── text.utf32
│ │ │ ├── hello_unicode.py
│ │ │ ├── codingbat.py
│ │ │ ├── test_codingbat.py
│ │ │ ├── codingbat_unittest.py
│ │ │ ├── test_pytest_parameter.py
│ │ │ ├── test_random_nose.py
│ │ │ ├── test_random_pytest.py
│ │ │ └── unittest_example.py
│ │ ├── presentation-week-05.log
│ │ ├── presentation-week-05.pdf
│ │ ├── presentation-week-05.out
│ │ ├── presentation-week-05.toc
│ │ └── presentation-week-05.vrb
│ ├── week-09
│ │ ├── code
│ │ │ ├── capitalize
│ │ │ │ ├── capitalize
│ │ │ │ │ ├── __init__.py
│ │ │ │ │ └── capital_mod.py
│ │ │ │ ├── test
│ │ │ │ │ └── test_text_file.txt
│ │ │ │ ├── setup.py
│ │ │ │ └── scripts
│ │ │ │ │ └── cap_script.py
│ │ │ ├── decorators
│ │ │ │ ├── properties_dec_example.py
│ │ │ │ ├── circle_properties.py
│ │ │ │ ├── circle_properties_solution.py
│ │ │ │ ├── p_wrapper.py
│ │ │ │ └── p_wrapper_solution.py
│ │ │ └── context_manager
│ │ │ │ ├── timer_context.py
│ │ │ │ ├── timer_context_solution.py
│ │ │ │ └── timer_context.rst
│ │ ├── packaging1.pdf
│ │ ├── PackagingTimeline.pdf
│ │ └── presentation-week-09.pdf
│ ├── week-02
│ │ ├── code
│ │ │ ├── command_params.py
│ │ │ ├── distance.py
│ │ │ ├── fib_solution.py
│ │ │ ├── factorial.py
│ │ │ ├── FizzBuzz.py
│ │ │ └── codingbat.rst
│ │ ├── presentation-week02.pdf
│ │ ├── homework.rst
│ │ ├── homework_gary.py
│ │ ├── homework_solution.py
│ │ └── homework_solution_memo.py
│ ├── week-01
│ │ ├── GvR.jpg
│ │ ├── code
│ │ │ ├── .DS_Store
│ │ │ ├── schedule.py
│ │ │ ├── split_student_names.py
│ │ │ ├── students.txt
│ │ │ └── schedule.txt
│ │ ├── PythonOrigins.jpg
│ │ ├── presentation-week01.pdf
│ │ ├── students.txt
│ │ ├── demo_notes.txt
│ │ ├── homework1_solution.py
│ │ └── homework.rst
│ ├── week-10
│ │ ├── code
│ │ │ ├── example.cfg
│ │ │ ├── Solutions
│ │ │ │ ├── pickle_example.py
│ │ │ │ ├── json_example.py
│ │ │ │ ├── indent_etree.py
│ │ │ │ ├── shelve_example.py
│ │ │ │ ├── circle.py
│ │ │ │ ├── ini_file_example.py
│ │ │ │ ├── python_literal.py
│ │ │ │ ├── anydbm_example.py
│ │ │ │ ├── xml_example.py
│ │ │ │ ├── pickle_example2.py
│ │ │ │ ├── csv_example.py
│ │ │ │ ├── add_book_data_flat.py
│ │ │ │ ├── add_book_data.py
│ │ │ │ └── xml_example2.py
│ │ │ ├── switch_case.py
│ │ │ ├── add_book_data_flat.py
│ │ │ └── add_book_data.py
│ │ └── presentation-week-10.pdf
│ ├── week-03
│ │ ├── presentation-week03.pdf
│ │ └── code
│ │ │ ├── module_reload.py
│ │ │ ├── mail_merge_solution.py
│ │ │ ├── list_lab_solution.py
│ │ │ └── string_formatting_solution.py
│ ├── week-04
│ │ ├── presentation-week-04.pdf
│ │ ├── code
│ │ │ ├── students_languages_solution.py
│ │ │ └── students_languages.txt
│ │ └── homework
│ │ │ └── sherlock_small.txt
│ ├── week-06
│ │ ├── presentation-week-06.pdf
│ │ └── code
│ │ │ ├── lambda
│ │ │ ├── lambda_keyword.pyc
│ │ │ ├── lambda_keyword_solution.py
│ │ │ ├── lambda_keyword.py
│ │ │ └── test_lambda_keyword.py
│ │ │ ├── html_render
│ │ │ ├── sample_html.html
│ │ │ └── Solutions
│ │ │ │ ├── gen_1.py
│ │ │ │ └── gen_2.py
│ │ │ └── simple_classes.py
│ ├── week-07
│ │ └── presentation-week-07.pdf
│ ├── week-08
│ │ ├── presentation-week-08.pdf
│ │ └── code
│ │ │ ├── circle.py
│ │ │ ├── yield_example.py
│ │ │ ├── properties_example.py
│ │ │ ├── static_method.py
│ │ │ ├── class_method.py
│ │ │ ├── iterator_1.py
│ │ │ ├── circle_solution1.py
│ │ │ ├── GeneratorLAB.rst
│ │ │ ├── yield_xrange.py
│ │ │ ├── test_circle1.py
│ │ │ ├── test_iterator.py
│ │ │ ├── vector.py
│ │ │ ├── generator_solution.py
│ │ │ ├── iterator_3_solution.py
│ │ │ ├── iterator_2_solution.py
│ │ │ ├── test_generator.py
│ │ │ └── circle_solution2.py
│ ├── week-08.5
│ │ ├── presentation-wxpython.pdf
│ │ └── code
│ │ │ ├── address_book_solution
│ │ │ ├── .DS_Store
│ │ │ ├── a_book.json
│ │ │ └── address_book_data.py
│ │ │ ├── basic_app_1.py
│ │ │ └── address_book
│ │ │ ├── a_book.json
│ │ │ ├── switcher.py
│ │ │ └── address_book_data.py
│ └── readme.rst
├── source
│ ├── _static
│ │ ├── pc_menu.png
│ │ ├── python.png
│ │ ├── git_head.png
│ │ ├── phd101212s.gif
│ │ ├── plugin_list.png
│ │ ├── remotes_fork.png
│ │ ├── flake8_output.png
│ │ ├── git_new_branch.png
│ │ ├── git_new_commit.png
│ │ ├── remotes_clone.png
│ │ ├── remotes_start.png
│ │ ├── simple_prompt.png
│ │ ├── tab_completion.png
│ │ ├── transmogrifier.jpg
│ │ ├── color_git_prompt.png
│ │ ├── git_master_branch.png
│ │ ├── git_merge_commit.png
│ │ ├── remotes_upstream.png
│ │ ├── two_line_prompt.png
│ │ ├── virtualenv_prompt.png
│ │ ├── git_checkout_branch.png
│ │ ├── git_checkout_master.png
│ │ ├── git_simple_timeline.png
│ │ ├── git_commit_on_branch.png
│ │ ├── git_new_commit_on_master.png
│ │ └── git_another_commit_on_branch.png
│ ├── supplements
│ │ ├── text.utf16
│ │ ├── text.utf32
│ │ ├── ICanEatGlass.utf16.txt
│ │ ├── index.rst
│ │ ├── hello_unicode.py
│ │ ├── exception_test.py
│ │ ├── unicode_exception_test.py
│ │ ├── static_method.py
│ │ ├── properties_example.py
│ │ ├── class_method.py
│ │ ├── text.utf8
│ │ ├── ICanEatGlass.utf8.txt
│ │ ├── vector.py
│ │ ├── latin1_test.py
│ │ └── unicodify.py
│ ├── include.rst
│ ├── _templates
│ │ ├── end_slide.html
│ │ └── title_slide.html
│ ├── exercises
│ │ ├── slicing.rst
│ │ ├── exceptions_lab.rst
│ │ ├── sample_html.html
│ │ ├── sherlock_small.txt
│ │ ├── index.rst
│ │ ├── fizz_buzz.rst
│ │ ├── lambda_magic.rst
│ │ ├── rot13.rst
│ │ ├── file_lab.rst
│ │ └── args_kwargs_lab.rst
│ └── index.rst
├── requirements.txt
├── ToDo.txt
└── build_gh_pages.sh
├── .gitignore
└── README.rst
/Examples/Session04/junk2.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Examples/Session04/junkfile.txt:
--------------------------------------------------------------------------------
1 | some textsome more text
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-05/presentation-week-05.snm:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Examples/README.rst:
--------------------------------------------------------------------------------
1 | Example code, etc.
2 |
3 | Random stuff here.
4 |
5 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-09/code/capitalize/capitalize/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Examples/Session03/test_script.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | print "yes, it ran"
4 |
5 |
--------------------------------------------------------------------------------
/Examples/Session04/test_file2.txt:
--------------------------------------------------------------------------------
1 | antoher simple text file
2 | still with jsut a couple lines in it
3 |
--------------------------------------------------------------------------------
/Examples/Session05/arg_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import sys
4 |
5 | print(sys.argv)
6 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-02/code/command_params.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import sys
3 |
4 | print sys.argv
5 |
6 |
--------------------------------------------------------------------------------
/Examples/Session04/simple_text_file.txt:
--------------------------------------------------------------------------------
1 | This is a text file with very little in it
2 | but it at least has more than one line
3 |
--------------------------------------------------------------------------------
/Examples/Suppliments/text.utf16:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/Examples/Suppliments/text.utf16
--------------------------------------------------------------------------------
/Examples/Suppliments/text.utf32:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/Examples/Suppliments/text.utf32
--------------------------------------------------------------------------------
/Examples/Session04/format_test.py:
--------------------------------------------------------------------------------
1 | def print_msg(t):
2 | print ("the first %i numbers are: " + ", ".join(["%i"] * len(t)) ) % ((len(t),) + t)
3 |
4 |
--------------------------------------------------------------------------------
/Examples/Session07/html_render/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/Examples/Session07/html_render/.DS_Store
--------------------------------------------------------------------------------
/slides_sources/source/_static/pc_menu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/pc_menu.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/python.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/python.png
--------------------------------------------------------------------------------
/Examples/Suppliments/ICanEatGlass.utf16.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/Examples/Suppliments/ICanEatGlass.utf16.txt
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-01/GvR.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-01/GvR.jpg
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_head.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_head.png
--------------------------------------------------------------------------------
/Examples/Suppliments/example.cfg:
--------------------------------------------------------------------------------
1 | [Section1]
2 | int = 15
3 | bool = true
4 | float = 3.1415
5 |
6 | [Section2]
7 | int = 32
8 | bool = False
9 | float = 1.4235
--------------------------------------------------------------------------------
/slides_sources/source/_static/phd101212s.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/phd101212s.gif
--------------------------------------------------------------------------------
/slides_sources/source/_static/plugin_list.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/plugin_list.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/remotes_fork.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/remotes_fork.png
--------------------------------------------------------------------------------
/slides_sources/source/supplements/text.utf16:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/supplements/text.utf16
--------------------------------------------------------------------------------
/slides_sources/source/supplements/text.utf32:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/supplements/text.utf32
--------------------------------------------------------------------------------
/slides_sources/source/_static/flake8_output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/flake8_output.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_new_branch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_new_branch.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_new_commit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_new_commit.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/remotes_clone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/remotes_clone.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/remotes_start.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/remotes_start.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/simple_prompt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/simple_prompt.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/tab_completion.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/tab_completion.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/transmogrifier.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/transmogrifier.jpg
--------------------------------------------------------------------------------
/Examples/Session01/test.py:
--------------------------------------------------------------------------------
1 | x = 5
2 | y = 55
3 |
4 | print(x, y)
5 |
6 |
7 | def f():
8 | x = 5
9 | return x
10 |
11 | def f2():
12 | 5 + "5"
13 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-01/code/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-01/code/.DS_Store
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-05/code/text.utf16:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-05/code/text.utf16
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-05/code/text.utf32:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-05/code/text.utf32
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-09/packaging1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-09/packaging1.pdf
--------------------------------------------------------------------------------
/slides_sources/source/_static/color_git_prompt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/color_git_prompt.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_master_branch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_master_branch.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_merge_commit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_merge_commit.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/remotes_upstream.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/remotes_upstream.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/two_line_prompt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/two_line_prompt.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/virtualenv_prompt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/virtualenv_prompt.png
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-01/PythonOrigins.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-01/PythonOrigins.jpg
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_checkout_branch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_checkout_branch.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_checkout_master.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_checkout_master.png
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_simple_timeline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_simple_timeline.png
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-10/code/example.cfg:
--------------------------------------------------------------------------------
1 | [Section1]
2 | int = 15
3 | bool = true
4 | float = 3.1415
5 |
6 | [Section2]
7 | int = 32
8 | bool = False
9 | float = 1.4235
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_commit_on_branch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_commit_on_branch.png
--------------------------------------------------------------------------------
/slides_sources/source/supplements/ICanEatGlass.utf16.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/supplements/ICanEatGlass.utf16.txt
--------------------------------------------------------------------------------
/Examples/Session07/class.py:
--------------------------------------------------------------------------------
1 | class C:
2 | x = 5
3 |
4 | def __init__(self, y):
5 | self.y = y
6 |
7 | def meth(self, z):
8 | return self.x + self.y + z
9 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-09/PackagingTimeline.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-09/PackagingTimeline.pdf
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_new_commit_on_master.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_new_commit_on_master.png
--------------------------------------------------------------------------------
/slides_sources/source/supplements/index.rst:
--------------------------------------------------------------------------------
1 | **********************
2 | Supplemental Materials
3 | **********************
4 |
5 | .. toctree::
6 | :maxdepth: 1
7 |
8 | unicode
9 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-01/presentation-week01.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-01/presentation-week01.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-02/presentation-week02.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-02/presentation-week02.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-03/presentation-week03.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-03/presentation-week03.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-04/presentation-week-04.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-04/presentation-week-04.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-05/presentation-week-05.log:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-05/presentation-week-05.log
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-05/presentation-week-05.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-05/presentation-week-05.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-06/presentation-week-06.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-06/presentation-week-06.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-07/presentation-week-07.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-07/presentation-week-07.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-08/presentation-week-08.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-08/presentation-week-08.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-09/presentation-week-09.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-09/presentation-week-09.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-10/presentation-week-10.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-10/presentation-week-10.pdf
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-08.5/presentation-wxpython.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-08.5/presentation-wxpython.pdf
--------------------------------------------------------------------------------
/slides_sources/source/_static/git_another_commit_on_branch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/source/_static/git_another_commit_on_branch.png
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-06/code/lambda/lambda_keyword.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-06/code/lambda/lambda_keyword.pyc
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-08.5/code/address_book_solution/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/UWPCE-PythonCert/IntroToPython-2014/HEAD/slides_sources/old_versions/week-08.5/code/address_book_solution/.DS_Store
--------------------------------------------------------------------------------
/Examples/Session07/class_demo.py:
--------------------------------------------------------------------------------
1 |
2 | class C:
3 | x = 5
4 |
5 | def __init__(self, y):
6 | self.y = y
7 |
8 | def meth(self, z):
9 | C.x = z
10 | return self.x + self.y + z
11 |
--------------------------------------------------------------------------------
/slides_sources/requirements.txt:
--------------------------------------------------------------------------------
1 | Jinja2
2 | MarkupSafe
3 | Pygments
4 | Sphinx
5 | docutils
6 | sphinx-rtd-theme
7 | hieroglyph
8 | #-e git+https://github.com/nyergler/hieroglyph.git#egg=hieroglyph
9 | libsass
10 | ipython
11 |
12 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-09/code/capitalize/test/test_text_file.txt:
--------------------------------------------------------------------------------
1 | This is a really simple Text file.
2 | It is here so that I can test the capitalize script.
3 |
4 | And that's only there to try out distutils.
5 |
6 | So there.
7 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-08/code/circle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """
4 | circle class --
5 |
6 | fill this in so it will pass all the tests.
7 | """
8 |
9 | import math
10 |
11 | class Circle(object):
12 | pass
13 |
--------------------------------------------------------------------------------
/Examples/Session02/factorial.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin python3
2 |
3 | """
4 | Simple factorial function -- to demostrate recursion
5 | """
6 |
7 |
8 | def fact(n):
9 | if n == 0:
10 | return 1
11 | else:
12 | return n * fact(n-1)
13 |
--------------------------------------------------------------------------------
/Examples/Session03/module_reload.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | """
4 | a really simple module to use to test reloading
5 | """
6 |
7 | this = "this2"
8 | that = "that"
9 |
10 | def print_something():
11 | print "I'm printing something else"
12 |
13 |
--------------------------------------------------------------------------------
/Examples/Session04/format_example.py:
--------------------------------------------------------------------------------
1 | def print_me( nums ):
2 | formatter = "the first %d numbers are: " + ", ".join( ["%i"] * len(nums) )
3 | print "formatter: ", formatter
4 | print formatter%(( len(nums), ) + nums)
5 |
6 | print_me( (2,3,4,5) )
7 |
8 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/readme.rst:
--------------------------------------------------------------------------------
1 | Old versions of the class materials
2 | ====================================
3 |
4 | These are the versinos of the class materials from 2013 -- since updated
5 | and moved to the Sphinx/Hieroglyph documentation system.
6 |
7 |
--------------------------------------------------------------------------------
/slides_sources/source/include.rst:
--------------------------------------------------------------------------------
1 |
2 | .. |instructor_1_name| replace:: Christopher Barker
3 | .. |instructor_1_email| replace:: PythonCHB@gmail.com
4 |
5 | .. |instructor_2_name| replace:: Maria McKinley
6 | .. |instructor_2_email| replace:: maria@mariakathryn.net
7 |
--------------------------------------------------------------------------------
/slides_sources/old_versions/week-03/code/module_reload.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | """
4 | a really simple module to use to test reloading
5 | """
6 |
7 | this = "this2"
8 | that = "that"
9 |
10 | def print_something():
11 | print "I'm printing something else"
12 |
13 |
--------------------------------------------------------------------------------
/Examples/Session07/html_render/test_html_output1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text
4 | And here is another piece of text -- you should be able to add any number
5 |
--------------------------------------------------------------------------------
/slides_sources/source/_templates/end_slide.html:
--------------------------------------------------------------------------------
1 |
6 |
7 | Thank You!
4 |
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 6 |
7 |8 | And here is another piece of text -- you should be able to add any number 9 |
10 | 11 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/exception_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | example for what happens when you pass non-ascii unicode to a Exception 5 | """ 6 | 7 | msg = u'This is an ASCII-compatible unicode message' 8 | 9 | #msg = u'This is an non ASCII\N{EM DASH}compatible unicode message' 10 | 11 | print "\nDo you see this message in the Exception report?\n" 12 | print msg 13 | print 14 | 15 | raise ValueError(msg) 16 | 17 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/unicode_exception_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | example for what happens when you pass non-ascii unicode to a Exception 5 | """ 6 | 7 | #msg = u'This is an ASCII-compatible unicode message' 8 | 9 | msg = u'This is an non ASCII\N{EM DASH}compatible unicode message' 10 | 11 | print "\nDo you see this message in the Exception report?\n" 12 | print msg 13 | print 14 | 15 | raise ValueError(msg) 16 | 17 | -------------------------------------------------------------------------------- /Examples/Session07/html_render/test_html_output4.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |8 | Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text 9 |
10 | 11 | -------------------------------------------------------------------------------- /Examples/Session10/timer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | timing context manager 5 | """ 6 | 7 | import sys 8 | import time 9 | 10 | class Timer: 11 | def __init__(self, outfile=sys.stdout): 12 | self.outfile = outfile 13 | 14 | def __enter__(self): 15 | self.start = time.time() 16 | 17 | def __exit__(self, exc_type, exc_val, exc_tb): 18 | self.outfile.write("elapsed time:{} seconds".format(time.time() - self.start)) -------------------------------------------------------------------------------- /slides_sources/source/_templates/title_slide.html: -------------------------------------------------------------------------------- 1 |8 | Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text 9 |
10 |8 | Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text 9 |
10 |11 | And here is another piece of text -- you should be able to add any number 12 |
13 | 14 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/static_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | examples of static and class methods 5 | """ 6 | 7 | class C(object): 8 | 9 | def a_static_method(a, b): 10 | print "in a_static_method" 11 | return a+b 12 | a_static_method = staticmethod(a_static_method) 13 | 14 | def test(self): 15 | return self.a_static_method(2,3) 16 | 17 | if __name__ == "__main__": 18 | 19 | print C.a_static_method(3,4) 20 | 21 | c = C() 22 | 23 | print c.a_static_method(4,5) 24 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/yield_example.py: -------------------------------------------------------------------------------- 1 | def counter(): 2 | print 'counter: starting counter' 3 | i = -3 4 | while i < 3: 5 | i = i + 1 6 | print 'counter: yield', i 7 | yield i 8 | 9 | 10 | 11 | if __name__ == '__main__': 12 | print "the generator function:" 13 | print repr(counter) 14 | print "call generator function" 15 | 16 | c = counter() 17 | print "the generator:" 18 | print repr(c) 19 | 20 | print 'iterate' 21 | for item in c: 22 | print 'received:', item 23 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/properties_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | example code for properties 5 | 6 | NOTE: if your getters and setters are this simple: don't do this! 7 | 8 | """ 9 | 10 | class C(object): 11 | _x = None 12 | def getx(self): 13 | return self._x 14 | def setx(self, value): 15 | self._x = value 16 | def delx(self): 17 | del self._x 18 | x = property(getx, setx, delx, "docstring") 19 | 20 | if __name__ == "__main__": 21 | c = C 22 | c.x = 5 23 | print c.x 24 | 25 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/properties_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | example code for properties 5 | 6 | NOTE: if your getters and setters are this simple: don't do this! 7 | 8 | """ 9 | 10 | class C(object): 11 | _x = None 12 | def getx(self): 13 | return self._x 14 | def setx(self, value): 15 | self._x = value 16 | def delx(self): 17 | del self._x 18 | x = property(getx, setx, delx, "docstring") 19 | 20 | if __name__ == "__main__": 21 | c = C 22 | c.x = 5 23 | print c.x 24 | 25 | -------------------------------------------------------------------------------- /Examples/Session09/yield_example.py: -------------------------------------------------------------------------------- 1 | def counter(): 2 | print('counter: starting counter') 3 | i = -3 4 | while i < 3: 5 | i = i + 1 6 | print('counter: yield', i) 7 | yield i 8 | return None 9 | 10 | 11 | # if __name__ == '__main__': 12 | # print "the generator function:" 13 | # print repr(counter) 14 | # print "call generator function" 15 | 16 | # c = counter() 17 | # print "the generator:" 18 | # print repr(c) 19 | 20 | # print 'iterate' 21 | # for item in c: 22 | # print 'received:', item 23 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/static_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | examples of static and class methods 5 | """ 6 | 7 | class C(object): 8 | 9 | def a_static_method(a, b): 10 | print "in a_static_method" 11 | return a+b 12 | a_static_method = staticmethod(a_static_method) 13 | 14 | def test(self): 15 | return self.a_static_method(2,3) 16 | 17 | if __name__ == "__main__": 18 | 19 | print C.a_static_method(3,4) 20 | 21 | c = C() 22 | 23 | print c.a_static_method(4,5) 24 | 25 | -------------------------------------------------------------------------------- /Examples/Session06/closure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example code for closures / currying 5 | """ 6 | 7 | from functools import partial 8 | 9 | 10 | def counter(start_at=0): 11 | count = [start_at] 12 | 13 | def incr(): 14 | count[0] += 1 15 | return count[0] 16 | return incr 17 | 18 | 19 | def power(base, exponent): 20 | """returns based raised to the given exponent""" 21 | return base ** exponent 22 | 23 | # now some specialized versions: 24 | 25 | square = partial(power, exponent=2) 26 | cube = partial(power, exponent=3) 27 | -------------------------------------------------------------------------------- /Examples/Session09/closure.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example code for closures / currying 5 | """ 6 | 7 | from functools import partial 8 | 9 | 10 | def counter(start_at=0): 11 | count = [start_at] 12 | 13 | def incr(): 14 | count[0] += 1 15 | return count[0] 16 | return incr 17 | 18 | 19 | def power(base, exponent): 20 | """returns based raised to the given exponent""" 21 | return base ** exponent 22 | 23 | # now some specialized versions: 24 | 25 | square = partial(power, exponent=2) 26 | cube = partial(power, exponent=3) 27 | -------------------------------------------------------------------------------- /Examples/Session07/html_render/test_html_output6.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |8 | Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text 9 |
10 |{}
".format(string) 11 | return string 12 | return func 13 | 14 | 15 | class tag_wrapper: 16 | def __init__(self, tag): 17 | self.tag = tag 18 | 19 | def __call__(self, orig_func): 20 | def func(*args, **kwargs): 21 | string = orig_func(*args, **kwargs) 22 | string = "<{tag}> {s} {tag}>".format(tag=self.tag, s=string) 23 | return string 24 | return func 25 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/class_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | example of a class method 5 | """ 6 | 7 | class C(object): 8 | def __init__(self, x, y): 9 | self.x = x 10 | self.y = y 11 | 12 | def a_class_method(klass, y): 13 | print "in a_class_method", klass 14 | return klass( y, y**2 ) 15 | a_class_method = classmethod(a_class_method) 16 | 17 | class C2(C): 18 | pass 19 | 20 | 21 | if __name__ == "__main__": 22 | 23 | c = C(3, 4) 24 | print type(c), c.x, c.y 25 | 26 | c2 = C.a_class_method(3) 27 | print type(c2), c2.x, c2.y 28 | 29 | c3 = C2.a_class_method(2) 30 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/class_method.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | example of a class method 5 | """ 6 | 7 | 8 | class C(object): 9 | def __init__(self, x, y): 10 | self.x = x 11 | self.y = y 12 | 13 | def a_class_method(klass, y): 14 | print "in a_class_method", klass 15 | return klass(y, y**2) 16 | a_class_method = classmethod(a_class_method) 17 | 18 | 19 | class C2(C): 20 | pass 21 | 22 | 23 | if __name__ == "__main__": 24 | 25 | c = C(3, 4) 26 | print type(c), c.x, c.y 27 | 28 | c2 = C.a_class_method(3) 29 | print type(c2), c2.x, c2.y 30 | 31 | c3 = c2.a_class_method(2) 32 | print type(c3), c3.x, c3.y 33 | -------------------------------------------------------------------------------- /Examples/Session03/slicing_lab.py: -------------------------------------------------------------------------------- 1 | # slicing lab 2 | 3 | 4 | def swap(seq): 5 | return seq[-1:]+seq[1:-1]+seq[:1] 6 | 7 | 8 | assert swap('something') == 'gomethins' 9 | assert swap(tuple(range(10))) == (9,1,2,3,4,5,6,7,8,0) 10 | 11 | def rem(seq): 12 | return seq[::2] 13 | 14 | assert rem('a word') == 'awr' 15 | 16 | def rem4(seq): 17 | return seq[4:-4:2] 18 | 19 | print(rem4( (1,2,3,4,5,6,7,8,9,10,11), ) ) 20 | 21 | def reverse(seq): 22 | return seq[::-1] 23 | 24 | print(reverse('a string')) 25 | 26 | def thirds(seq): 27 | i = len(seq)//3 28 | #return seq[i*2:i*3+1] + seq[:i] + seq[i:i*2] 29 | return seq[i:-i] + seq[-i:] + seq[:i] 30 | 31 | print (thirds(tuple(range(12)))) 32 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-01/code/split_student_names.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | fr = open('C:\Users\Josh\PYTHON100\courseenrollees 9-30-13 - Sheet1.csv') 4 | lines = fr.readlines()[1:] 5 | fr.close() 6 | 7 | #print(type(lines)) 8 | #print(len(lines)) 9 | 10 | studentNames = [] 11 | for line in lines: 12 | segments = line.split(',') 13 | studentNames.append(segments[0] + ", " + segments[1]) 14 | 15 | # Python is smart enough to not keep on appending to this file when run multiple times 16 | # (use the 'a' flag if you DO want to append) 17 | 18 | fw = open('C:\Users\Josh\PYTHON100\IntroToPython\week-01\students.txt', 'w') 19 | 20 | for name in studentNames: 21 | fw.write(name + '\n') 22 | fw.close() -------------------------------------------------------------------------------- /slides_sources/old_versions/week-09/code/capitalize/scripts/cap_script.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | A really simple script just to demonstrate disutils 5 | """ 6 | 7 | import sys, os 8 | from capitalize import capital_mod 9 | 10 | 11 | if __name__ == "__main__": 12 | try: 13 | infilename = sys.argv[1] 14 | except IndexError: 15 | print "you need to pass in a file to process" 16 | 17 | root, ext = os.path.splitext(infilename) 18 | outfilename = root + "_cap" + ext 19 | 20 | # do the real work: 21 | print "Capitalizing: %s and storing it in %s"%(infilename, outfilename) 22 | capital_mod.capitalize(infilename, outfilename) 23 | 24 | print "I'm done" 25 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/json_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example of how to save data as json 5 | 6 | """ 7 | 8 | import json 9 | 10 | outfilename = "add_book_data.json" 11 | 12 | # get the data from the py file 13 | from add_book_data import AddressBook 14 | 15 | # dump it as json (it's really this simple) 16 | json.dump(AddressBook, open(outfilename, 'wb') ) 17 | #json.dump(AddressBook, open(outfilename, 'wb'), indent=4 ) # specifying indent pretty-prints the json 18 | 19 | ### see if we can re-load it 20 | 21 | AddressBook2 = json.load( open(outfilename, 'rb') ) 22 | 23 | if AddressBook2 == AddressBook: 24 | print "json version is the same as the original" 25 | 26 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08.5/code/basic_app_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example of the very basic, minimal framework for a wxPython application. 5 | """ 6 | 7 | import wx 8 | 9 | class TestFrame(wx.Frame): 10 | def __init__(self, *args, **kwargs): 11 | kwargs.setdefault('title', "Simple test App") 12 | wx.Frame.__init__(self, *args, **kwargs) 13 | 14 | 15 | class TestApp(wx.App): 16 | def OnInit(self): 17 | """ 18 | App initilization goes here -- not much to do in this case 19 | """ 20 | f = TestFrame(None) 21 | f.Show() 22 | 23 | return True 24 | 25 | if __name__ == "__main__": 26 | app = TestApp(False) 27 | app.MainLoop() 28 | 29 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-09/code/capitalize/capitalize/capital_mod.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | A really simple module, just to demonstrate disutils 5 | """ 6 | 7 | def capitalize(infilename, outfilename): 8 | """ 9 | reads the contents of infilename, and writes it to outfilename, but with 10 | every word capitalized 11 | 12 | note: very primitive -- it will mess some files up! 13 | 14 | this is called by the capitalize script 15 | """ 16 | infile = open(infilename, 'U') 17 | outfile = open(outfilename, 'w') 18 | 19 | for line in infile: 20 | outfile.write( " ".join( [word.capitalize() for word in line.split() ] ) ) 21 | outfile.write("\n") 22 | 23 | return None -------------------------------------------------------------------------------- /slides_sources/source/exercises/slicing.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_slicing: 2 | 3 | *********** 4 | Slicing Lab 5 | *********** 6 | 7 | Goal 8 | ==== 9 | 10 | Get the basics of sequence slicing down 11 | 12 | Tasks 13 | ----- 14 | 15 | Write some functions that: 16 | 17 | * return a sequence with the first and last items exchanged. 18 | * return a sequence with every other item removed 19 | * return a sequence with the first and last 4 items removed, and every other item in between 20 | * return a sequence reversed (just with slicing) 21 | * return a sequence with the middle third, then last third, then the first third in the new order 22 | 23 | NOTE: 24 | these should work with ANY sequence -- but you can use strings to test, if you like. 25 | 26 | -------------------------------------------------------------------------------- /Examples/Session06/safe_input.py: -------------------------------------------------------------------------------- 1 | def safe_input(): 2 | try: 3 | the_input = input("\ntype something >>> ") 4 | except (KeyboardInterrupt, EOFError) as error: 5 | print("the error: ", error) 6 | error.extra_info = "extra info for testing" 7 | # raise 8 | return None 9 | return the_input 10 | 11 | def main(): 12 | safe_input() 13 | 14 | def divide(x,y): 15 | try: 16 | return x/y 17 | except ZeroDivisionError as err: 18 | print("you put in a zero!!!") 19 | print("the exeption:", err) 20 | err.args = (("very bad palce for a zero",)) 21 | err.extra_stuff = "all kinds of things" 22 | raise 23 | 24 | # if __name__ == '__main__': 25 | # main() -------------------------------------------------------------------------------- /slides_sources/old_versions/week-03/code/mail_merge_solution.py: -------------------------------------------------------------------------------- 1 | data = ( ('George', 'a goldfish'), 2 | ('Joe', 'several small pieces of lint'), 3 | ('Jennifer','a red wagon') 4 | ) 5 | 6 | template = """ 7 | Dear %s, 8 | 9 | Thank you so much for your gift of %s. I will treasure it 10 | forever. I've always wanted an excuse to get %s, and now I 11 | don't have to pay for it! 12 | 13 | Please enjoy this form letter as a token of my sincere appreciation. 14 | """ 15 | 16 | for name, gift in data: 17 | print 'Filling template for %s' % name 18 | message = template%(name, gift, gift) 19 | file_name = 'thank_you_%s.txt' % name.lower() 20 | f = open(file_name, 'w') 21 | f.write(message) 22 | f.close() 23 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-05/code/codingbat_unittest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | test file for codingbat module 5 | 6 | This version used unittest 7 | """ 8 | 9 | import unittest 10 | from codingbat import sleep_in 11 | 12 | class Test_sleep_in(unittest.TestCase): 13 | 14 | def test_false_false(self): 15 | self.assertTrue( sleep_in(False, False) ) 16 | 17 | def test_true_false(self): 18 | self.assertFalse( sleep_in(True, False) ) 19 | 20 | def test_false_true(self): 21 | self.assertTrue( sleep_in(False, True) ) 22 | 23 | def test_true_true(self): 24 | self.assertTrue( sleep_in(True, True) ) 25 | 26 | if __name__ == "__main__": 27 | unittest.main() 28 | 29 | -------------------------------------------------------------------------------- /Examples/Suppliments/text.utf8: -------------------------------------------------------------------------------- 1 | Origin (in native language) Name (in native language) 2 | Հայաստան Արամ Խաչատրյան 3 | Australia Nicole Kidman 4 | Österreich Johann Strauß 5 | Azərbaycan Vaqif Səmədoğlu 6 | Азәрбајҹан Вагиф Сәмәдоғлу 7 | Azərbaycan Heydər Əliyev 8 | Азәрбајҹан Һејдәр Әлијев 9 | België René Magritte 10 | Belgique René Magritte 11 | Belgien René Magritte 12 | বাংলা সুকুমার রায় 13 | འབྲུག་ཡུལ། མགོན་པོ་རྡོ་རྗེ། 14 | ប្រទេសកម្ពុជា ព្រះពុទ្ឋឃោសាចារ្យជួនណាត 15 | Canada Céline Dion 16 | ᓄᓇᕗᒻᒥᐅᑦ ᓱᓴᓐ ᐊᒡᓗᒃᑲᖅ 17 | -------------------------------------------------------------------------------- /Examples/Session05/test_pytest_parameter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | pytest example of a parameterized test 5 | 6 | NOTE: there is a failure in here! can you fix it? 7 | 8 | """ 9 | import pytest 10 | 11 | 12 | # a (really simple) function to test 13 | def add(a, b): 14 | """ 15 | returns the sum of a and b 16 | """ 17 | return a + b 18 | 19 | # now some test data: 20 | 21 | test_data = [((2, 3), 5), 22 | ((-3, 2), -1), 23 | ((2, 0.5), 2.5), 24 | (("this", "that"), "this that"), 25 | (([1, 2, 3], [6, 7, 8]), [1, 2, 3, 6, 7, 8]), 26 | ] 27 | 28 | 29 | @pytest.mark.parametrize(("input", "result"), test_data) 30 | def test_add(input, result): 31 | assert add(*input) == result 32 | -------------------------------------------------------------------------------- /Examples/Session06/test_pytest_parameter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | pytest example of a parameterized test 5 | 6 | NOTE: there is a failure in here! can you fix it? 7 | 8 | """ 9 | import pytest 10 | 11 | 12 | # a (really simple) function to test 13 | def add(a, b): 14 | """ 15 | returns the sum of a and b 16 | """ 17 | return a + b 18 | 19 | # now some test data: 20 | 21 | test_data = [((2, 3), 5), 22 | ((-3, 2), -1), 23 | ((2, 0.5), 2.5), 24 | (("this", "that"), "this that"), 25 | (([1, 2, 3], [6, 7, 8]), [1, 2, 3, 6, 7, 8]), 26 | ] 27 | 28 | 29 | @pytest.mark.parametrize(("input", "result"), test_data) 30 | def test_add(input, result): 31 | assert add(*input) == result 32 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/text.utf8: -------------------------------------------------------------------------------- 1 | Origin (in native language) Name (in native language) 2 | Հայաստան Արամ Խաչատրյան 3 | Australia Nicole Kidman 4 | Österreich Johann Strauß 5 | Azərbaycan Vaqif Səmədoğlu 6 | Азәрбајҹан Вагиф Сәмәдоғлу 7 | Azərbaycan Heydər Əliyev 8 | Азәрбајҹан Һејдәр Әлијев 9 | België René Magritte 10 | Belgique René Magritte 11 | Belgien René Magritte 12 | বাংলা সুকুমার রায় 13 | འབྲུག་ཡུལ། མགོན་པོ་རྡོ་རྗེ། 14 | ប្រទេសកម្ពុជា ព្រះពុទ្ឋឃោសាចារ្យជួនណាត 15 | Canada Céline Dion 16 | ᓄᓇᕗᒻᒥᐅᑦ ᓱᓴᓐ ᐊᒡᓗᒃᑲᖅ 17 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-06/code/lambda/lambda_keyword_solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | example code for using lambda, keywords, and keyword scope 5 | 6 | 7 | The challenge: 8 | 9 | Write a function that returns a list of n functions, 10 | such that each one, when called, will return the input value, 11 | incremented by an increaseing number. 12 | 13 | you should use a for loop, lambda, and a keyword argument 14 | 15 | extra credit: do it with a list comprhension, instead of a for loop 16 | 17 | """ 18 | 19 | def function_builder(n): 20 | 21 | l = [] 22 | for i in range(n): 23 | l.append( lambda x, i=i: x+i ) 24 | return l 25 | 26 | def function_builder2(n): 27 | 28 | return [ lambda x, i=i: x+i for i in range(n) ] 29 | 30 | -------------------------------------------------------------------------------- /Examples/Session09/iterator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Simple iterator examples 5 | """ 6 | 7 | 8 | class IterateMe_1(object): 9 | """ 10 | About as simple an iterator as you can get: 11 | 12 | returns the sequence of numbers from zero to 4 13 | ( like range(4) ) 14 | """ 15 | def __init__(self, stop=5): 16 | self.current = -1 17 | self.stop = stop 18 | def __iter__(self): 19 | return self 20 | def __next__(self): 21 | self.current += 1 22 | if self.current < self.stop: 23 | return self.current 24 | else: 25 | raise StopIteration 26 | 27 | if __name__ == "__main__": 28 | 29 | print("Testing the iterator") 30 | for i in IterateMe_1(): 31 | print(i) 32 | 33 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08.5/code/address_book/a_book.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "phone": "123-456-8888", 4 | "first_name": "Chris", 5 | "last_name": "Barker", 6 | "email": "PythonCHB@gmail.com" 7 | }, 8 | { 9 | "phone": "510-555-1234", 10 | "first_name": "Fred", 11 | "last_name": "Jones", 12 | "email": "FredJones@some_company.com" 13 | }, 14 | { 15 | "phone": "423-321-9876", 16 | "first_name": "Nancy", 17 | "last_name": "Wilson", 18 | "email": "Wilson.Nancy@gmail.com" 19 | }, 20 | { 21 | "phone": "555-555-5555", 22 | "first_name": "Charles", 23 | "last_name": "Dickens", 24 | "email": "chuck@victorian.england.com" 25 | } 26 | ] -------------------------------------------------------------------------------- /slides_sources/old_versions/week-05/code/test_pytest_parameter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | pytest example of a parameterized test 5 | 6 | NOTE: there is a failure in here! can you fix it? 7 | 8 | """ 9 | import pytest 10 | 11 | # a (really simple) function to test 12 | def add(a, b): 13 | """ 14 | returns the sum of a and b 15 | """ 16 | return a + b 17 | 18 | # now some test data: 19 | 20 | test_data = [ ( ( 2, 3), 5), 21 | ( (-3, 2), -1), 22 | ( ( 2, 0.5), 2.5), 23 | ( ( "this", "that"), "this that"), 24 | ( ( [1,2,3], [6,7,8]), [1,2,3,6,7,8]), 25 | ] 26 | 27 | @pytest.mark.parametrize(("input", "result"), test_data) 28 | def test_add(input, result): 29 | assert add(*input) == result 30 | 31 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08.5/code/address_book_solution/a_book.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "phone": "123-456-8888", 4 | "first_name": "Chris", 5 | "last_name": "Barker", 6 | "email": "PythonCHB@gmail.com" 7 | }, 8 | { 9 | "phone": "510-555-1234", 10 | "first_name": "Fred", 11 | "last_name": "Jones", 12 | "email": "FredJones@some_company.com" 13 | }, 14 | { 15 | "phone": "423-321-9876", 16 | "first_name": "Nancy", 17 | "last_name": "Wilson", 18 | "email": "Wilson.Nancy@gmail.com" 19 | }, 20 | { 21 | "phone": "555-555-5555", 22 | "first_name": "Charles", 23 | "last_name": "Dickens", 24 | "email": "chuck@victorian.england.com" 25 | } 26 | ] -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/iterator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Simple iterator examples 5 | """ 6 | 7 | 8 | class IterateMe_1(object): 9 | """ 10 | About as simple an iterator as you can get: 11 | 12 | returns the sequence of numbers from zero to 4 13 | ( like xrange(4) ) 14 | """ 15 | def __init__(self, stop=5): 16 | self.current = -1 17 | self.stop = stop 18 | def __iter__(self): 19 | return self 20 | def next(self): 21 | self.current += 1 22 | if self.current < self.stop: 23 | return self.current 24 | else: 25 | raise StopIteration 26 | 27 | if __name__ == "__main__": 28 | 29 | print "first version" 30 | for i in IterateMe_1(): 31 | print i 32 | 33 | -------------------------------------------------------------------------------- /slides_sources/source/exercises/exceptions_lab.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_exceptions_lab: 2 | 3 | ************** 4 | Exceptions Lab 5 | ************** 6 | 7 | Learning Exceptions 8 | =================== 9 | 10 | Just a little bit for the basics. 11 | 12 | Exceptions Lab 13 | --------------- 14 | 15 | Improving ``input`` 16 | 17 | * The ``input()`` function can generate two exceptions: ``EOFError`` 18 | or ``KeyboardInterrupt`` on end-of-file(EOF) or canceled input. 19 | 20 | * Create a wrapper function, perhaps ``safe_input()`` that returns ``None`` 21 | rather rather than raising these exceptions, when the user enters ``^C`` for Keyboard Interrupt, or ``^D`` (``^Z`` on Windows) for End Of File. 22 | 23 | * Update your mailroom program to use exceptions (and IBAFP) to handle 24 | malformed numeric input 25 | 26 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-02/code/distance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | A version of TP's distance -- showing tuple unpacking 5 | 6 | """ 7 | 8 | import math 9 | 10 | something = 3 11 | 12 | # TP's version: 13 | def distance(x1, y1, x2, y2): 14 | dx = x2 - x1 15 | dy = y2 - y1 16 | dsquared = dx**2 + dy**2 17 | result = math.sqrt(dsquared) 18 | return result 19 | 20 | # my version: 21 | def distance2( pt1, pt2 ): 22 | dx = pt2[0] - pt1[0] 23 | dy = pt2[1] - pt1[1] 24 | dsquared = dx**2 + dy**2 25 | result = math.sqrt(dsquared) 26 | return result 27 | 28 | # my version: 29 | def distance3( (x1, y1), (x2, y2) ): 30 | 31 | dx = x2 - x1 32 | dy = y2 - y1 33 | dsquared = dx**2 + dy**2 34 | result = math.sqrt(dsquared) 35 | return result 36 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-09/code/context_manager/timer_context.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | timer_context 5 | 6 | A context manager that does simpel code timing 7 | 8 | Adapted from: 9 | 10 | http://preshing.com/20110924/timing-your-code-using-pythons-with-statement/ 11 | 12 | 13 | NOTE: this is only good for crude timing -- use the timeit module to do it better. 14 | """ 15 | 16 | import time 17 | 18 | class Timer(object): 19 | def __enter__(self): 20 | pass 21 | def __exit__(self, *args): 22 | pass 23 | 24 | 25 | if __name__ == "__main__": 26 | 27 | # hard to write proper unit tests for this... 28 | 29 | with Timer() as t: 30 | for i in range(100000): 31 | i = i**20 32 | 33 | print t.interval 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Examples/Suppliments/ICanEatGlass.utf8.txt: -------------------------------------------------------------------------------- 1 | I Can Eat Glass: 2 | 3 | And from the sublime to the ridiculous, here is a certain phrase in an assortment of languages: 4 | 5 | Sanskrit: काचं शक्नोम्यत्तुम् । नोपहिनस्ति माम् ॥ 6 | 7 | Sanskrit (standard transcription): kācaṃ śaknomyattum; nopahinasti mām. 8 | 9 | Classical Greek: ὕαλον ϕαγεῖν δύναμαι· τοῦτο οὔ με βλάπτει. 10 | 11 | Greek (monotonic): Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. 12 | 13 | Greek (polytonic): Μπορῶ νὰ φάω σπασμένα γυαλιὰ χωρὶς νὰ πάθω τίποτα. 14 | 15 | Latin: Vitrum edere possum; mihi non nocet. 16 | 17 | Old French: Je puis mangier del voirre. Ne me nuit. 18 | 19 | French: Je peux manger du verre, ça ne me fait pas mal. 20 | 21 | Provençal / Occitan: Pòdi manjar de veire, me nafrariá pas. 22 | 23 | Québécois: J'peux manger d'la vitre, ça m'fa pas mal. -------------------------------------------------------------------------------- /slides_sources/build_gh_pages.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # simple script to build and push to gh-pages 4 | # designed to be run from master 5 | 6 | # To use this script you need another copy of the repo, right next this 7 | # one, but named "IntroToPython.gh-pages" 8 | # this script builds the docs, then copies them to the other repo 9 | # then pushes that to gitHub 10 | 11 | GHPAGESDIR=../../IntroToPython.gh-pages/ 12 | 13 | # make sure the Gh pages repo is there and in the right branch 14 | pushd $GHPAGESDIR 15 | git checkout gh-pages 16 | popd 17 | 18 | # make the docs 19 | make html 20 | # copy to other repo (on the gh-pages branch) 21 | cp -R build/html/ $GHPAGESDIR 22 | 23 | pushd $GHPAGESDIR 24 | git add * # in case there are new files added 25 | git commit -a -m "updating presentation materials" 26 | git pull -s ours --no-edit 27 | git push 28 | 29 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/ICanEatGlass.utf8.txt: -------------------------------------------------------------------------------- 1 | I Can Eat Glass: 2 | 3 | And from the sublime to the ridiculous, here is a certain phrase in an assortment of languages: 4 | 5 | Sanskrit: काचं शक्नोम्यत्तुम् । नोपहिनस्ति माम् ॥ 6 | 7 | Sanskrit (standard transcription): kācaṃ śaknomyattum; nopahinasti mām. 8 | 9 | Classical Greek: ὕαλον ϕαγεῖν δύναμαι· τοῦτο οὔ με βλάπτει. 10 | 11 | Greek (monotonic): Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. 12 | 13 | Greek (polytonic): Μπορῶ νὰ φάω σπασμένα γυαλιὰ χωρὶς νὰ πάθω τίποτα. 14 | 15 | Latin: Vitrum edere possum; mihi non nocet. 16 | 17 | Old French: Je puis mangier del voirre. Ne me nuit. 18 | 19 | French: Je peux manger du verre, ça ne me fait pas mal. 20 | 21 | Provençal / Occitan: Pòdi manjar de veire, me nafrariá pas. 22 | 23 | Québécois: J'peux manger d'la vitre, ça m'fa pas mal. -------------------------------------------------------------------------------- /Examples/Session06/codingbat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Examples from: http://codingbat.com 5 | 6 | Put here so we can write unit tests for them ourselves 7 | """ 8 | 9 | # Python > Warmup-1 > sleep_in 10 | 11 | # The parameter weekday is True if it is a weekday, and the parameter 12 | # vacation is True if we are on vacation. 13 | # 14 | # We sleep in if it is not a weekday or we're on vacation. 15 | # Return True if we sleep in. 16 | 17 | 18 | def sleep_in(weekday, vacation): 19 | return not weekday or vacation 20 | 21 | 22 | # We have two monkeys, a and b, and the parameters a_smile and b_smile 23 | # indicate if each is smiling. 24 | 25 | # We are in trouble if they are both smiling or if neither of them is 26 | # smiling. 27 | 28 | # Return True if we are in trouble. 29 | 30 | def monkey_trouble(a_smile, b_smile): 31 | return a_smile is b_smile 32 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/circle_solution1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | circle class -- my solution to the firt part of the exercise 5 | 6 | test code to run it is in test_circle1.py 7 | """ 8 | 9 | import math 10 | 11 | class Circle(object): 12 | def __init__(self, radius): 13 | self.radius = radius 14 | 15 | def _get_d(self): 16 | return self.radius * 2 17 | def _set_d(self, d): 18 | self.radius = d / 2.0 19 | diameter = property(_get_d, _set_d, doc="The diameter of the circle") 20 | 21 | def _get_area(self): 22 | return math.pi * self.radius**2 23 | area = property(_get_area, doc="The area of the circle") 24 | 25 | # alternate constructor that takes diameter 26 | def from_diameter(klass, d): 27 | return klass(d / 2.0) 28 | from_diameter = classmethod(from_diameter) 29 | 30 | 31 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-02/code/fib_solution.py: -------------------------------------------------------------------------------- 1 | #/usr/bin/env python 2 | 3 | def fib(n): 4 | """ 5 | recursive function that computes Fibonacci numbers 6 | """ 7 | if n == 0: 8 | return 0 9 | elif n == 1: 10 | return 1 11 | else: 12 | return fib(n-1) + fib(n-2) 13 | 14 | def fib2(n): 15 | """ 16 | non-recusive function that computes fibonacci numbers 17 | """ 18 | if n == 0: 19 | return 0 20 | if n == 1: 21 | return 1 22 | else: 23 | minus_2 = 0 24 | minus_1 = 1 25 | for i in range(2, n+1): 26 | result = minus_2 + minus_1 27 | minus_2, minus_1 = minus_1, result 28 | return result 29 | 30 | 31 | print fib(0), 32 | print fib(1), 33 | print fib(2), 34 | print fib(3), 35 | print fib(4), 36 | print fib(5), 37 | print fib(6), 38 | print fib(7), 39 | 40 | 41 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-06/code/lambda/lambda_keyword.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | example code for using lambda, keywords, and keyword scope 5 | 6 | The challenge: 7 | 8 | Write a function that returns a list of n functions, 9 | such that each one, when called, will return the input value, 10 | incremented by an increaseing number. 11 | 12 | you should use a for loop, lambda, and a keyword argument 13 | 14 | Not clear? here's what you should get: 15 | 16 | In [96]: the_list = function_builder(4) 17 | 18 | In [97]: the_list[0](2) 19 | Out[97]: 2 20 | 21 | In [98]: the_list[1](2) 22 | Out[98]: 3 23 | 24 | In [100]: for f in the_list: 25 | print f(5) 26 | .....: 27 | 5 28 | 6 29 | 7 30 | 8 31 | 32 | extra credit: do it with a list comprhension, instead of a for loop 33 | 34 | """ 35 | 36 | def function_builder(n): 37 | ## put somethingin here... 38 | pass 39 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-05/presentation-week-05.vrb: -------------------------------------------------------------------------------- 1 | \frametitle {Homework}\par Recommended Reading: 2 | \begin{itemize} 3 | \item TP: ch 15-18 4 | \item LPTHW: Ex 40 - 45 5 | \item Dive Into Python: chapter 4, 5 6 | \end{itemize} 7 | 8 | Do: 9 | \begin{itemize} 10 | \item Finish (or re-factor) the Labs you didn't finish in class. 11 | \item Write some unit tests for a couple of the functions you've 12 | written for previous excercises (Or something new) 13 | \item Using the unit tests you jsut wrote, refactor the above functions 14 | using list and/or dict comprehensions. 15 | \item Write a script which does something useful (to you) and reads and writes 16 | files. Very, very small scope is good. something useful at work would 17 | be great, but no job secrets! 18 | \item Start thinking about what you want to do for your project! 19 | \end{itemize} 20 | 21 | 22 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/indent_etree.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | indenting function to pretty-print an ElementTree 4 | 5 | from: 6 | 7 | http://infix.se/2007/02/06/gentlemen-indent-your-xml 8 | 9 | why the %*#^ this isn't built-in to etree is beyond me. 10 | 11 | usage: 12 | 13 | indent(tree.getroot()) 14 | 15 | tree.write(outfilename) 16 | 17 | """ 18 | 19 | def indent(elem, level=0): 20 | i = "\n" + level*" " 21 | if len(elem): 22 | if not elem.text or not elem.text.strip(): 23 | elem.text = i + " " 24 | for e in elem: 25 | indent(e, level+1) 26 | if not e.tail or not e.tail.strip(): 27 | e.tail = i + " " 28 | if not e.tail or not e.tail.strip(): 29 | e.tail = i 30 | else: 31 | if level and (not elem.tail or not elem.tail.strip()): 32 | elem.tail = i 33 | 34 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-05/code/test_random_nose.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | port of the random unit tests from the python docs to nose/py.test 5 | """ 6 | 7 | import random 8 | import nose.tools 9 | 10 | seq = range(10) 11 | 12 | def test_shuffle(): 13 | # make sure the shuffled sequence does not lose any elements 14 | random.shuffle(seq) 15 | seq.sort() 16 | print seq 17 | assert seq == range(8) 18 | 19 | @nose.tools.raises(TypeError) 20 | def test_shuffle_immutable(): 21 | # should raise an exception for an immutable sequence 22 | random.shuffle( (1,2,3) ) 23 | 24 | def test_choice(): 25 | element = random.choice(seq) 26 | assert (element in seq) 27 | 28 | def test_sample(): 29 | for element in random.sample(seq, 5): 30 | assert element in seq 31 | 32 | @nose.tools.raises(ValueError) 33 | def test_sample_too_large(): 34 | random.sample(seq, 20) 35 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-05/code/test_random_pytest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | port of the random unit tests from the python docs to nose/py.test 5 | """ 6 | 7 | import random 8 | import pytest 9 | 10 | 11 | seq = range(10) 12 | 13 | def test_shuffle(): 14 | # make sure the shuffled sequence does not lose any elements 15 | random.shuffle(seq) 16 | seq.sort() 17 | print "seq:", seq 18 | ## expect this to fail -- so we can see the output. 19 | assert seq == range(10) 20 | 21 | def test_shuffle_immutable(): 22 | pytest.raises(TypeError, random.shuffle, (1,2,3) ) 23 | 24 | def test_choice(): 25 | element = random.choice(seq) 26 | assert (element in seq) 27 | 28 | def test_sample(): 29 | for element in random.sample(seq, 5): 30 | assert element in seq 31 | 32 | def test_sample_too_large(): 33 | with pytest.raises(ValueError): 34 | random.sample(seq, 20) 35 | -------------------------------------------------------------------------------- /Examples/Session07/html_render/sample_html.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |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 11 |
12 |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 11 |
12 |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 11 |
12 |9 | Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text 10 |
11 |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 11 |
12 |this is a string
' 16 | 17 | def test_with_args(): 18 | @p_wrapper 19 | def f_string(a, b, this=45 ): 20 | return "the numbers are: {}, {}, {}".format(a,b,this) 21 | 22 | assert f_string(2, 3, this=54) == "the numbers are: 2, 3, 54
" 23 | 24 | 25 | # #Extra credit: 26 | 27 | def test_tag_wrapper(): 28 | @tag_wrapper('html') 29 | def return_a_string(string): 30 | return string 31 | 32 | assert return_a_string("this is a string") == " this is a string " 33 | 34 | def test_tag_wrapper2(): 35 | @tag_wrapper('div') 36 | def return_a_string(string): 37 | return string 38 | 39 | assert return_a_string("this is a string") == "tag: 6 | 7 | @p_wrapper 8 | def func(): 9 | " simplest example possible" 10 | return "this is the returned string" 11 | 12 | >> func() 13 | 14 | "
this is the returned string
" 15 | 16 | """ 17 | 18 | # the simple decorator 19 | 20 | def p_wrapper(func): 21 | ## put decorator here 22 | pass 23 | 24 | 25 | 26 | """ 27 | 28 | Fancier decorator using a class: 29 | 30 | This lets you make a decorator with some custom input 31 | 32 | the argument to the __init__ sets what tag you want, which creates a custom decorator. 33 | 34 | the __call__ method is the decorator itself. 35 | 36 | """ 37 | 38 | class tag_wrapper(object): 39 | def __init__(self, tag='p' ): 40 | """ 41 | inititilze the decorator class with the tag you want 42 | """ 43 | pass 44 | def __call__(self, func, *args, **kwargs): 45 | """ 46 | The actual decorator function. 47 | """ 48 | pass 49 | # return a_function... 50 | 51 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/switch_case.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Spelling switch/case with a dictionary 5 | """ 6 | 7 | """ 8 | A switch/case example: 9 | switch(n) { 10 | case 0: 11 | printf("You typed zero.\n"); 12 | break; 13 | case 1: 14 | case 9: 15 | printf("n is a perfect square\n"); 16 | break; 17 | case 2: 18 | printf("n is an even number\n"); 19 | case 3: 20 | case 5: 21 | case 7: 22 | printf("n is a prime number\n"); 23 | break; 24 | case 4: 25 | printf("n is a perfect square\n"); 26 | case 6: 27 | case 8: 28 | printf("n is an even number\n"); 29 | break; 30 | default: 31 | printf("Only single-digit numbers are allowed\n"); 32 | break; 33 | } 34 | """ 35 | def zero(): 36 | return "You typed zero.\n" 37 | 38 | def sqr(): 39 | return "n is a perfect square\n" 40 | 41 | def even(): 42 | return "n is an even number\n" 43 | 44 | def prime(): 45 | return "n is a prime number\n" 46 | 47 | options = { 0 : zero, 48 | 1 : sqr, 49 | 4 : sqr, 50 | 9 : sqr, 51 | 2 : even, 52 | 3 : prime, 53 | 5 : prime, 54 | 7 : prime, 55 | } 56 | 57 | print options[2]() 58 | 59 | print options[4]() 60 | 61 | -------------------------------------------------------------------------------- /Examples/Session08/vector.py: -------------------------------------------------------------------------------- 1 | """ 2 | Vector type with +, * redefined as Vector addition and dot product 3 | From Jon Jacky's Intro to Python course: 4 | http://staff.washington.edu/jon/python-course/ 5 | """ 6 | 7 | 8 | class Vector(list): 9 | def __repr__(self): 10 | """ 11 | String representation, uses list (superclass) representation 12 | """ 13 | return 'Vector(%s)' % super(Vector, self).__repr__() 14 | 15 | def __add__(self, v): 16 | """ 17 | redefine + as element-wise Vector sum 18 | """ 19 | assert len(self) == len(v) 20 | return Vector([x1 + x2 for x1, x2 in zip(self, v)]) 21 | 22 | def __mul__(self, v): 23 | """ 24 | redefine * as Vector dot product 25 | """ 26 | assert len(self) == len(v) 27 | return sum([x1 * x2 for x1, x2 in zip(self, v)]) 28 | 29 | l1 = [1, 2, 3] 30 | l2 = [4, 5, 6] 31 | v1 = Vector(l1) 32 | v2 = Vector(l2) 33 | 34 | if __name__ == '__main__': 35 | print('l1') 36 | print(l1) 37 | print('l1 + l2') 38 | print(l1 + l2) 39 | # print(l1 * l2) # TypeError 40 | print('zip(l1, l2)') 41 | print(zip(l1, l2)) 42 | print('v1') 43 | print(v1) 44 | print('v1 + v2') 45 | print(v1 + v2) 46 | print('v1 * v2') 47 | print(v1 * v2) 48 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/vector.py: -------------------------------------------------------------------------------- 1 | """ 2 | Vector type with +, * redefined as vector addition and dot product 3 | From Jon Jacky's Intro to Python course: 4 | http://staff.washington.edu/jon/python-course/ 5 | """ 6 | 7 | 8 | class vector(list): 9 | def __repr__(self): 10 | """ 11 | String representation, uses list (superclass) representation 12 | """ 13 | return 'vector(%s)' % super(vector, self).__repr__() 14 | 15 | def __add__(self, v): 16 | """ 17 | redefine + as element-wise vector sum 18 | """ 19 | assert len(self) == len(v) 20 | return vector([x1 + x2 for x1, x2 in zip(self, v)]) 21 | 22 | def __mul__(self, v): 23 | """ 24 | redefine * as vector dot product 25 | """ 26 | assert len(self) == len(v) 27 | return sum([x1 * x2 for x1, x2 in zip(self, v)]) 28 | 29 | l1 = [1, 2, 3] 30 | l2 = [4, 5, 6] 31 | v1 = vector(l1) 32 | v2 = vector(l2) 33 | 34 | if __name__ == '__main__': 35 | print 'l1' 36 | print l1 37 | print 'l1 + l2' 38 | print l1 + l2 39 | # print l1 * l2 # TypeError 40 | print 'zip(l1, l2)' 41 | print zip(l1, l2) 42 | print 'v1' 43 | print v1 44 | print 'v1 + v2' 45 | print v1 + v2 46 | print 'v1 * v2' 47 | print v1 * v2 48 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/test_iterator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | tests for the iterator solutions 5 | """ 6 | 7 | from iterator_1 import IterateMe_1 8 | from iterator_2_solution import IterateMe_2 9 | from iterator_3_solution import IterateMe_3 10 | 11 | def test_1(): 12 | l = [] 13 | for i in IterateMe_1(4): 14 | l.append(i) 15 | print l 16 | assert l == [0, 1, 2, 3] 17 | 18 | def test_3a(): 19 | l = [] 20 | for i in IterateMe_3(1, 4): 21 | l.append(i) 22 | print l 23 | assert l == [1, 2, 3] 24 | 25 | def test_3b(): 26 | l = [] 27 | for i in IterateMe_3(0, 3): 28 | l.append(i) 29 | print l 30 | assert l == [0, 1, 2] 31 | 32 | def test_3c(): 33 | l = [] 34 | for i in IterateMe_3(2, 10, 2): 35 | l.append(i) 36 | print l 37 | assert l == [2, 4, 6, 8] 38 | 39 | def test_3_break(): 40 | """ 41 | this tests if the iterator re-sets itself when called again. 42 | """ 43 | iter = IterateMe_3(2,10,2) 44 | 45 | l = [] 46 | for i in iter: 47 | l.append(i) 48 | if i > 4: break 49 | print l 50 | assert l == [2, 4, 6] 51 | 52 | ## doing it again should give the same result 53 | ## i.e. the iterator should reset when it its used again 54 | l = [] 55 | for i in iter: 56 | l.append(i) 57 | if i > 4: break 58 | print l 59 | assert l == [2, 4, 6] 60 | 61 | 62 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/vector.py: -------------------------------------------------------------------------------- 1 | """ 2 | Vector type with +, * redefined as vector addition and dot product 3 | From Jon Jacky's Intro to Python course: 4 | http://staff.washington.edu/jon/python-course/ 5 | """ 6 | 7 | 8 | class vector(list): 9 | def __repr__(self): 10 | """ 11 | String representation, uses list (superclass) representation 12 | """ 13 | return 'vector(%s)' % super(vector, self).__repr__() 14 | 15 | def __add__(self, v): 16 | """ 17 | redefine + as element-wise vector sum 18 | """ 19 | assert len(self) == len(v) 20 | return vector([x1 + x2 for x1, x2 in zip(self, v)]) 21 | 22 | def __mul__(self, v): 23 | """ 24 | redefine * as vector dot product 25 | """ 26 | assert len(self) == len(v) 27 | return sum([x1 * x2 for x1, x2 in zip(self, v)]) 28 | 29 | l1 = [1, 2, 3] 30 | l2 = [4, 5, 6] 31 | v1 = vector(l1) 32 | v2 = vector(l2) 33 | 34 | if __name__ == '__main__': 35 | print 'l1' 36 | print l1 37 | print 'l1 + l2' 38 | print l1 + l2 39 | # print l1 * l2 # TypeError 40 | print 'zip(l1, l2)' 41 | print zip(l1, l2) 42 | print 'v1' 43 | print v1 44 | print 'v1 + v2' 45 | print v1 + v2 46 | print 'v1 * v2' 47 | print v1 * v2 48 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-09/code/context_manager/timer_context.rst: -------------------------------------------------------------------------------- 1 | A context manager as a simple timer 2 | ##################################### 3 | 4 | See if you can write a context manger that will time some code. 5 | 6 | When using it, you can do:: 7 | 8 | with timer: 9 | this_is_some_code_to_run() 10 | how_long_might_it_take 11 | 12 | 13 | and you'll get something like:: 14 | 15 | this code took 0.12 seconds 16 | 17 | NOTE: 18 | ------- 19 | 20 | you can do simple timing with the time module. Without a context, you'd do:: 21 | 22 | import time 23 | 24 | start_time = time.clock() 25 | 26 | run_some_code_here 27 | 28 | run_time = time.clock - start_time 29 | print "this code took %f seconds"%run_time) 30 | 31 | But isn't:: 32 | with Timer(): 33 | 34 | easier? 35 | 36 | 37 | NOTE2: 38 | ------- 39 | 40 | The context manager's __exit__() method is called with three arguments, the exception details (type, value, traceback): the same values returned by sys.exc_info(), which can also be None if no exception occurred). 41 | 42 | If you do'nt want to do anytihng special with exceptions, youc an ignore them, but the __exit__ method msut take something:: 43 | 44 | def __exit__(self, *args) 45 | your_code_that 46 | ignors_exceptions 47 | 48 | 49 | will do fine... -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/xml_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example of how to save data as xml, using the element tree module 5 | 6 | This version stores all the data as attributes 7 | 8 | """ 9 | 10 | import xml.etree.ElementTree as ET 11 | from indent_etree import indent # for prettier output 12 | 13 | outfilename = "add_book_data.xml" 14 | 15 | # get the data from the py file 16 | from add_book_data_flat import AddressBook 17 | 18 | # build a tree structure 19 | root = ET.Element("address_book") 20 | 21 | # add the elements: 22 | for person in AddressBook: 23 | p = ET.SubElement(root, "person") 24 | # This method stores everything in attributes 25 | for key,value in person.items(): 26 | p.set(key, value) 27 | 28 | # wrap it in an ElementTree instance, and save as XML 29 | tree = ET.ElementTree(root) 30 | 31 | indent(tree.getroot()) # to make it more pretty 32 | tree.write(outfilename) 33 | 34 | ### See if we can re-load it 35 | 36 | tree = ET.parse(outfilename) 37 | book = tree.getroot() 38 | # re-build the original list: 39 | AddressBook2 = [] 40 | for person in book.getchildren(): 41 | #print person.attrib 42 | AddressBook2.append(person.attrib) 43 | 44 | if AddressBook2 == AddressBook: 45 | print "xml version is the same as the original" 46 | 47 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/pickle_example2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example of how to save custom classes in a pickle 5 | """ 6 | 7 | import cPickle as pickle 8 | 9 | outfilename = "circles.pickle" 10 | 11 | ### You can pickle a custom class, too: 12 | # remember the Circle class? 13 | 14 | import circle 15 | 16 | # create a couple of circles: 17 | 18 | C1 = circle.Circle(radius=2) 19 | print C1 20 | 21 | C2 = circle.Circle(radius=3.4) 22 | print C2 23 | 24 | # put them in a dict: 25 | circles = {'circle1': C1, 26 | 'circle2': C2} 27 | 28 | #print circles 29 | 30 | ## pickle the list 31 | pickle.dump(circles, open(outfilename, 'wb') ) 32 | 33 | ### see if we can re-load it 34 | 35 | ## Note: the circle module needs to be available when you load the pickle 36 | circles2 = pickle.load( open(outfilename, 'rb') ) 37 | 38 | # Haven't defined compare for the circle class: 39 | ## extra credit -- add compare method (__cmp__) to Circle class 40 | same = True 41 | for c1, c2 in zip(circles.values(), circles2.values()): 42 | if c1.radius != c2.radius: 43 | same = False 44 | break 45 | 46 | if same: 47 | print "pickled/unpickled version is the same as the original" 48 | else: 49 | print "not the same" 50 | print circles 51 | print circles2 -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/generator_solution.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def intsum(): # 1 + 2 + 3 + 4 + 5... 5 | """ 6 | simplest solution 7 | """ 8 | a = b = 0 9 | while True: 10 | yield b 11 | a += 1 12 | b = b + a 13 | 14 | def intsum2(): # 1 + 2 + 3 + 4 + 5... 15 | """ 16 | takes advantage of some clever math 17 | """ 18 | a = 0 19 | while True: 20 | yield (a * (a + 1)) / 2 21 | a += 1 22 | 23 | 24 | def doubler(): # 1, 2, 4, 8, 16, 32, 64... 25 | a = 1 26 | while True: 27 | yield a 28 | a = a * 2 29 | 30 | 31 | def fib(): # 1, 1, 2, 3, 5, 8, 13, 21, 34... 32 | a, b = 0, 1 33 | while True: 34 | yield b 35 | a, b = b, a + b 36 | 37 | def prime(): # 2, 3, 5, 7, 11, 13, 17, 19, 23... 38 | a = 2 39 | while True: 40 | yield a 41 | p = False 42 | while not p: # while not prime 43 | a += 1 # try the next integer 44 | p = True # assume it is prime... 45 | for x in xrange(2, int(math.floor(math.sqrt(a))) + 1): 46 | if a % x == 0: 47 | p = False # ...unless it isn't 48 | break 49 | 50 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-02/homework_solution.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | """ 4 | Chris' Solution to The Ackermann function 5 | """ 6 | 7 | def ack(m,n): 8 | """ 9 | Solution to the Ackerman function 10 | 11 | http://en.wikipedia.org/wiki/Ackermann_function 12 | 13 | This one simply follows the logic laid out in the definition 14 | 15 | """ 16 | 17 | if m<0 or n<0: 18 | return "Solution is not Defined" 19 | 20 | if m == 0: 21 | return n+1 22 | elif n == 0 and m > 0: 23 | return ack(m-1, 1) 24 | else: 25 | return ack(m-1, ack(m, n-1)) 26 | 27 | 28 | def ack2(m,n): 29 | """ 30 | Solution to the Ackerman function 31 | 32 | http://en.wikipedia.org/wiki/Ackermann_function 33 | 34 | This one uses nested conditional expressions: 35 | Don't try this at home! 36 | 37 | """ 38 | 39 | if m<0 or n<0: 40 | return "Solution is not Defined" 41 | else: 42 | return n+1 if m==0 else ( 43 | ack2(m-1, 1) if (n == 0 and m > 0) else ( 44 | ack2(m-1, ack2(m, n-1) ) 45 | ) 46 | ) 47 | 48 | 49 | 50 | # tests: 51 | print ack(2,3) 52 | 53 | for m in range(-1, 4): 54 | for n in range(-1, 5): 55 | print " the result of ack", (m,n), "is", ack(m,n) 56 | print " the result of ack2", (m,n), "is", ack2(m,n) 57 | 58 | 59 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/iterator_3_solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Simple iterator examples 5 | """ 6 | 7 | class IterateMe_3(object): 8 | """ 9 | Almost a replacement for xrange: 10 | 11 | IterateMe_3 (start, stop, step=1) 12 | 13 | returns the sequence of numbers from start (inclusive) to stop (exclusive), 14 | skipping every step number 15 | 16 | ( like xrange(start, stop, step) ) 17 | 18 | This version re-sets itself when used again. 19 | """ 20 | def __init__(self, start, stop, step=1): 21 | self.start = start 22 | self.stop = stop 23 | self.step = step 24 | self.current = start-step 25 | def __iter__(self): 26 | self.current = self.start-self.step 27 | return self 28 | def next(self): 29 | self.current += self.step 30 | if self.current < self.stop: 31 | return self.current 32 | else: 33 | raise StopIteration 34 | 35 | if __name__ == "__main__": 36 | 37 | print "Test the usual" 38 | for i in IterateMe_3(3, 11, 2): 39 | print i 40 | 41 | print "This one is different when broken out of" 42 | it = IterateMe_3(3, 11, 2) 43 | for i in it: 44 | if i > 8: 45 | break 46 | print i 47 | 48 | print "we pick up again from the beginning" 49 | for i in it: 50 | print i 51 | 52 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-09/code/decorators/p_wrapper_solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python decorator example 3 | 4 | Simple decorator that turns any function that returns a string 5 | into one that returns that string wrapped in the htmltag: 6 | 7 | @p_wrapper 8 | def func(): 9 | " simplest example possible" 10 | return "this is the returned string" 11 | 12 | func() 13 | 14 | """ 15 | 16 | # the simple decorator 17 | 18 | def p_wrapper(func): 19 | def function(*args, **kwargs): 20 | result = func(*args, **kwargs) 21 | return "
" + result + "
" 22 | return function 23 | 24 | """ 25 | 26 | Fancier decorator using a class: 27 | 28 | this lets you make a decorator with some custom input 29 | the argument to the __init__ sets what tag you want 30 | this creates a custom decorator 31 | the __call__ method is the decorator itself. 32 | 33 | """ 34 | 35 | class tag_wrapper(object): 36 | def __init__(self, tag='p' ): 37 | """ 38 | inititilze the decorator class with the tag you want 39 | """ 40 | self.open_tag = "<%s> "%tag 41 | self.close_tag = " %s>"%tag 42 | 43 | def __call__(self, func, *args, **kwargs): 44 | """ 45 | The actual decorator function. 46 | 47 | using lambda - 'cause why not? 48 | """ 49 | return lambda *args, **kwargs: self.open_tag + func(*args, **kwargs) + self.close_tag 50 | 51 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-01/code/schedule.txt: -------------------------------------------------------------------------------- 1 | week 2: Antoun, Jo-Anne: python (GIS) 2 | week 2: Onen, Omer: matlab, skil 3 | week 2: Small, Edward (Ryan): python, JS 4 | week 2: Warren, Catherine: SQL 5 | week 3: Flagg, Nate: basic, pascal, C, c#, TCL 6 | week 3: Rakita, Joshua C# Java Python JavaScript 7 | week 3: Wright, Duane 8 | week 3: name languages 9 | week 4: Eaton, Sako: php, sql 10 | week 4: Ivers, Brandon: ruby, 11 | week 4: Pei, Guangyu (gary): C, C++ 12 | week 4: Savage, Nathan: py3, PHP, 13 | week 5: Chhen, Rithy: PHP, java, JS, SQL 14 | week 5: Edson, Howard: SQL, C++ 15 | week 5: Kang, Dong: Java 16 | week 5: Werner, Steven: javascript 17 | week 6: Chan, Lawrence: VB 18 | week 6: Colwell, Kimberly: pascal 19 | week 6: Petrova, Maria: R, SQL 20 | week 6: Tran, Linh: html, java 21 | week 7: Rajagopalan, Sridharan: C, Java, C++ 22 | week 7: Salkodu Parameshwar, Maitri: C, C++, bash 23 | week 7: Smith, Richard: C++, Java, XML, Shell 24 | week 7: Thach, Phuc: all of them: php, JS 25 | week 8: Barker, Chris Python C C++ Shell Fortran Pascal 26 | week 8: Cypret, Luke: bash, python, sql 27 | week 8: Moore, Blane: C++, java 28 | week 8: Parrish, Brent: python, JS 29 | week 9: AuBuchon, Harlan: py (java) 30 | week 9: Gapasin, Anne-Lynn: java, C#, perl, XML, assembly 31 | week 9: Popish, Mario: shell 32 | week 9: Schmitz, Brian: javascript, PHP 33 | week 10: Bae, Andrew: pascal, C, C# 34 | week 10: Grizzel, Travis: shell, 35 | week 10: Leblanc, Adam: C, C++, ADA, Java, C# 36 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/iterator_2_solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Simple iterator examples 5 | """ 6 | 7 | class IterateMe_2(object): 8 | """ 9 | Almost a replacement for xrange: 10 | 11 | Iterate_2(start, stop, step=1) 12 | 13 | returns the sequence of numbers from start (inclusive) to stop (exclusive), 14 | skipping every step number 15 | ( like xrange(start, stop, step) ) 16 | 17 | """ 18 | def __init__(self, start, stop, step=1): 19 | self.current = start-step 20 | self.stop = stop 21 | self.step = step 22 | def __iter__(self): 23 | return self 24 | def next(self): 25 | self.current += self.step 26 | if self.current < self.stop: 27 | return self.current 28 | else: 29 | raise StopIteration 30 | 31 | 32 | if __name__ == "__main__": 33 | 34 | print "second version" 35 | for i in IterateMe_2(0, 5): 36 | print i 37 | 38 | print "second version with a different start" 39 | for i in IterateMe_2(4, 7): 40 | print i 41 | 42 | print "second version with a different step" 43 | for i in IterateMe_2(2, 20, 2): 44 | print i 45 | 46 | print "But what if we break out of it:" 47 | it = IterateMe_2(2, 20, 2) 48 | for i in it: 49 | if i > 10: 50 | break 51 | print i 52 | 53 | print "And then pick up again" 54 | for i in it: 55 | print i 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Examples/Session06/test_cigar_party.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | When squirrels get together for a party, they like to have cigars. 5 | A squirrel party is successful when the number of cigars is between 6 | 40 and 60, inclusive. Unless it is the weekend, in which case there 7 | is no upper bound on the number of cigars. 8 | 9 | Return True if the party with the given values is successful, 10 | or False otherwise. 11 | """ 12 | 13 | 14 | # you can change this import to test different versions 15 | from cigar_party import cigar_party 16 | # from cigar_party import cigar_party2 as cigar_party 17 | # from cigar_party import cigar_party3 as cigar_party 18 | 19 | 20 | def test_1(): 21 | assert cigar_party(30, False) is False 22 | 23 | 24 | def test_2(): 25 | 26 | assert cigar_party(50, False) is True 27 | 28 | 29 | def test_3(): 30 | 31 | assert cigar_party(70, True) is True 32 | 33 | 34 | def test_4(): 35 | assert cigar_party(30, True) is False 36 | 37 | 38 | def test_5(): 39 | assert cigar_party(50, True) is True 40 | 41 | 42 | def test_6(): 43 | assert cigar_party(60, False) is True 44 | 45 | 46 | def test_7(): 47 | assert cigar_party(61, False) is False 48 | 49 | 50 | def test_8(): 51 | assert cigar_party(40, False) is True 52 | 53 | 54 | def test_9(): 55 | assert cigar_party(39, False) is False 56 | 57 | 58 | def test_10(): 59 | assert cigar_party(40, True) is True 60 | 61 | 62 | def test_11(): 63 | assert cigar_party(39, True) is False 64 | 65 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-03/code/string_formatting_solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | String formatting lab: 5 | 6 | """ 7 | # Rewrite: "the first 3 numbers are: %i, %i, %i"%(1,2,3) 8 | # for an arbitrary number of numbers... 9 | 10 | # solution 1 11 | # the goal was to demonstrate dynamic building of format strings: 12 | 13 | # create the numbers 14 | numbers = [32, 56, 34, 12, 48, 18] 15 | 16 | # build the format string for the numbers: 17 | formatter = " %i," * len(numbers) 18 | 19 | formatter = formatter[:-1] # take the extra comma off the end 20 | 21 | # put it together with the rest of the string 22 | formatter = "the first %i numbers are: %s"%(len(numbers), formatter) 23 | 24 | # use it: 25 | # the format operator needs a tuple 26 | # tuple(seq) will make a tuple out of any sequence 27 | print formatter%tuple(numbers) 28 | 29 | # solution 2 30 | # in class, a couple people realized that str() would make a nice string from 31 | # a list or tuple 32 | 33 | numbers_str = str(numbers)[1:-1] # make a string, remove the brackets 34 | # put it together with the rest of the string 35 | print "the first %i numbers are: %s"%(len(numbers), numbers_str) 36 | 37 | ##### 38 | # Write a format string that will take: 39 | # ( 2, 123.4567, 10000) 40 | # and produce: 41 | # 'file_002 : 123.46, 1e+04' 42 | ##### 43 | 44 | t = (2, 123.4567, 10000) 45 | print "file_%03i, %10.2f, %.3g"%t 46 | 47 | # could use '%e' for the last one, too -- I like '%g' -- it does significant figures... 48 | -------------------------------------------------------------------------------- /Examples/Session10/context_managers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import sys 3 | from io import StringIO 4 | from contextlib import contextmanager 5 | 6 | 7 | class Context(object): 8 | """from Doug Hellmann, PyMOTW 9 | http://pymotw.com/2/contextlib/#module-contextlib 10 | """ 11 | def __init__(self, handle_error): 12 | print('__init__({})'.format(handle_error)) 13 | self.handle_error = handle_error 14 | 15 | def __enter__(self): 16 | print('__enter__()') 17 | return self 18 | 19 | def __exit__(self, exc_type, exc_val, exc_tb): 20 | print('__exit__({}, {}, {})'.format(exc_type, exc_val, exc_tb)) 21 | if exc_type == ZeroDivisionError: 22 | return True 23 | else: 24 | return False 25 | 26 | # return self.handle_error 27 | 28 | @contextmanager 29 | def context(boolean): 30 | print("__init__ code here") 31 | try: 32 | print("__enter__ code goes here") 33 | yield object() 34 | except Exception as e: 35 | print("errors handled here") 36 | if not boolean: 37 | raise e 38 | finally: 39 | print("__exit__ cleanup goes here") 40 | 41 | 42 | @contextmanager 43 | def print_encoded(encoding): 44 | old_stdout = sys.stdout 45 | sys.stdout = buff = StringIO() 46 | try: 47 | yield None 48 | finally: 49 | sys.stdout = old_stdout 50 | buff.seek(0) 51 | raw = buff.read() 52 | encoded = raw.encode(encoding) 53 | print(encoded) 54 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-01/homework1_solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Chris' solution to the week 1 homework problem. 5 | 6 | Note that we hadn't talked about loops yet, so this is a solution with no loops. 7 | 8 | Note also that there is nore than one way to skin a cat -- or code a function 9 | """ 10 | 11 | 12 | def print_grid(size): 13 | """ 14 | print a 2x2 grid with a total size of size 15 | 16 | :param size: total size of grid -- it will be rounded if not onemore than a multiple of 2 17 | """ 18 | N = 2 19 | s = int( (size-1) // 2 ) # size of one grid box 20 | print "s:", s 21 | # top row 22 | top = ('+ ' + '- '*s)*N + '+' + '\n' 23 | middle = ('| ' + ' '*2*s)*N + '|' + '\n' 24 | 25 | row = top + middle*s 26 | 27 | grid = row*N + top 28 | 29 | print grid 30 | 31 | 32 | def print_grid2(N, s): 33 | """ 34 | print a NxN grid with each box of size s 35 | 36 | :param N: number of grid boxes (row and column) 37 | 38 | :param s: size of each grid box 39 | """ 40 | # top row 41 | top = ('+ ' + '- '*s)*N + '+' + '\n' 42 | middle = ('| ' + ' '*2*s)*N + '|' + '\n' 43 | 44 | row = top + middle*s 45 | 46 | grid = row*N + top 47 | 48 | print grid 49 | 50 | def print_grid3(size): 51 | """ 52 | same as print_grid, but calling print_grid2 to do the work 53 | """ 54 | N = 2 55 | s = (size-1) / 2 # size of one grid box 56 | print_grid2(N, s) 57 | 58 | print_grid(11) 59 | print_grid(7) 60 | 61 | print_grid2(3,3) 62 | print_grid2(3,5) 63 | 64 | print_grid3(11) 65 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08.5/code/address_book/switcher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | A custom widget to switch between different entries in the address book 5 | 6 | Subclassed from a wx.Panel 7 | """ 8 | 9 | import wx 10 | 11 | class Switcher(wx.Panel): 12 | def __init__(self, parent, *args, **kwargs): 13 | """ 14 | create a new switcher instance. 15 | 16 | :param parent: the parent frame -- this is designed to go on an 17 | AddBookFrame object 18 | 19 | 20 | :params *args, **kwargs: all the other arguments that a wx.Window takes. 21 | """ 22 | wx.Panel.__init__(self, parent, *args, **kwargs) 23 | 24 | self.add_book_frame = parent 25 | 26 | ## add some widgets here to do the switching 27 | 28 | 29 | def onPrev(self, evt=None): 30 | # save the data in the form 31 | print "in onPrev" 32 | self.add_book_frame.previous() 33 | def onNext(self, evt=None): 34 | # restore the form 35 | print "in onNext" 36 | self.add_book_frame.next() 37 | 38 | class TestFrame(wx.Frame): 39 | """ 40 | simple Frame with jsut enough to text the Switcher 41 | """ 42 | def next(self): 43 | print "next() called in frame" 44 | def previous(self): 45 | print "previous() called in frame" 46 | 47 | # I like to have a little test app so it can be run on its own 48 | if __name__ == "__main__": 49 | 50 | app = wx.App(False) 51 | f = TestFrame(None) 52 | p = Switcher(f) 53 | f.Show() 54 | app.MainLoop() 55 | 56 | 57 | -------------------------------------------------------------------------------- /slides_sources/source/exercises/fizz_buzz.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_fizz_buzz: 2 | 3 | ****************** 4 | Fizz Buzz Exercise 5 | ****************** 6 | 7 | The Classic Fizz Buzz Problem 8 | ============================== 9 | 10 | .. rst-class:: left 11 | 12 | Fizz Buzz is a classic simple problem in computer science. 13 | 14 | Often used as an exercise in interviews for programmers. 15 | 16 | Apparently a LOT of people applying for jobs as profesional developers can't do this in an interview: 17 | 18 | (http://c2.com/cgi/wiki?FizzBuzzTest) 19 | 20 | Now that I've psyched you out -- it's really pretty straightforward. 21 | 22 | Goal: 23 | ----- 24 | 25 | * Write a program that prints the numbers from 1 to 100 inclusive. 26 | 27 | * But for multiples of three print "Fizz" instead of the number 28 | 29 | * For the multiples of five print "Buzz". 30 | 31 | * For numbers which are multiples of both three and five print "FizzBuzz" instead. 32 | 33 | Hint: 34 | ----- 35 | 36 | * Look up the ``%`` operator. What do these do? 37 | 38 | * ``10 % 7`` 39 | * ``14 % 7`` 40 | 41 | (try that in iPython) 42 | 43 | * **Do** try to write a solution *before* looking it up -- there are a million nifty solutions posted on the web, but you'll learn a lot more if you figure it out on your own first. 44 | 45 | Results: 46 | -------- 47 | 48 | Running your code should result in something like:: 49 | 50 | 1 51 | 2 52 | Fizz 53 | 4 54 | Buzz 55 | Fizz 56 | 7 57 | 8 58 | Fizz 59 | Buzz 60 | 11 61 | Fizz 62 | 13 63 | 14 64 | FizzBuzz 65 | 16 66 | .... 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /slides_sources/source/exercises/lambda_magic.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_lambda_magic: 2 | 3 | ************************ 4 | lambda and keyword Magic 5 | ************************ 6 | 7 | Goals 8 | ===== 9 | 10 | .. rst-class:: left 11 | 12 | * A bit of lambda 13 | * functions as objects 14 | * keyword evaluation 15 | 16 | 17 | Task 18 | ---- 19 | 20 | Write a function that returns a list of n functions, 21 | such that each one, when called, will return the input value, 22 | incremented by an increasing number. 23 | 24 | Use a for loop, ``lambda``, and a keyword argument 25 | 26 | **Extra credit:** 27 | 28 | Do it with a list comprehension, instead of a for loop 29 | 30 | Not clear? here's what you should get... 31 | 32 | Example calling code 33 | --------------------- 34 | 35 | .. code-block:: ipython 36 | 37 | In [96]: the_list = function_builder(4) 38 | ### so the_list should contain n functions (callables) 39 | In [97]: the_list[0](2) 40 | Out[97]: 2 41 | ## the zeroth element of the list is a function that add 0 42 | ## to the input, hence called with 2, returns 2 43 | In [98]: the_list[1](2) 44 | Out[98]: 3 45 | ## the 1st element of the list is a function that adds 1 46 | ## to the input value, thus called with 2, returns 3 47 | In [100]: for f in the_list: 48 | print(f(5)) 49 | .....: 50 | 5 51 | 6 52 | 7 53 | 8 54 | ### If you loop through them all, and call them, each one adds one more 55 | to the input, 5... i.e. the nth function in the list adds n to the input. 56 | 57 | .. nextslide:: 58 | 59 | See the test code in Examples/Session09 60 | 61 | 62 | -------------------------------------------------------------------------------- /Examples/Session09/test_generator.py: -------------------------------------------------------------------------------- 1 | """ 2 | test_generator.py 3 | 4 | tests the solution to the generator lab 5 | 6 | can be run with py.test or nosetests 7 | """ 8 | 9 | import generator_solution as gen 10 | 11 | 12 | def test_intsum(): 13 | 14 | g = gen.intsum() 15 | 16 | assert next(g) == 0 17 | assert next(g) == 1 18 | assert next(g) == 3 19 | assert next(g) == 6 20 | assert next(g) == 10 21 | assert next(g) == 15 22 | 23 | 24 | def test_intsum2(): 25 | 26 | g = gen.intsum2() 27 | 28 | assert next(g) == 0 29 | assert next(g) == 1 30 | assert next(g) == 3 31 | assert next(g) == 6 32 | assert next(g) == 10 33 | assert next(g) == 15 34 | 35 | 36 | def test_doubler(): 37 | 38 | g = gen.doubler() 39 | 40 | assert next(g) == 1 41 | assert next(g) == 2 42 | assert next(g) == 4 43 | assert next(g) == 8 44 | assert next(g) == 16 45 | assert next(g) == 32 46 | 47 | for i in range(10): 48 | j = next(g) 49 | 50 | assert j == 2**15 51 | 52 | 53 | def test_fib(): 54 | g = gen.fib() 55 | 56 | assert next(g) == 1 57 | assert next(g) == 1 58 | assert next(g) == 2 59 | assert next(g) == 3 60 | assert next(g) == 5 61 | assert next(g) == 8 62 | assert next(g) == 13 63 | assert next(g) == 21 64 | 65 | 66 | def test_prime(): 67 | g = gen.prime() 68 | 69 | assert next(g) == 2 70 | assert next(g) == 3 71 | assert next(g) == 5 72 | assert next(g) == 7 73 | assert next(g) == 11 74 | assert next(g) == 13 75 | assert next(g) == 17 76 | assert next(g) == 19 77 | assert next(g) == 23 78 | 79 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/test_generator.py: -------------------------------------------------------------------------------- 1 | """ 2 | test_generator.py 3 | 4 | tests the solution to the generator lab 5 | """ 6 | 7 | import generator_solution as gen 8 | 9 | def test_intsum(): 10 | 11 | g = gen.intsum() 12 | 13 | assert g.next() == 0 14 | assert g.next() == 1 15 | assert g.next() == 3 16 | assert g.next() == 6 17 | assert g.next() == 10 18 | assert g.next() == 15 19 | 20 | def test_intsum2(): 21 | 22 | g = gen.intsum2() 23 | 24 | assert g.next() == 0 25 | assert g.next() == 1 26 | assert g.next() == 3 27 | assert g.next() == 6 28 | assert g.next() == 10 29 | assert g.next() == 15 30 | 31 | 32 | def test_doubler(): 33 | 34 | g = gen.doubler() 35 | 36 | assert g.next() == 1 37 | assert g.next() == 2 38 | assert g.next() == 4 39 | assert g.next() == 8 40 | assert g.next() == 16 41 | assert g.next() == 32 42 | 43 | for i in range(10): 44 | j = g.next() 45 | 46 | assert j == 2**15 47 | 48 | def test_fib(): 49 | g = gen.fib() 50 | 51 | assert g.next() == 1 52 | assert g.next() == 1 53 | assert g.next() == 2 54 | assert g.next() == 3 55 | assert g.next() == 5 56 | assert g.next() == 8 57 | assert g.next() == 13 58 | assert g.next() == 21 59 | 60 | def test_prime(): 61 | g = gen.prime() 62 | 63 | assert g.next() == 2 64 | assert g.next() == 3 65 | assert g.next() == 5 66 | assert g.next() == 7 67 | assert g.next() == 11 68 | assert g.next() == 13 69 | assert g.next() == 17 70 | assert g.next() == 19 71 | assert g.next() == 23 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /slides_sources/source/exercises/rot13.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_rot13: 2 | 3 | ***** 4 | ROT13 5 | ***** 6 | 7 | Goal 8 | ---- 9 | 10 | Get used to working with the number values for characters 11 | 12 | Get a bit of practice with string methods and string processing 13 | 14 | 15 | ROT13 encryption 16 | ----------------- 17 | 18 | The ROT13 encryption scheme is a simple substitution cypher where each letter 19 | in a text is replace by the letter 13 away from it (imagine the alphabet as a 20 | circle, so it wraps around). 21 | 22 | The task 23 | -------- 24 | 25 | 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. 26 | 27 | This function should preserve whitespace, punctuation and capitalization. 28 | 29 | 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. 30 | 31 | 32 | .. nextslide:: A bit more 33 | 34 | There is a "short-cut" available that will help you accomplish this task. Some 35 | spelunking in `the documentation for strings`_ should help you to find it. If 36 | you do find it, using it is completely fair game. 37 | 38 | As usual, add your new file to your local clone right away. Make commits 39 | early and often and include commit messages that are descriptive and concise. 40 | 41 | When you are done, if you want me to review it, push your changes to github 42 | and issue a pull request. 43 | 44 | try decrypting this: 45 | 46 | "Zntargvp sebz bhgfvqr arne pbeare" 47 | 48 | .. _the documentation for strings: https://docs.python.org/3/library/stdtypes.html#string-methods 49 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-01/homework.rst: -------------------------------------------------------------------------------- 1 | Homework for week 1 (Due week 2) 2 | ================================== 3 | 4 | (adapted from Downey, "Think Python", ex. 3.5) 5 | 6 | 7 | Part 1 8 | ---------- 9 | 10 | Write a function that draws a grid like the following:: 11 | 12 | 13 | + - - - - + - - - - + 14 | | | | 15 | | | | 16 | | | | 17 | | | | 18 | + - - - - + - - - - + 19 | | | | 20 | | | | 21 | | | | 22 | | | | 23 | + - - - - + - - - - + 24 | 25 | Hint: to print more than one value on a line, you can print a comma-separated sequence: 26 | ``print '+', '-'`` 27 | 28 | If the sequence ends with a comma, Python leaves the line unfinished, so the value printed next appears on the same line. 29 | 30 | :: 31 | 32 | print '+', 33 | print '-' 34 | 35 | The output of these statements is ``'+ -'``. 36 | 37 | A print statement all by itself ends the current line and goes to the next line. 38 | 39 | 40 | Part 2: 41 | -------- 42 | 43 | Write a function ``print_grid()`` that takes one integer argument 44 | and prints a grid like the picture above, BUT the size of the 45 | grid is given by the argument. 46 | 47 | For example, ``print_grid(11)`` prints the grid in the above picture. 48 | 49 | This problem is underspecified. Do something reasonable. 50 | 51 | Hints: 52 | 53 | A character is a string of length 1 54 | 55 | ``s + t`` is string ``s`` followed by string ``t`` 56 | 57 | ``s * n`` is string ``s`` replicated n times 58 | 59 | Part 3: 60 | ---------- 61 | 62 | Write a function that draws a similar grid with three rows and three columns. 63 | 64 | (what to do about rounding?) 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-02/code/FizzBuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Fizz Buzz examples -- from most straightforward, to most compact. 5 | """ 6 | 7 | # basic approach: 8 | def fizzbuzz1(n): 9 | for i in range(1, n+1): 10 | if i%3 == 0 and i%5 == 0: 11 | print "FizzBuzz" 12 | elif i%3 == 0: 13 | print "Fizz" 14 | elif i%5 == 0: 15 | print "Buzz" 16 | else: 17 | print i 18 | 19 | def fizzbuzz2(n): 20 | """ 21 | Why evaluate i%3 and i%5 twice? 22 | """ 23 | for i in range(1, n+1): 24 | msg = '' 25 | if i%3 == 0: 26 | msg += "Fizz" 27 | if i%5 == 0: 28 | msg += "Buzz" 29 | if msg: 30 | print msg 31 | else: 32 | print i 33 | 34 | def fizzbuzz3(n): 35 | """ 36 | use conditional expressions: 37 | """ 38 | for i in range(1, n+1): 39 | msg = "Fizz" if i%3 == 0 else '' 40 | msg += "Buzz" if i%5 == 0 else '' 41 | print msg or i 42 | 43 | def fizzbuzz4(n): 44 | """ 45 | the one liner 46 | """ 47 | for i in range(1,n+1): print ( "Fizz" * (not (i%3)) + "Buzz" * (not (i%5)) ) or i 48 | 49 | def fizzbuzz_ruby(n): 50 | """ 51 | This is a one-liner version inspired by the Ruby one-liner 52 | found here: 53 | 54 | http://www.commandercoriander.net/blog/2013/02/03/fizzbuzz-in-one-line 55 | 56 | This uses list comprehensions, and slicing, and is, well, pretty darn ugly! 57 | 58 | """ 59 | for word in [ ("".join(["Fizz",][0:1-i%3]+["Buzz",][0:1-i%5]) or `i`) for i in range(1, n+1)]: print word 60 | 61 | 62 | fizzbuzz1(16) 63 | print 64 | fizzbuzz2(16) 65 | print 66 | fizzbuzz3(16) 67 | print 68 | fizzbuzz4(16) 69 | print 70 | fizzbuzz_ruby(16) 71 | 72 | 73 | -------------------------------------------------------------------------------- /Examples/Session02/codingbat.rst: -------------------------------------------------------------------------------- 1 | 2 | Coding Bat examples 3 | #################### 4 | 5 | Warmup-1 > monkey_trouble 6 | ============================ 7 | 8 | We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble:: 9 | 10 | monkey_trouble(True, True) → True 11 | monkey_trouble(False, False) → True 12 | monkey_trouble(True, False) → False 13 | 14 | 15 | Warmup-1 > sleep_in 16 | ======================= 17 | 18 | The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. 19 | 20 | sleep_in(False, False) → True 21 | sleep_in(True, False) → False 22 | sleep_in(False, True) → True 23 | 24 | 25 | Warmup-1 > diff21 26 | ================= 27 | 28 | Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. 29 | 30 | diff21(19) → 2 31 | diff21(10) → 11 32 | diff21(21) → 0 33 | 34 | Warmup-1 > makes10 35 | =================== 36 | 37 | Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. 38 | 39 | makes10(9, 10) → True 40 | makes10(9, 9) → False 41 | makes10(1, 9) → True 42 | 43 | Logic-1 > cigar_party 44 | ====================== 45 | 46 | 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. 47 | 48 | cigar_party(30, False) → False 49 | cigar_party(50, False) → True 50 | cigar_party(70, True) → True 51 | 52 | -------------------------------------------------------------------------------- /slides_sources/source/exercises/file_lab.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_file_lab: 2 | 3 | ******** 4 | File LAB 5 | ******** 6 | 7 | A bit of practice with files 8 | ============================ 9 | 10 | Goal: 11 | ----- 12 | 13 | Get a little bit of practice with handling files and parsing simple text. 14 | 15 | 16 | Paths and File Processing 17 | -------------------------- 18 | 19 | * write a program which prints the full path to all files in the current 20 | directory, one per line 21 | 22 | * write a program which copies a file from a source, to a destination 23 | (without using shutil, or the OS copy command) 24 | 25 | - advanced: make it work for any size file: i.e. don't read the entire 26 | contents of the file into memory at once. 27 | 28 | - This should work for any kind of file, so you need to open 29 | the files in binary mode: ``open(filename, 'rb')`` (or ``'wb'`` for 30 | writing). Note that for binary files, you can't use ``readline()`` -- 31 | lines don't have any meaning for binary files. 32 | 33 | - Test it with both text and binrary files (maybe jpeg or??) 34 | 35 | 36 | File reading and parsing 37 | ------------------------ 38 | 39 | 40 | In the class repo, in: 41 | 42 | ``Examples/Session01/students.txt`` 43 | 44 | You will find the list I generated in the first class of all the students in the class, and what programming languages they have used in the past. 45 | 46 | Write a little script that reads that file, and generates a list of all 47 | the languages that have been used. 48 | 49 | Extra credit: keep track of how many students specified each language. 50 | 51 | If you've got git set up right, ``git pull upstream master`` should update 52 | your repo. Otherwise, you can get it from gitHub: 53 | 54 | https://github.com/UWPCE-PythonCert/IntroPython2016/blob/master/Examples/Session01/students.txt 55 | 56 | -------------------------------------------------------------------------------- /Examples/Suppliments/latin1_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | An example of using latin-1 as a universal encoding 5 | 6 | latin-1 is a superset of ASCII that is suitable for western european languages. 7 | 8 | Is the most common, and a good default, if you need a one-byte per char encoding 9 | for European text. 10 | 11 | It also has a nice property: 12 | : every byte value from 0 to 255 is avalid charactor 13 | 14 | Thus you will never get an UnicodeDecodeError if 15 | you try to decode arbitrary bytes with latin-1. 16 | 17 | And it can "round-trip" trhough a unicode object. 18 | 19 | This can be useful is you don't know the encoding -- at least it won't break. 20 | It's also useful if you need to work with cobined text+binary data. 21 | 22 | 23 | 24 | """ 25 | 26 | # all the byte values in a bytes (str) object: 27 | all_bytes = ''.join( [chr(i) for i in range(255)] ) 28 | 29 | print type(all_bytes) 30 | print len(all_bytes) 31 | 32 | print "Example value: 20" 33 | print ord(all_bytes[20]) == 20 34 | print "Example high value: 245" 35 | print ord(all_bytes[245]) == 245 36 | 37 | # now decode it to a unicode object: 38 | try: 39 | uni = all_bytes.decode() 40 | except UnicodeDecodeError: 41 | print "OOPS: can't decode with default encoding" 42 | 43 | # latin-1 works: 44 | try: 45 | all_uni = all_bytes.decode('latin-1') 46 | print "Yup -- that worked" 47 | print all_uni 48 | print "note that the ASCII subset is the same..." 49 | except UnicodeDecodeError: 50 | print "OOPS: This should have worked!!" 51 | raise 52 | 53 | ## now show that it round-trips: 54 | all_bytes2 = all_uni.encode('latin-1') 55 | 56 | if all_bytes2 == all_bytes: 57 | print "yup -- that worked...the values are preserved on the round trip." 58 | else: 59 | print "Hey, that should have worked" 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/latin1_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | An example of using latin-1 as a universal encoding 5 | 6 | latin-1 is a superset of ASCII that is suitable for western european languages. 7 | 8 | Is the most common, and a good default, if you need a one-byte per char encoding 9 | for European text. 10 | 11 | It also has a nice property: 12 | : every byte value from 0 to 255 is avalid charactor 13 | 14 | Thus you will never get an UnicodeDecodeError if 15 | you try to decode arbitrary bytes with latin-1. 16 | 17 | And it can "round-trip" trhough a unicode object. 18 | 19 | This can be useful is you don't know the encoding -- at least it won't break. 20 | It's also useful if you need to work with cobined text+binary data. 21 | 22 | 23 | 24 | """ 25 | 26 | # all the byte values in a bytes (str) object: 27 | all_bytes = ''.join( [chr(i) for i in range(255)] ) 28 | 29 | print type(all_bytes) 30 | print len(all_bytes) 31 | 32 | print "Example value: 20" 33 | print ord(all_bytes[20]) == 20 34 | print "Example high value: 245" 35 | print ord(all_bytes[245]) == 245 36 | 37 | # now decode it to a unicode object: 38 | try: 39 | uni = all_bytes.decode() 40 | except UnicodeDecodeError: 41 | print "OOPS: can't decode with default encoding" 42 | 43 | # latin-1 works: 44 | try: 45 | all_uni = all_bytes.decode('latin-1') 46 | print "Yup -- that worked" 47 | print all_uni 48 | print "note that the ASCII subset is the same..." 49 | except UnicodeDecodeError: 50 | print "OOPS: This should have worked!!" 51 | raise 52 | 53 | ## now show that it round-trips: 54 | all_bytes2 = all_uni.encode('latin-1') 55 | 56 | if all_bytes2 == all_bytes: 57 | print "yup -- that worked...the values are preserved on the round trip." 58 | else: 59 | print "Hey, that should have worked" 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-02/code/codingbat.rst: -------------------------------------------------------------------------------- 1 | Coding Bat examples 2 | ###################### 3 | 4 | Warmup-1 > monkey_trouble 5 | ============================ 6 | 7 | We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble:: 8 | 9 | monkey_trouble(True, True) → True 10 | monkey_trouble(False, False) → True 11 | monkey_trouble(True, False) → False 12 | 13 | 14 | Warmup-1 > sleep_in 15 | ======================= 16 | 17 | The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. 18 | 19 | sleep_in(False, False) → True 20 | sleep_in(True, False) → False 21 | sleep_in(False, True) → True 22 | 23 | 24 | Warmup-1 > diff21 25 | ======================= 26 | 27 | Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. 28 | 29 | diff21(19) → 2 30 | diff21(10) → 11 31 | diff21(21) → 0 32 | 33 | Warmup-1 > makes10 34 | ====================== 35 | 36 | Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. 37 | 38 | makes10(9, 10) → True 39 | makes10(9, 9) → False 40 | makes10(1, 9) → True 41 | 42 | Logic-1 > cigar_party 43 | ====================== 44 | 45 | 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. 46 | 47 | cigar_party(30, False) → False 48 | cigar_party(50, False) → True 49 | cigar_party(70, True) → True 50 | 51 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08/code/circle_solution2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | circle class -- my solution to the second part of the exercise 5 | 6 | test code to run it is in test_circle2.py 7 | """ 8 | 9 | import math 10 | 11 | class Circle(object): 12 | def __init__(self, radius): 13 | self.radius = radius 14 | 15 | def _get_d(self): 16 | return self.radius * 2 17 | def _set_d(self, d): 18 | self.radius = d / 2.0 19 | diameter = property(_get_d, _set_d, doc="The diameter of the circle") 20 | 21 | def _get_area(self): 22 | return math.pi * self.radius**2 23 | area = property(_get_area, doc="The area of the circle") 24 | 25 | # alternate constructor that takes diameter 26 | def from_diameter(klass, d): 27 | return klass(d / 2.0) 28 | from_diameter = classmethod(from_diameter) 29 | 30 | ## The magic methods: 31 | def __str__(self): 32 | return "Circle with radius: %f"%self.radius 33 | 34 | def __repr__(self): 35 | return "Circle(%s)"%self.radius 36 | 37 | def __add__(self, other): 38 | return Circle(self.radius + other.radius) 39 | 40 | def __mul__(self, factor): 41 | return Circle(self.radius * factor) 42 | 43 | ## comparisons 44 | def __eq__(self, other): 45 | return self.radius == other.radius 46 | def __ne__(self, other): 47 | return self.radius != other.radius 48 | def __gt__(self, other): 49 | return self.radius > other.radius 50 | def __ge__(self, other): 51 | return self.radius >= other.radius 52 | def __lt__(self, other): 53 | return self.radius < other.radius 54 | def __le__(self, other): 55 | return self.radius <= other.radius 56 | 57 | # ## or, in this simple case: 58 | # def __cmp__(self, other): 59 | # return cmp(self.radius, other.radius) 60 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/csv_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example of how to save data as an CSV file with the CSV module 5 | 6 | """ 7 | 8 | import csv 9 | 10 | outfilename = "add_book_data.csv" 11 | 12 | # get the data from the py file 13 | # csv format really only holds flat data well. 14 | from add_book_data_flat import AddressBook 15 | 16 | # create a csv file writing object 17 | writer = csv.writer( open(outfilename, 'wb') ) 18 | 19 | # write the headers 20 | # assume all data have the same keys 21 | headers = AddressBook[0].keys() 22 | writer.writerow ( headers ) 23 | 24 | for person in AddressBook: 25 | row = [person[key] for key in headers] 26 | writer.writerow(row) 27 | 28 | del writer # to make sure the file gets closed 29 | 30 | ### see if it can be re-loaded. 31 | 32 | # create a csv file reading object 33 | reader = csv.reader( open(outfilename, 'rb') ) 34 | # read the headers 35 | headers = reader.next() # it's an iterator -- so next() gives us the next row -- in this case, the first row 36 | 37 | # build up the new version: 38 | AddressBook2 = [] 39 | for row in reader: 40 | AddressBook2.append(dict(zip(headers, row))) 41 | 42 | del reader # to make sure the file is closed 43 | 44 | #Check if they are the same 45 | if AddressBook2 == AddressBook: 46 | print "csv readr version is the same as the original" 47 | 48 | ## or use the built-in "DictReader": 49 | 50 | # create a DictReader file reading object 51 | reader = csv.DictReader( open(outfilename, 'rb') ) 52 | # no need to read the headers -- it will use the first row 53 | 54 | # build up the new version: 55 | AddressBook3 = [] 56 | for row in reader: 57 | print "row:", row 58 | AddressBook3.append(row) 59 | 60 | del reader # to make sure the file is closed 61 | 62 | #Check if they are the same 63 | if AddressBook3 == AddressBook: 64 | print "The DictReader one is the the same" 65 | 66 | -------------------------------------------------------------------------------- /Examples/Suppliments/add_book_data_flat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | sample data for persistence/serialization examples 5 | this version is flat for saving in CSV, ini, etc. 6 | """ 7 | 8 | AddressBook = [ {'first_name': "Chris", 9 | 'last_name': "Barker", 10 | 'address_line_1':"835 NE 33rd St", 11 | 'address_line_2' : "", 12 | 'address_city' : "Seattle", 13 | 'address_state': "WA", 14 | 'address_zip': "96543", 15 | 'email' : "PythonCHB@gmail.com", 16 | 'home_phone' : "206-555-1234", 17 | 'office_phone' : "123-456-7890", 18 | 'cell_phone' : "234-567-8901", 19 | }, 20 | 21 | {'first_name': "Fred", 22 | 'last_name': "Jones", 23 | 'address_line_1':"123 SE 13th St", 24 | 'address_line_2' : "Apt. 43", 25 | 'address_city' : "Tacoma", 26 | 'address_state': "WA", 27 | 'address_zip': "93465", 28 | 'email' : "FredJones@some_company.com", 29 | 'home_phone' : "510-555-1234", 30 | 'office_phone' : "564-466-7990", 31 | 'cell_phone' : "403-561-8911", 32 | }, 33 | 34 | {'first_name': "Nancy", 35 | 'last_name': "Wilson", 36 | 'address_line_1':"8654 Walnut St", 37 | 'address_line_2' : "Suite 567", 38 | 'address_city' : "Pasadena", 39 | 'address_state': "CA", 40 | 'address_zip': "12345", 41 | 'email' : "Wilson.Nancy@gmail.com", 42 | 'home_phone' : "423-321-9876", 43 | 'office_phone' : "123-765-9877", 44 | 'cell_phone' : "432-567-8466", 45 | }, 46 | ] 47 | 48 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-06/code/html_render/Solutions/gen_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Python class example. 5 | 6 | This is the first Element base class --- 7 | 8 | """ 9 | 10 | class Element(object): 11 | """ 12 | An element with multiple items in the content 13 | """ 14 | tag = "html" 15 | indent = " " 16 | def __init__(self, content=None): 17 | """ 18 | initialize an element and any number of sub-elements and content 19 | 20 | :param content: content of the element: single string or another element. 21 | an empty string will be ignored 22 | 23 | example: 24 | """ 25 | if not content: 26 | self.children = [] 27 | else: 28 | self.children = [content] 29 | 30 | def append(self, element): 31 | self.children.append(element) 32 | 33 | def render(self, file_out, ind = ""): 34 | """ 35 | an html rendering method for elements that have content 36 | """ 37 | file_out.write("\n") 38 | file_out.write(ind) 39 | file_out.write("<%s"%self.tag) 40 | file_out.write(">") 41 | for child in self.children: 42 | file_out.write("\n") 43 | file_out.write(ind + self.indent) 44 | file_out.write(child) 45 | file_out.write("\n") 46 | file_out.write(ind) 47 | file_out.write('%s>'%self.tag) 48 | 49 | 50 | if __name__ == "__main__": 51 | import sys, cStringIO 52 | page = Element() 53 | 54 | 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") 55 | 56 | page.append("And here is another piece of text -- you should be able to add any number") 57 | 58 | f = cStringIO.StringIO() 59 | 60 | page.render(f) 61 | 62 | f.reset() 63 | print f.read() 64 | 65 | f.reset() 66 | open("test_html.html", 'w').write(f.read()) 67 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08.5/code/address_book/address_book_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | application logic code for ultra simple 5 | address book app... 6 | """ 7 | 8 | import json 9 | 10 | class AddressBook(object): 11 | """ 12 | very simple data model -- just a list of dicts 13 | 14 | each dict represents an entry in the address book 15 | """ 16 | fields = [ "phone", 17 | "first_name", 18 | "last_name", 19 | "email", 20 | ] 21 | 22 | def __init__(self, filename="a_book.json"): 23 | self.filename = filename 24 | self.book = [] 25 | self.new_record() 26 | 27 | def new_record(self): 28 | """ 29 | and a new, empty record 30 | 31 | :returns index: index of the new, empty record 32 | """ 33 | self.book.append(dict.fromkeys(self.fields, "")) 34 | return len(self.book) - 1 35 | 36 | def save_to_file(self, filename=None): 37 | if filename is not None : 38 | self.filename = filename 39 | json.dump(self.book, open(self.filename, 'wb'), indent=4 ) 40 | 41 | def load_from_file(self, filename=None): 42 | if filename is not None : 43 | self.filename = filename 44 | self.book = json.load( open(self.filename, 'rb') ) 45 | 46 | def close(self): 47 | """ 48 | clear out the data... 49 | leave it with one empty dict 50 | """ 51 | del self.book[:] 52 | self.book.append({}) 53 | 54 | if __name__ == "__main__": 55 | import pprint 56 | a_book = AddressBook() 57 | a_book.load_from_file() 58 | 59 | print "the data in the address book is:" 60 | pprint.pprint(a_book.book) 61 | 62 | print 63 | print "the first entry is:" 64 | entry = a_book.book[0] 65 | print entry 66 | print "the first entry's name is:" 67 | print entry['first_name'], entry['last_name'] 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/add_book_data_flat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | sample data for persistence/serialization examples 5 | this version is flat for saving in CSV, ini, etc. 6 | """ 7 | 8 | AddressBook = [ {'first_name': "Chris", 9 | 'last_name': "Barker", 10 | 'address_line_1':"835 NE 33rd St", 11 | 'address_line_2' : "", 12 | 'address_city' : "Seattle", 13 | 'address_state': "WA", 14 | 'address_zip': "96543", 15 | 'email' : "PythonCHB@gmail.com", 16 | 'home_phone' : "206-555-1234", 17 | 'office_phone' : "123-456-7890", 18 | 'cell_phone' : "234-567-8901", 19 | }, 20 | 21 | {'first_name': "Fred", 22 | 'last_name': "Jones", 23 | 'address_line_1':"123 SE 13th St", 24 | 'address_line_2' : "Apt. 43", 25 | 'address_city' : "Tacoma", 26 | 'address_state': "WA", 27 | 'address_zip': "93465", 28 | 'email' : "FredJones@some_company.com", 29 | 'home_phone' : "510-555-1234", 30 | 'office_phone' : "564-466-7990", 31 | 'cell_phone' : "403-561-8911", 32 | }, 33 | 34 | {'first_name': "Nancy", 35 | 'last_name': "Wilson", 36 | 'address_line_1':"8654 Walnut St", 37 | 'address_line_2' : "Suite 567", 38 | 'address_city' : "Pasadena", 39 | 'address_state': "CA", 40 | 'address_zip': "12345", 41 | 'email' : "Wilson.Nancy@gmail.com", 42 | 'home_phone' : "423-321-9876", 43 | 'office_phone' : "123-765-9877", 44 | 'cell_phone' : "432-567-8466", 45 | }, 46 | ] 47 | 48 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-08.5/code/address_book_solution/address_book_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | application logic code for ultra simple 5 | address book app... 6 | """ 7 | 8 | import json 9 | 10 | class AddressBook(object): 11 | """ 12 | very simple data model -- just a list of dicts 13 | 14 | each dict represents an entry in the address book 15 | """ 16 | fields = [ "phone", 17 | "first_name", 18 | "last_name", 19 | "email", 20 | ] 21 | 22 | def __init__(self, filename="a_book.json"): 23 | self.filename = filename 24 | self.book = [] 25 | self.new_record() 26 | 27 | def new_record(self): 28 | """ 29 | and a new, empty record 30 | 31 | :returns index: index of the new, empty record 32 | """ 33 | self.book.append(dict.fromkeys(self.fields, "")) 34 | return len(self.book) - 1 35 | 36 | def save_to_file(self, filename=None): 37 | if filename is not None : 38 | self.filename = filename 39 | json.dump(self.book, open(self.filename, 'wb'), indent=4 ) 40 | 41 | def load_from_file(self, filename=None): 42 | if filename is not None : 43 | self.filename = filename 44 | self.book = json.load( open(self.filename, 'rb') ) 45 | 46 | def close(self): 47 | """ 48 | clear out the data... 49 | leave it with one empty dict 50 | """ 51 | del self.book[:] 52 | self.book.append({}) 53 | 54 | if __name__ == "__main__": 55 | import pprint 56 | a_book = AddressBook() 57 | a_book.load_from_file() 58 | 59 | print "the data in the address book is:" 60 | pprint.pprint(a_book.book) 61 | 62 | print 63 | print "the first entry is:" 64 | entry = a_book.book[0] 65 | print entry 66 | print "the first entry's name is:" 67 | print entry['first_name'], entry['last_name'] 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/add_book_data_flat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | sample data for persistence/serialization examples 5 | this version is flat for saving in CSV, ini, etc. 6 | """ 7 | 8 | AddressBook = [ {'first_name': "Chris", 9 | 'last_name': "Barker", 10 | 'address_line_1':"835 NE 33rd St", 11 | 'address_line_2' : "", 12 | 'address_city' : "Seattle", 13 | 'address_state': "WA", 14 | 'address_zip': "96543", 15 | 'email' : "PythonCHB@gmail.com", 16 | 'home_phone' : "206-555-1234", 17 | 'office_phone' : "123-456-7890", 18 | 'cell_phone' : "234-567-8901", 19 | }, 20 | 21 | {'first_name': "Fred", 22 | 'last_name': "Jones", 23 | 'address_line_1':"123 SE 13th St", 24 | 'address_line_2' : "Apt. 43", 25 | 'address_city' : "Tacoma", 26 | 'address_state': "WA", 27 | 'address_zip': "93465", 28 | 'email' : "FredJones@some_company.com", 29 | 'home_phone' : "510-555-1234", 30 | 'office_phone' : "564-466-7990", 31 | 'cell_phone' : "403-561-8911", 32 | }, 33 | 34 | {'first_name': "Nancy", 35 | 'last_name': "Wilson", 36 | 'address_line_1':"8654 Walnut St", 37 | 'address_line_2' : "Suite 567", 38 | 'address_city' : "Pasadena", 39 | 'address_state': "CA", 40 | 'address_zip': "12345", 41 | 'email' : "Wilson.Nancy@gmail.com", 42 | 'home_phone' : "423-321-9876", 43 | 'office_phone' : "123-765-9877", 44 | 'cell_phone' : "432-567-8466", 45 | }, 46 | ] 47 | 48 | -------------------------------------------------------------------------------- /slides_sources/source/exercises/args_kwargs_lab.rst: -------------------------------------------------------------------------------- 1 | .. _exercise_args_kwargs_lab: 2 | 3 | ******************* 4 | args and kwargs Lab 5 | ******************* 6 | 7 | Learning about ``args`` and ``kwargs`` 8 | ====================================== 9 | 10 | Goal: 11 | ----- 12 | 13 | Develop an understanding of using advanced argument passing and parameter definitons. 14 | 15 | If this is all confusing -- you may want to review this: 16 | 17 | http://stupidpythonideas.blogspot.com/2013/08/arguments-and-parameters.html 18 | 19 | Procedure 20 | --------- 21 | 22 | **Keyword arguments:** 23 | 24 | * Write a function that has four optional parameters (with defaults): 25 | 26 | - `fore_color` 27 | - `back_color` 28 | - `link_color` 29 | - `visited_color` 30 | 31 | * Have it print the colors (use strings for the colors) 32 | 33 | * Call it with a couple different parameters set 34 | 35 | - using just positional arguments: 36 | 37 | - ``func('red', 'blue', 'yellow', 'chartreuse')`` 38 | 39 | - using just keyword arguments: 40 | 41 | - ``func(link_color='red', back_color='blue')`` 42 | 43 | - using a combination of positional and keyword 44 | 45 | - ````func('purple', link_color='red', back_color='blue')`` 46 | 47 | - using ``*some_tuple`` and/or ``**some_dict`` 48 | 49 | - ``regular = ('red', 'blue')`` 50 | 51 | - ``links = {'link_color': 'chartreuse'}`` 52 | 53 | - ``func(*regular, *links)`` 54 | 55 | .. nextslide:: 56 | 57 | **Generic parameters:** 58 | 59 | * Write a the same function with the parameters as: 60 | 61 | ``*args`` and ``**kwags`` 62 | 63 | * Have it print the colors (use strings for the colors) 64 | 65 | * Call it with the same various combinations of arguments used above. 66 | 67 | * Also have it print `args` and `kwargs` directly, so you can be sure you understand what's going on. 68 | 69 | * Note that in general, you can't know what will get passed into ``**kwargs`` So maybe adapt your function to be able to do something reasonable with any keywords. 70 | 71 | 72 | -------------------------------------------------------------------------------- /slides_sources/source/index.rst: -------------------------------------------------------------------------------- 1 | *************** 2 | Intro To Python 3 | *************** 4 | 5 | 6 | In This Course 7 | ============== 8 | 9 | .. ifslides:: 10 | 11 | +----------------------+-----------------------+ 12 | | Lectures: | Materials: | 13 | +======================+=======================+ 14 | | .. toctree:: | .. toctree:: | 15 | | :maxdepth: 1 | :maxdepth: 1 | 16 | | | | 17 | | session01 | exercises/index | 18 | | session02 | supplements/index | 19 | | session03 | | 20 | | session04 | | 21 | | session05 | | 22 | | session06 | | 23 | | session07 | | 24 | | session08 | | 25 | | session09 | | 26 | | session10 | | 27 | +----------------------+-----------------------+ 28 | 29 | .. ifnotslides:: 30 | 31 | Lectures: 32 | --------- 33 | 34 | .. toctree:: 35 | :maxdepth: 1 36 | 37 | session01 38 | session02 39 | session03 40 | session04 41 | session05 42 | session06 43 | session07 44 | session08 45 | session09 46 | session10 47 | 48 | Materials: 49 | ---------- 50 | 51 | .. toctree:: 52 | :maxdepth: 2 53 | 54 | extra_topics 55 | exercises/index 56 | supplements/index 57 | 58 | .. rst-class:: credit 59 | 60 | These materials copyright Christopher Barker and Cris Ewing, with thanks to 61 | Jon Jacky and Brian Dorsey for the materials from which these were derived. 62 | Licenced under the 63 | Creative Commons Attribution-ShareAlike 4.0 International Public License. 64 | 65 | https://creativecommons.org/licenses/by-sa/4.0/legalcode 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /Examples/Suppliments/unicodify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ''' 4 | Decorators to convert all arguments passed to a function or method to 5 | unicode or str, including default arguments 6 | 7 | From: http://axialcorps.com/2014/03/20/unicode-str/ 8 | 9 | ''' 10 | 11 | 12 | import sys 13 | import functools 14 | import inspect 15 | 16 | def _convert_arg(arg, from_, conv, enc): 17 | '''Safely convert unicode to string or string to unicode''' 18 | return getattr(arg, conv)(encoding=enc) if isinstance(arg, from_) else arg 19 | 20 | def _wrap_convert(from_type, fn, encoding=None): 21 | '''Decorate a function converting all str arguments to unicode or 22 | vice-versa''' 23 | conv = 'decode' if from_type is str else 'encode' 24 | encoding = encoding or sys.getdefaultencoding() 25 | 26 | # override string defaults using partial 27 | aspec, dflts = inspect.getargspec(fn), {} 28 | if aspec.defaults: 29 | for k,v in zip(aspec.args[-len(aspec.defaults):],aspec.defaults): 30 | dflts[k] = _convert_arg(v, from_type, conv, encoding) 31 | fn = functools.partial(fn, **dflts) 32 | 33 | @functools.wraps(fn.func if isinstance(fn, functools.partial) else fn) 34 | def converted(*args, **kwargs): 35 | args = [_convert_arg(a, from_type, conv, encoding) for a in args] 36 | for k,v in kwargs.iteritems(): 37 | kwargs[k] = _convert_arg(v, from_type, conv, encoding) 38 | return fn(*args, **kwargs) 39 | 40 | return converted 41 | 42 | def unicodify(fn=None, encoding=None): 43 | '''Convert all str arguments to unicode''' 44 | if fn is None: 45 | return functools.partial(unicodify, encoding=encoding) 46 | return _wrap_convert(str, fn, encoding=encoding) 47 | 48 | def stringify(fn=None, encoding=None): 49 | '''Convert all unicode arguments to str''' 50 | if fn is None: 51 | return functools.partial(stringify, encoding=encoding) 52 | return _wrap_convert(unicode, fn, encoding=encoding) 53 | 54 | __all__ = ['unicodify', 'stringify'] -------------------------------------------------------------------------------- /slides_sources/old_versions/week-06/code/simple_classes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | simple_classes.py 4 | 5 | demonstrating the basics of a class 6 | """ 7 | 8 | ## create a point class 9 | class Point(object): 10 | def __init__(self, x, y): 11 | self.x = x 12 | self.y = y 13 | 14 | ## create an instance of that class 15 | p = Point(3,4) 16 | 17 | ## access the attributes 18 | print "p.x is:", p.x 19 | print "p.y is:", p.y 20 | 21 | class Point2(object): 22 | size = 4 23 | color= "red" 24 | def __init__(self, x, y): 25 | self.x = x 26 | self.y = y 27 | 28 | p2 = Point2(4,5) 29 | print p2.size 30 | print p2.color 31 | 32 | class Point3(object): 33 | size = 4 34 | color= "red" 35 | def __init__(self, x, y): 36 | self.x = x 37 | self.y = y 38 | def get_color(self): 39 | return self.color 40 | 41 | 42 | p3 = Point3(4,5) 43 | print p3.size 44 | print p3.get_color() 45 | 46 | class Circle(object): 47 | color = "red" 48 | def __init__(self, diameter): 49 | self.diameter = diameter 50 | 51 | def grow(self, factor=2): 52 | """ 53 | grows the circle's diameter 54 | 55 | :param factor=2: factor by which to grow the circle 56 | """ 57 | self.diameter = self.diameter * factor 58 | 59 | def get_area(self): 60 | return math.pi * self.diameter / 2.0 61 | 62 | class NewCircle(Circle): 63 | color = "blue" 64 | 65 | def grow(self, factor=2): 66 | """grows the area by factor...""" 67 | self.diameter = self.diameter * math.sqrt(2) 68 | 69 | nc = NewCircle 70 | print nc.color 71 | 72 | class CircleR(Circle): 73 | def __init__(self, radius): 74 | diameter = radius*2 75 | Circle.__init__(self, diameter) 76 | 77 | class CircleR2(Circle): 78 | def __init__(self, radius): 79 | self.radius = radius 80 | 81 | def get_area(self): 82 | return Circle.get_area(self, self.radius*2) 83 | 84 | 85 | -------------------------------------------------------------------------------- /slides_sources/source/supplements/unicodify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ''' 4 | Decorators to convert all arguments passed to a function or method to 5 | unicode or str, including default arguments 6 | 7 | From: http://axialcorps.com/2014/03/20/unicode-str/ 8 | 9 | ''' 10 | 11 | 12 | import sys 13 | import functools 14 | import inspect 15 | 16 | def _convert_arg(arg, from_, conv, enc): 17 | '''Safely convert unicode to string or string to unicode''' 18 | return getattr(arg, conv)(encoding=enc) if isinstance(arg, from_) else arg 19 | 20 | def _wrap_convert(from_type, fn, encoding=None): 21 | '''Decorate a function converting all str arguments to unicode or 22 | vice-versa''' 23 | conv = 'decode' if from_type is str else 'encode' 24 | encoding = encoding or sys.getdefaultencoding() 25 | 26 | # override string defaults using partial 27 | aspec, dflts = inspect.getargspec(fn), {} 28 | if aspec.defaults: 29 | for k,v in zip(aspec.args[-len(aspec.defaults):],aspec.defaults): 30 | dflts[k] = _convert_arg(v, from_type, conv, encoding) 31 | fn = functools.partial(fn, **dflts) 32 | 33 | @functools.wraps(fn.func if isinstance(fn, functools.partial) else fn) 34 | def converted(*args, **kwargs): 35 | args = [_convert_arg(a, from_type, conv, encoding) for a in args] 36 | for k,v in kwargs.iteritems(): 37 | kwargs[k] = _convert_arg(v, from_type, conv, encoding) 38 | return fn(*args, **kwargs) 39 | 40 | return converted 41 | 42 | def unicodify(fn=None, encoding=None): 43 | '''Convert all str arguments to unicode''' 44 | if fn is None: 45 | return functools.partial(unicodify, encoding=encoding) 46 | return _wrap_convert(str, fn, encoding=encoding) 47 | 48 | def stringify(fn=None, encoding=None): 49 | '''Convert all unicode arguments to str''' 50 | if fn is None: 51 | return functools.partial(stringify, encoding=encoding) 52 | return _wrap_convert(unicode, fn, encoding=encoding) 53 | 54 | __all__ = ['unicodify', 'stringify'] -------------------------------------------------------------------------------- /Examples/Suppliments/add_book_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | sample data for persistence/serializatiion examples 5 | 6 | This version is nested, with more stucture 7 | - can be saved with pickle, JSON, xml... 8 | """ 9 | 10 | AddressBook = [ {'first_name': "Chris", 11 | 'last_name': "Barker", 12 | 'address' : {'line_1':"835 NE 33rd St", 13 | 'line_2' : "", 14 | 'city' : "Seattle", 15 | 'state': "WA", 16 | 'zip': "96543"}, 17 | 'email' : "PythonCHB@gmail.com", 18 | 'home_phone' : "206-555-1234", 19 | 'office_phone' : "123-456-7890", 20 | 'cell_phone' : "234-567-8901", 21 | }, 22 | 23 | {'first_name': "Fred", 24 | 'last_name': "Jones", 25 | 'address' : {'line_1':"123 SE 13th St", 26 | 'line_2' : "Apt. 43", 27 | 'city' : "Tacoma", 28 | 'state': "WA", 29 | 'zip': "93465"}, 30 | 'email' : "FredJones@some_company.com", 31 | 'home_phone' : "510-555-1234", 32 | 'office_phone' : "564-466-7990", 33 | 'cell_phone' : "403-561-8911", 34 | }, 35 | 36 | {'first_name': "Nancy", 37 | 'last_name': "Wilson", 38 | 'address' : {'line_1':"8654 Walnut St", 39 | 'line_2' : "Suite 567", 40 | 'city' : "Pasadena", 41 | 'state': "CA", 42 | 'zip': "12345"}, 43 | 'email' : "Wilson.Nancy@gmail.com", 44 | 'home_phone' : "423-321-9876", 45 | 'office_phone' : "123-765-9877", 46 | 'cell_phone' : "432-567-8466", 47 | }, 48 | ] 49 | 50 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/add_book_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | sample data for persistence/serializatiion examples 5 | 6 | This version is nested, with more stucture 7 | - can be saved with pickle, JSON, xml... 8 | """ 9 | 10 | AddressBook = [ {'first_name': "Chris", 11 | 'last_name': "Barker", 12 | 'address' : {'line_1':"835 NE 33rd St", 13 | 'line_2' : "", 14 | 'city' : "Seattle", 15 | 'state': "WA", 16 | 'zip': "96543"}, 17 | 'email' : "PythonCHB@gmail.com", 18 | 'home_phone' : "206-555-1234", 19 | 'office_phone' : "123-456-7890", 20 | 'cell_phone' : "234-567-8901", 21 | }, 22 | 23 | {'first_name': "Fred", 24 | 'last_name': "Jones", 25 | 'address' : {'line_1':"123 SE 13th St", 26 | 'line_2' : "Apt. 43", 27 | 'city' : "Tacoma", 28 | 'state': "WA", 29 | 'zip': "93465"}, 30 | 'email' : "FredJones@some_company.com", 31 | 'home_phone' : "510-555-1234", 32 | 'office_phone' : "564-466-7990", 33 | 'cell_phone' : "403-561-8911", 34 | }, 35 | 36 | {'first_name': "Nancy", 37 | 'last_name': "Wilson", 38 | 'address' : {'line_1':"8654 Walnut St", 39 | 'line_2' : "Suite 567", 40 | 'city' : "Pasadena", 41 | 'state': "CA", 42 | 'zip': "12345"}, 43 | 'email' : "Wilson.Nancy@gmail.com", 44 | 'home_phone' : "423-321-9876", 45 | 'office_phone' : "123-765-9877", 46 | 'cell_phone' : "432-567-8466", 47 | }, 48 | ] 49 | 50 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/add_book_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | sample data for persistence/serializatiion examples 5 | 6 | This version is nested, with more stucture 7 | - can be saved with pickle, JSON, xml... 8 | """ 9 | 10 | AddressBook = [ {'first_name': "Chris", 11 | 'last_name': "Barker", 12 | 'address' : {'line_1':"835 NE 33rd St", 13 | 'line_2' : "", 14 | 'city' : "Seattle", 15 | 'state': "WA", 16 | 'zip': "96543"}, 17 | 'email' : "PythonCHB@gmail.com", 18 | 'home_phone' : "206-555-1234", 19 | 'office_phone' : "123-456-7890", 20 | 'cell_phone' : "234-567-8901", 21 | }, 22 | 23 | {'first_name': "Fred", 24 | 'last_name': "Jones", 25 | 'address' : {'line_1':"123 SE 13th St", 26 | 'line_2' : "Apt. 43", 27 | 'city' : "Tacoma", 28 | 'state': "WA", 29 | 'zip': "93465"}, 30 | 'email' : "FredJones@some_company.com", 31 | 'home_phone' : "510-555-1234", 32 | 'office_phone' : "564-466-7990", 33 | 'cell_phone' : "403-561-8911", 34 | }, 35 | 36 | {'first_name': "Nancy", 37 | 'last_name': "Wilson", 38 | 'address' : {'line_1':"8654 Walnut St", 39 | 'line_2' : "Suite 567", 40 | 'city' : "Pasadena", 41 | 'state': "CA", 42 | 'zip': "12345"}, 43 | 'email' : "Wilson.Nancy@gmail.com", 44 | 'home_phone' : "423-321-9876", 45 | 'office_phone' : "123-765-9877", 46 | 'cell_phone' : "432-567-8466", 47 | }, 48 | ] 49 | 50 | -------------------------------------------------------------------------------- /Examples/Session10/decorators.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | def substitute(a_function): 5 | """return a different function than the one supplied""" 6 | def new_function(*args, **kwargs): 7 | return "I'm not that other function" 8 | return new_function 9 | 10 | 11 | def add(a, b): 12 | print("Function 'add' called with args: {}, {}".format(a, b) ) 13 | result = a + b 14 | print("\tResult --> {}".format(result)) 15 | return result 16 | 17 | 18 | def logged_func(func): 19 | def logged(*args, **kwargs): 20 | print("Function {} called".format(func.__name__)) 21 | if args: 22 | print("\twith args: {}".format(args)) 23 | if kwargs: 24 | print("\twith kwargs: {}".format(kwargs)) 25 | result = func(*args, **kwargs) 26 | print("\t Result --> {}".format(result)) 27 | return result 28 | return logged 29 | 30 | 31 | def simple_add(a, b): 32 | return a + b 33 | 34 | 35 | class Memoize(object): 36 | """ 37 | memoize decorator from avinash.vora 38 | http://avinashv.net/2008/04/python-decorators-syntactic-sugar/ 39 | """ 40 | def __init__(self, function): # runs when memoize class is called 41 | self.function = function 42 | self.memoized = {} 43 | 44 | def __call__(self, *args): # runs when memoize instance is called 45 | try: 46 | return self.memoized[args] 47 | except KeyError: 48 | self.memoized[args] = self.function(*args) 49 | return self.memoized[args] 50 | 51 | 52 | @Memoize 53 | def sum2x(n): 54 | return sum(2 * i for i in range(n)) 55 | # sum2x = Memoize(sum2x) 56 | 57 | @Memoize 58 | def prod2(a,b): 59 | return sum( a * b**2 for a,b in zip(range(a), range(b))) 60 | 61 | import time 62 | 63 | def timed_func(func): 64 | def timed(*args, **kwargs): 65 | start = time.time() 66 | result = func(*args, **kwargs) 67 | elapsed = time.time() - start 68 | print("time expired: {}".format(elapsed)) 69 | return result 70 | return timed 71 | 72 | 73 | @timed_func 74 | @Memoize 75 | def sum2x(n): 76 | return sum(2 * i for i in range(n)) 77 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-10/code/Solutions/xml_example2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Example of how to save data as xml, using the element tree module 5 | 6 | This version uses the nested dataset, and does full-on nested XML 7 | 8 | """ 9 | 10 | import xml.etree.ElementTree as ET 11 | from indent_etree import indent # for prettier output 12 | 13 | outfilename = "add_book_data2.xml" 14 | 15 | # get the data from the py file 16 | from add_book_data import AddressBook 17 | 18 | # build a tree structure 19 | root = ET.Element("address_book") 20 | 21 | # add the elements: 22 | for person in AddressBook: 23 | p = ET.SubElement(root, "person") 24 | # This method stores everything as sub-elements 25 | for key, value in person.items(): 26 | if type(value) == dict: 27 | address = ET.SubElement(p, 'address') 28 | for sub_key, sub_value in value.items(): 29 | sub_el = ET.SubElement(address, sub_key) 30 | sub_el.text=sub_value 31 | else: 32 | el = ET.SubElement(p, key) 33 | el.text=value 34 | 35 | # wrap it in an ElementTree instance, and save as XML 36 | tree = ET.ElementTree(root) 37 | 38 | indent(tree.getroot()) # to make it more pretty 39 | tree.write(outfilename) 40 | 41 | ### See if we can re-load it 42 | 43 | tree = ET.parse(outfilename) 44 | book = tree.getroot() 45 | # re-build the original list: 46 | AddressBook2 = [] 47 | for person in list(book): 48 | p = {} 49 | for sub_el in list(person): 50 | if sub_el.tag == "address": 51 | address = {} 52 | for sub_sub_el in sub_el.getchildren(): 53 | t = sub_sub_el.text 54 | if t is None: ## etree returns None for empty tags! 55 | address[sub_sub_el.tag] = "" 56 | else: 57 | address[sub_sub_el.tag] = t 58 | p['address'] = address 59 | else: 60 | p[sub_el.tag] = sub_el.text 61 | AddressBook2.append(p) 62 | 63 | if AddressBook2 == AddressBook: 64 | print "xml version is the same as the original" 65 | else: 66 | print "xml version is not exactly the same as the original" 67 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-06/code/html_render/Solutions/gen_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Python class example. 5 | 6 | This adds a couple sub-classes 7 | 8 | """ 9 | 10 | class Element(object): 11 | """ 12 | An element with multiple items in the content 13 | """ 14 | tag = "" 15 | indent = " " 16 | def __init__(self, content=None): 17 | """ 18 | initialize an element and any number of sub-elements and content 19 | 20 | :param content: content of the element: single string or another element. 21 | an empty string will be ignored 22 | 23 | example: 24 | """ 25 | if not content: 26 | self.children = [] 27 | else: 28 | self.children = [content] 29 | 30 | def append(self, element): 31 | self.children.append(element) 32 | 33 | def render(self, file_out, ind = ""): 34 | """ 35 | an html rendering method for elements that have content 36 | """ 37 | file_out.write("\n") 38 | file_out.write(ind) 39 | file_out.write("<%s"%self.tag) 40 | file_out.write(">") 41 | for child in self.children: 42 | try: 43 | child.render(file_out, ind + self.indent) 44 | except AttributeError: 45 | file_out.write("\n") 46 | file_out.write(ind + self.indent) 47 | file_out.write(str(child)) 48 | file_out.write("\n") 49 | file_out.write(ind) 50 | file_out.write('%s>'%self.tag) 51 | 52 | class Html(Element): 53 | tag = "html" 54 | 55 | class Body(Element): 56 | tag = "body" 57 | 58 | class P(Element): 59 | tag = "p" 60 | 61 | 62 | if __name__ == "__main__": 63 | import sys, cStringIO 64 | page = Html() 65 | 66 | body = Body() 67 | 68 | body.append(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")) 69 | 70 | page.append(body) 71 | 72 | f = cStringIO.StringIO() 73 | 74 | page.render(f) 75 | 76 | f.reset() 77 | print f.read() 78 | 79 | f.reset() 80 | open("test_html.html", 'w').write(f.read()) 81 | -------------------------------------------------------------------------------- /slides_sources/old_versions/week-02/homework_solution_memo.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | 3 | """ 4 | Chris' Solution to The Ackermann function 5 | """ 6 | 7 | all_calls = {} 8 | 9 | num_calls = 0 10 | num_calls2 = 0 11 | 12 | 13 | def ack(m,n): 14 | """ 15 | Solution to the Ackerman function 16 | 17 | http://en.wikipedia.org/wiki/Ackermann_function 18 | 19 | This one directly follows the logic laid out in the definition 20 | 21 | """ 22 | 23 | # I prefer to check bounds up front: 24 | # this really should raise an exception, 25 | # but we haven't covered that yet in class. 26 | 27 | global num_calls 28 | num_calls += 1 29 | 30 | if m<0 or n<0: 31 | return "Solution is not Defined" 32 | 33 | # print "ack called with:", m, n 34 | if (m,n) in all_calls: 35 | # print "already called with:", (m,n) 36 | return all_calls[(m,n)] 37 | else: 38 | if m == 0: 39 | result = n+1 40 | elif n == 0 and m > 0: 41 | result = ack(m-1, 1) 42 | else: 43 | result = ack(m-1, ack(m, n-1)) 44 | all_calls[(m,n)] = result 45 | 46 | return result 47 | 48 | 49 | def ack2(m,n): 50 | """ 51 | Solution to the Ackerman function 52 | 53 | http://en.wikipedia.org/wiki/Ackermann_function 54 | 55 | This one uses nested conditional expressions: 56 | Don't try this at home! 57 | 58 | """ 59 | global num_calls2 60 | num_calls2 += 1 61 | 62 | if m<0 or n<0: 63 | return "Solution is not Defined" 64 | else: 65 | return n+1 if m==0 else ( 66 | ack2(m-1, 1) if (n == 0 and m > 0) else ( 67 | ack2(m-1, ack2(m, n-1) ) 68 | ) 69 | ) 70 | 71 | 72 | # tests: 73 | print "with saving intermediate results:" 74 | print ack(3,4) 75 | print "total number of calls:", num_calls 76 | 77 | print "without saving intermediate results:" 78 | print ack2(3,4) 79 | print "total number of calls:", num_calls2 80 | 81 | # for m in range(-1, 4): 82 | # for n in range(-1, 5): 83 | # print " the result of ack", (m,n), "is", ack(m,n) 84 | # print " the result of ack2", (m,n), "is", ack2(m,n) 85 | 86 | 87 | --------------------------------------------------------------------------------