CSci 227 Syllabus    Resources    Coursework



Laboratory Exercise 4
CSci 227: Programming Methods
Department of Computer Science
Hunter College, City University of New York
Spring 2024


Learning Objectives:

Software Tools Needed: Web browser to access textbook and an IDE (on-line or on computer) with core Python 3.6+ loaded.

Lab Notes: Download the outline and focus questions to guide you while working through this lab. These are a useful tool for note taking and as well as studying for the quizzes and final exam.


Parameters & Functions

In lecture this week, we briefly recapped parameters and functions from CSCI 127. To test your understanding, work through the examples from the functions chapter of the CSCI 127 textbook:

We will go into more details on the functions calling functions section (recursion) below.

Exceptions

Exceptions are runtime errors that cause the end of execution. Python, like most programming languages have a way to "handle" or "catch" exceptions, as well as "throw" exceptions if warranted. Work through the textbook's section on exception handling:

Recursion

In lecture, we showed several functions that call themselves, including the nested triangles from CSCI 127:

Our triangle examples have a basic format:

Then they have a case (or cases) that call the function again with decreasing values. If the first case is missing, the recursion will not stop and go on forever. If the second case doesn't use decreasing values, then it will also go on forever. For the recursion to work, both are needed and the book formalizes this as the Three Laws of Recursion.

Three Laws of Recursion

Work through the example below to see each of the laws of recurions in action:

Visualizing Recursion

The textbook has several other visual examples of recursion: one on trees and a more complex one of nested triangles:

Binary Search

The binary search algorithm that we saw in Classwork 4 is a canonical recursive algorithm that is useful for solving many problems (see a few in the additional practice section below).

LeetCode has a tutorial on using binary search as part of their Explore series. Work through the first template that they give and the associated problems.

Quizzes and Code Reviews

There are weekly written quizzes and code reviews in 1001G, 11:30-5:30, Mondays-Fridays when classes are in session. No appointments are needed for CSCI 227 students. Make sure to complete Quiz 4 and Code Review 4 by Thursday, 29 February.

Additional Practice

For additional practice on core Python, see the HackerRank prepare series:

HackerRank: Prepare Python

Click the Easy option on the right hand menu, and work through their Python challenges.

For more practice on using recursion to solve problems, here are some popular ones from LeetCode where using recursion is an efficient approach: