DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Similar documents
DM502 Programming A. Peter Schneider-Kamp.

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

Functions and Recursion

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM503 Programming B. Peter Schneider-Kamp.

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Conditionals and Recursion. Python Part 4

ITERATION AND RECURSION 3

Recursion. Fundamentals of Computer Science

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

An introduction to Scheme

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

ENVIRONMENT DIAGRAMS AND RECURSION 2

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Conditionals: Making Choices

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

11.3 Function Prototypes

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

RECURSION: n. SEE RECURSION 3

RECURSION, RECURSION, (TREE) RECURSION! 3

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion


DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Chapter 1. Fundamentals of Higher Order Programming

Python lab session 1

Control Structures 1 / 17

Answers to review questions from Chapter 2

Organization of Programming Languages CS3200/5200N. Lecture 11

cs1114 REVIEW of details test closed laptop period

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

How to Design Programs

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS 1301 CS1 with Robots Summer 2007 Exam 1

RECURSION, RECURSION, (TREE) RECURSION! 2

Algorithm Design and Recursion. Search and Sort Algorithms

ENGR 102 Engineering Lab I - Computation

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Software Development. Modular Design and Algorithm Analysis

Control structure: Repetition - Part 2

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams

ENVIRONMENT DIAGRAMS AND RECURSION 2

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

At full speed with Python

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

RECURSION, RECURSION, (TREE) RECURSION! 3

Introduction to Functional Programming

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Chapter 5: Recursion

CS1 Recitation. Week 2

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

CS1 Lecture 5 Jan. 25, 2019

>>> * *(25**0.16) *10*(25**0.16)

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

COMP 202 Java in one week

Fundamentals of Programming (Python) Getting Started with Programming

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Accelerating Information Technology Innovation

Loops / Repetition Statements

Math Day 2 Programming: How to make computers do math for you

DM550 Introduction to Programming part 2. Jan Baumbach.

Test #2 October 8, 2015

Python for Informatics

RECURSION AND LINKED LISTS 3

Homework 3 COSE212, Fall 2018

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

CONTROL AND HIGHER ORDER FUNCTIONS 1

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

CS 112: Intro to Comp Prog

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Constructing Algorithms and Pseudocoding This document was originally developed by Professor John P. Russo

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Data structure and algorithm in Python

Functions with Parameters and Return Values

CS1 Lecture 5 Jan. 26, 2018

CSI33 Data Structures

CS1110 Lab 6 (Mar 17-18, 2015)

CSC326 Python Imperative Core (Lec 2)

Introduction to Computer Programming for Non-Majors

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

A Brief Introduction to Scheme (I)

Accelerating Information Technology Innovation

Course Outline. Introduction to java

Transcription:

DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/!

RECURSION 2

Recursion a function can call other functions a function can call itself such a function is called a recursive function Example 1: def countdown(n): if n <= 0: print "Ka-Boooom!" else: print n, "seconds left!" countdown(n-1) countdown(3) 3

Stack Diagrams for Recursion main countdown n è 3 countdown n è 2 countdown n è 1 countdown n è 0 4

Recursion a function can call other functions a function can call itself such a function is called a recursive function Example 2: def polyline(t, n, length, angle): for i in range(n): fd(t, length) lt(t, angle) 5

Recursion a function can call other functions a function can call itself such a function is called a recursive function Example 2: def polyline(t, n, length, angle): if n > 0: fd(t, length) lt(t, angle) polyline(t, n-1, length, angle) 6

Infinite Recursion base case = no recursive function call reached we say the function call terminates Example 1: n == 0 in countdown / polyline infinite recursion = no base case is reached also called non-termination Example: def infinitely_often(): infinitely_often() Python has recursion limit 1000 ask sys.getrecursionlimit() 7

Keyboard Input so far we only know input() what happens when we enter Hello? input() treats all input as Python expression <expr> for string input, use raw_input() what happens when we enter 42? raw_input() treats all input as string both functions can take one argument prompt Example 1: a = input("first side: ") Example 2: name = raw_input("your name:\n") \n denotes a new line: print "Hello\nWorld\n!" 8

Debugging using Tracebacks error messages in Python give important information: where did the error occur? what kind of error occurred? unfortunately often hard to localize real problem Example: real problem error reported def determine_vat(base_price, vat_price): factor = base_price / vat_price reverse_factor = 1 / factor return reverse_factor - 1 print determine_vat(400, 500) 9

Debugging using Tracebacks error messages in Python give important information: where did the error occur? what kind of error occurred? unfortunately often hard to localize real problem Example: def determine_vat(base_price, vat_price): factor = float(base_price) / vat_price reverse_factor = 1 / factor return reverse_factor - 1 print determine_vat(400, 500) 10

FRUITFUL FUNCTIONS 11

Return Values so far we have seen only functions with one or no return sometimes more than one return makes sense Example 1: def sign(x): if x < 0: return -1 elif x == 0: return 0 else: return 1 12

Return Values so far we have seen only functions with one or no return sometimes more than one return makes sense Example 1: def sign(x): if x < 0: return -1 elif x == 0: return 0 return 1 important that all paths reach one return 13

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 14

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance print "dx:", dx 15

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance print "dx:", dx dy = y2 - y1 print "dy:", dy # vertical distance 16

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance print "dx:", dx dy = y2 - y1 print "dy:", dy dxs = dx**2; dys = dy**2 print "dxs dys:", dxs, dys # vertical distance 17

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 print "dxs dys:", dxs, dys 18

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 print "dxs dys:", dxs, dys ds = dxs + dys # square of distance print "ds:", ds 19

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 ds = dxs + dys # square of distance print "ds:", ds 20

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 ds = dxs + dys # square of distance print "ds:", ds d = math.sqrt(ds) # distance print d 21

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 ds = dxs + dys # square of distance d = math.sqrt(ds) # distance print d 22

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): print "x1 y1 x2 y2:", x1, y1, x2, y2 dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 ds = dxs + dys # square of distance d = math.sqrt(ds) # distance print d return d 23

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance dxs = dx**2; dys = dy**2 ds = dxs + dys # square of distance d = math.sqrt(ds) # distance return d 24

Incremental Development Idea: test code while writing it Example: computing the distance between (x 1,y 1 ) and (x 2,y 2 ) def distance(x1, y1, x2, y2): dx = x2 - x1 # horizontal distance dy = y2 - y1 # vertical distance return math.sqrt(dx**2 + dy**2) 25

Incremental Development Idea: test code while writing it 1. start with minimal function 2. add functionality piece by piece 3. use variables for intermediate values 4. print those variables to follow your progress 5. remove unnecessary output when function is finished 26

Composition function calls can be arguments to functions direct consequence of arguments being expressions Example: area of a circle from center and peripheral point def area(radius): return math.pi * radius**2 def area_from_points(xc, yc, xp, yp): return area(distance(xc, yc, xp, yp)) 27

Boolean Functions boolean functions = functions that return True or False useful e.g. as <cond> in a conditional execution Example: def divides(x, y): if y / x * x == y: # remainder of integer division is 0 return True return False 28

Boolean Functions boolean functions = functions that return True or False useful e.g. as <cond> in a conditional execution Example: def divides(x, y): if y % x == 0: # remainder of integer division is 0 return True return False 29

Boolean Functions boolean functions = functions that return True or False useful e.g. as <cond> in a conditional execution Example: def divides(x, y): return y % x == 0 30

Boolean Functions boolean functions = functions that return True or False useful e.g. as <cond> in a conditional execution Example: def divides(x, y): return y % x == 0 def even(x): return divides(2, x) 31

Boolean Functions boolean functions = functions that return True or False useful e.g. as <cond> in a conditional execution Example: def divides(x, y): return y % x == 0 def even(x): return divides(2, x) def odd(x): return not divides(2, x) 32

Boolean Functions boolean functions = functions that return True or False useful e.g. as <cond> in a conditional execution Example: def divides(x, y): return y % x == 0 def even(x): return divides(2, x) def odd(x): return not even(x) 33

RECURSION: SEE RECURSION 34

Recursion is Complete so far we know: values of type integer, float, string arithmetic expressions (recursive) function definitions (recursive) function calls conditional execution input/output ALL possible programs can be written using these elements! we say that we have a Turing complete language 35

Factorial in mathematics, the function is defined by 0! = 1 n! = n * (n-1)! such recursive definitions can trivially be expressed in Python Example: def (n): if n == 0: return 1 recurse = (n-1) result = n * recurse return result x = (3) 36

Stack Diagram for Factorial main n è 3 n è 2 n è 1 n è 0 37

Stack Diagram for Factorial main n è 3 n è 2 n è 1 n è 0 1 38

Stack Diagram for Factorial main n è 3 n è 2 n è 1 recurse è 1 n è 0 1 39

Stack Diagram for Factorial main n è 3 n è 2 n è 1 recurse è 1 result è 1 n è 0 1 40

Stack Diagram for Factorial main n è 3 n è 2 n è 1 recurse è 1 result è 1 n è 0 1 1 41

Stack Diagram for Factorial main n è 3 n è 2 recurse è 1 n è 1 recurse è 1 result è 1 n è 0 1 1 42

Stack Diagram for Factorial main n è 3 n è 2 recurse è 1 result è 2 n è 1 recurse è 1 result è 1 n è 0 1 1 43

Stack Diagram for Factorial main n è 3 n è 2 recurse è 1 result è 2 n è 1 recurse è 1 result è 1 n è 0 2 1 1 44

Stack Diagram for Factorial main n è 3 recurse è 2 n è 2 recurse è 1 result è 2 n è 1 recurse è 1 result è 1 n è 0 2 1 1 45

Stack Diagram for Factorial main n è 3 recurse è 2 result è 6 n è 2 recurse è 1 result è 2 n è 1 recurse è 1 result è 1 n è 0 2 1 1 46

Stack Diagram for Factorial main n è 3 recurse è 2 result è 6 n è 2 recurse è 1 result è 2 n è 1 recurse è 1 result è 1 n è 0 6 2 1 1 47

Stack Diagram for Factorial main x è 6 n è 3 recurse è 2 result è 6 n è 2 recurse è 1 result è 2 n è 1 recurse è 1 result è 1 n è 0 6 2 1 1 48

Leap of Faith following the flow of execution difficult with recursion alternatively take the leap of faith (induction) Example: def (n): if n == 0: return 1 recurse = (n-1) result = n * recurse return result x = (3) check the base case assume recursive call is correct check the step case 49

Control Flow Diagram Example: def (n): (n) if n == 0: return 1 recurse = (n-1) n == 0 False result = n * recurse return result recurse = (n-1) True result = n * recurse return result return 1 50

Fibonacci Fibonacci numbers model for unchecked rabbit population rabbit pairs at generation n is sum of rabbit pairs at generation n-1 and generation n-2 mathematically: fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2) Pythonically: def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) leap of faith required even for small n! 51

Control Flow Diagram Example: def fib(n): fib(n) if n == 0: return 0 elif n == 1: n == 0 False return 1 else: return fib(n-1) + fib(n-2) n == 1 False True True return fib(n-1) + fib(n-2) return 1 return 0 52

Types and Base Cases def (n): if n == 0: return 1 recurse = (n-1) result = n * recurse return result Problem: (1.5) exceeds recursion limit (0.5) (-0.5) (-1.5) 53

Types and Base Cases def (n): if n == 0: return 1 recurse = (n-1) result = n * recurse return result Idea: check type at beginning of function 54

Types and Base Cases def (n): if not isinstance(n, int): print "Integer required"; return None if n == 0: return 1 recurse = (n-1) result = n * recurse return result Idea: check type at beginning of function 55

Types and Base Cases def (n): if not isinstance(n, int): print "Integer required"; return None if n < 0: print "Non-negative number expected"; return None if n == 0: return 1 recurse = (n-1) result = n * recurse return result Idea: check type at beginning of function 56

Debugging Interfaces interfaces simplify testing and debugging 1. test if pre-conditions are given: do the arguments have the right type? are the values of the arguments ok? 2. test if the post-conditions are given: does the return value have the right type? is the return value computed correctly? 3. debug function, if pre- or post-conditions violated 57

Debugging (Recursive) Functions to check pre-conditions: print values & types of parameters at beginning of function insert check at beginning of function (pre assertion) to check post-conditions: print values before return statements insert check before return statements (post assertion) side-effect: visualize flow of execution 58

ITERATION 59

Multiple Assignment Revisited as seen before, variables can be assigned multiple times assignment is NOT the same as equality it is not symmetric, and changes with time Example: a = 42 b = a a = 23 from here, a and b are equal from here, a and b are different 60

Updating Variables most common form of multiple assignment is updating a variable is assigned to an expression containing that variable Example: x = 23 for i in range(19): x = x + 1 adding one is called incrementing expression evaluated BEFORE assignment takes place thus, variable needs to have been initialized earlier! 61

Iterating with While Loops iteration = repetition of code blocks can be implemented using recursion (countdown, polyline) while statement: <while-loop> => while <cond>: <instr 1 >; <instr 2 >; <instr 3 > Example: def countdown(n): n == 3 2 1 0 while n > 0: print n, "seconds left!" n = n - 1 print "Ka-Boom!" countdown(3) False True 62

Termination Termination = the condition is eventually False loop in countdown obviously terminates: while n > 0: n = n - 1 difficult for other loops: def collatz(n): while n!= 1: print n, if n % 2 == 0: # n is even n = n / 2 else: # n is odd n = 3 * n + 1 63

Termination Termination = the condition is eventually False loop in countdown obviously terminates: while n > 0: n = n - 1 can also be difficult for recursion: def collatz(n): if n!= 1: print n, if n % 2 == 0: # n is even collatz(n / 2) else: # n is odd collatz(3 * n + 1) 64

Breaking a Loop sometimes you want to force termination Example: while True: num = raw_input('enter a number (or "exit"):\n') if num == "exit": break n = int(num) print "Square of", n, "is:", n**2 print "Thanks a lot!" 65

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) for square root of a: f(x) = x 2 a f (x) = 2x simplifying for this special case: x n+1 = (x n + a / x n ) / 2 Example 1: while True: print xn xnp1 = (xn + a / xn) / 2 if xnp1 == xn: break xn = xnp1 66

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) Example 2: def f(x): return x**3 - math.cos(x) def f1(x): return 3*x**2 + math.sin(x) while True: print xn xnp1 = xn - f(xn) / f1(xn) if xnp1 == xn: break xn = xnp1 67

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) Example 2: def f(x): return x**3 - math.cos(x) def f1(x): return 3*x**2 + math.sin(x) while True: print xn xnp1 = xn - f(xn) / f1(xn) if math.abs(xnp1 - xn) < epsilon: break xn = xnp1 68

Algorithms algorithm = mechanical problem-solving process usually given as a step-by-step procedure for computation Newton s method is an example of an algorithm other examples: addition with carrying subtraction with borrowing long multiplication long division directly using Pythagora s formula is not an algorithm 69

Divide et Impera latin, means divide and conquer (courtesy of Julius Caesar) Idea: break down a problem and recursively work on parts Example: guessing a number by bisection def guess(low, high): if low == high: print "Got you! You thought of: ", low else: mid = (low+high) / 2 ans = raw_input("is "+str(mid)+" correct (>, =, <)?") if ans == ">": guess(mid,high) elif ans == "<": guess(low,mid) else: print "Yeehah! Got you!" 70

Debugging Larger Programs assume you have large function computing wrong return value going step-by-step very time consuming Idea: use bisection, i.e., half the search space in each step 1. insert intermediate output (e.g. using print) at mid-point 2. if intermediate output is correct, apply recursively to 2 nd part 3. if intermediate output is wrong, apply recursively to 1 st part 71