Week 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

RECURSION,

GLOBAL VARIABLES,
MODULES, FILES
CS115
Introduction to Programming in Python

Week 5

Slides are mostly adapted from MIT Open Courseware


1
LAST WEEK

▶ decomposition
▶ abstraction
▶ functions
▶ scope

2
THIS WEEK

▶ recursion
▶ global variables
▶ modules
▶ files

3
4
5
6
7
Computing Factorial

n! = n * (n - 1) * (n - 2) * … * 1
= n * (n - 1)!

factorial(0) = 1
factorial(n) = n * factorial(n-1)

8
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3)

9
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)

10
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))

11
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))

12
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))

13
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)

14
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)
= 3 * 2

15
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * (2 * (1 * factorial(0))
= 3 * (2 * (1 * 1))
= 3 * (2 * 1)
= 3 * 2
= 3 * 2

➢ See factorial_recursion.py
16
Computing Factorial
factorial(0) = 1
factorial(n) = n * factorial(n-1)

factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)
= 4 * 3 * 2
= 4 * 6
= 24

17
Computing Factorial factorial(0) = 1
factorial(n) = n * factorial(n-1)

18
19
20
21
Fibonacci Numbers

Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89…


indices: 0 1 2 3 4 5 6 7 8 9 10 11
fib(0) = 0
fib(1) = 1
fib(index) = fib(index -1) + fib(index -2) if index >= 2

➢ See fibonacci_recursion.py

22
Fibonacci Numbers
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89…
indices: 0 1 2 3 4 5 6 7 8 9 10 11
fib(0) = 0
fib(1) = 1
fib(index) = fib(index -1) + fib(index -2) if index >= 2

23
Fibonacci Numbers

24
Characteristics of Recursion

All recursive methods have the following characteristics:

▶ One or more base cases (the simplest case) to stop recursion


▶ Every recursive call solves the original problem with a smaller size input
▶ Eventually smaller size input becomes a base case

▶ In general, to solve a problem using recursion, you break it into subproblems.


If a subproblem resembles the original problem, you can solve it recursively.

25
26
Think Recursively
▶ how to check if a string of characters is a palindrome, i.e., reads the same
forwards and backwards
○ Examples:
▶ “Madam”
▶ “Able was I, ere I saw Elba” – attributed to Napoleon

▶ First, convert the string to just characters, by stripping out punctuation, and
converting upper case to lower case
▶ Then
◦ Base case: a string of length 0 or 1 is a palindrome
◦ Recursive case:
◦ If first character matches last character, then is a palindrome if middle
section is a palindrome
27
Think Recursively

28

28
29
30
Global Variables
▶ Python also supports global variables (variables that are defined
outside functions)
▶ A global variable is visible from within all functions
▶ Any function that wants to update a global variable must
include a global declaration
▶ Variables that are assigned values/updated inside functions,
with the same name as global variables, will not be considered
global without the global declaration. They will be
considered as local variables.
▶ Warning: Global variables are not generally recommended.  It
is a contradiction of modularity to have variables be accessible
in functions in which they are not used. Global variables can
cause unexpected results. 31
Global Variables - Example

def f(): def g() :


x = 1 global x
print(x) x = 1
print(x)
x = 5
f() x = 5
print(x) g()
print(x)

Output: Output:
1 1
5 1
32
Modules
▶ Python contains a standard library that can be used to create
powerful programs.
▶ A library is a collection of code that is ready for you to use in
your program.
▶ A standard library is considered part of the language and must
be included with any Python system.
▶ Python’s standard library is organized into modules; each
module contains related functions.
▶ In addition to using the standard libraries, you can also create
your own modules, however it is rarely necessary to write your
own implementations for mathematical or string functions.
▶ Python Library 33
Using Modules - import
▶ Before using the functions contained in a module, you must first
import the module to your program
▶ Importing is done using an import statement
▶ Using the import statement, we can import specific functions within a
module or all functions contained in the module at once.
▶ Syntax:
from math import sqrt -> makes available only sqrt in math

from math import sqrt, sin, cos -> makes available specific functions listed

from math import * -> makes available all function in math module

import math -> makes available all functions in math module, when

calling functions, you must add the module name

ex: math.sqrt(25) 34
Creating our own Modules

▶ Modules allow for problem decomposition


▶ Instead of placing our entire program in a single file, we divide
the program into modules (different source code files)
▶ Python modules allow us to easily construct a program from
code in multiple files
▶ A module is a .py file, containing Python definitions and
statements
▶ Example:
▪ circle.py / circleTest.py / circleTest2.py

35
Exercise
▶ Create a module (fitness_module.py) that stores fitness calculations.
Your module should define the following data and functions:
▪ MAX_RATE_CONSTANT (220)

▪ MAX_BMI (24)

▪ MIN_BMI (21)

▪ calculate_bmi ( weight / height2)

▪ display_bmi_category (30+ obese, 25-30 overweight,20-25 normal, <25


underweight)
▪ calculate_target_heart_rate ( 80% of (220 minus age))

▪ display_weight_range (bmi between min and max bmi )

▶ Create a script that inputs the age, height and weight from the user and
displays their fitness detail.
▶ fitness.py
36
Files

program

37
File Functions
Function Purpose
open(fileName, ’w’) Creates new a file for writing and returns the file object (file handle).
open(fileName, ’r’) Opens an existing file for reading and returns a file handle.
open(fileName, ’a’) Opens an existing file for appending and returns a file handle.
fh.read() Returns a string containing the contents of the file associated with the
file handle.
fh.readline() Returns the next line in the file associated with the file handle.
fh.readlines() Returns list, each element of which is one line of the file associated with
the file handle.
fh.write(s) Writes the string s to the end of the file associated with the file handle.
fh.writeLines(S) S is a sequence of strings, writes each element of S as a separate line to
the file associated with the file handle.
fh.close() Closes the file associated with the file handle.

38
Writing Data to a File

# writing data to a file


fileHandle = open('file1.txt', 'w')
for i in range(2):
name = input('Enter name: ')
fileHandle.write(name + '\n')
fileHandle.close()

File Contents:
Melisa Aksoy
Sam Smith

39
Appending Data to a File

# append data to end of file


fileHandle = open('file1.txt', 'a')
fileHandle.write('Jane Doe\n')
fileHandle.close()

File Contents:
Melisa Aksoy
Sam Smith
Jane Doe
40
Reading Data from File – read()

# reading data from a file - read()


fileHandle = open('file1.txt', 'r')
fileContents = fileHandle.read()
print(fileContents)
fileHandle.close()

41
Reading Lines from a File – readline()
# reading specific lines from a file - readline()
fileHandle = open('file1.txt', 'r')
for i in range(2):
line = fileHandle.readline()
print(line[:-1])
fileHandle.close()

Note:
▶ using the [:-1] syntax in the print method call stops the
print method from outputting the newline character from
the file data.
▶ We can also use the string strip() function, which removes
the leading and trailing whitespace characters and returns
the new string. 42
Reading Data from a File – for loop

# read all lines from the file


fileHandle = open('file1.txt', 'r')
for line in fileHandle:
print(line[:-1])
fileHandle.close()

43
Useful String Functions

▶ When processing files, there are a number of built-in string


functions that might be useful.

Function Name Purpose


s.count(s1) Counts how many times the string s1 occurs in s.
s.find(s1) Returns the index of the first occurrence of the substring
s1 in s, and -1 if s1 is not in s.
s.rfind(s1) Same as find, but starts from the end of s (the ‘r’ in rfind
stands for reverse)
s.replace(old,new) Replaces all occurrences of the string old in s with the
string new.
s.rstrip() Removes the trailing whitespace from s.
s.lower() Converts all uppercase letters in s to lowercase. 44
Exercises:
1. Write a program that reads hotel data from a file, and writes all
hotels in the city input by the user to a new file with the name
<city>hotels.txt. Note: you may assume that the city name is at the
beginning of each line, and that the city is followed by a dash(-) then
the hotel name.
▶ hotel_exercise.py / hotels.txt
2. Write a program to input two sorted files containing the names of
flowers and merges the two files into a new sorted file.
▶ flower_exercise.py / flower1.txt / flower2.txt

45
Exercises (cont’d):
3. Write a program that reads two country data files, worldpop.txt
and worldarea.txt. Both files contain the same countries in the
same order. Write a file world_pop_density.txt that contains
country names and population densities (people per square km).
▶ world_country.py / worldpop.txt / worldarea.txt

46
Terms of Use
➢ This presentation was adapted from lecture materials provided in MIT Introduction to Computer Science
and Programming in Python.
➢ Licenced under terms of Creative Commons License.

47

You might also like