DM502 Programming A. Peter Schneider-Kamp.

Similar documents
DM536 Introduction to Programming. Peter Schneider-Kamp.

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

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

DM502 Programming A. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM503 Programming B. Peter Schneider-Kamp.

DM536 Programming A. Peter Schneider-Kamp.

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

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

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

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

ITERATION AND RECURSION 3

ENVIRONMENT DIAGRAMS AND RECURSION 2

RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION: n. SEE RECURSION 3

Recursion. Fundamentals of Computer Science

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

ENVIRONMENT DIAGRAMS AND RECURSION 2

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

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

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

Answers to review questions from Chapter 2

Functions and Recursion

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

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

RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION, RECURSION, (TREE) RECURSION! 2

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

CS1 Recitation. Week 2

Chapter 5: Recursion

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

An introduction to Scheme

Python lab session 1

Conditionals: Making Choices


Algorithm Design and Recursion. Search and Sort Algorithms

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

Control Structures 1 / 17

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

11.3 Function Prototypes

Control structure: Repetition - Part 2

Software Development. Modular Design and Algorithm Analysis

Measuring Efficiency

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Recursion CS GMU

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

At full speed with Python

More Complicated Recursion CMPSC 122

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

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

This session. Recursion. Planning the development. Software development. COM1022 Functional Programming and Reasoning

Recursive Definitions

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CSCI 121: Recursive Functions & Procedures

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

Introduction to Scientific Computing

RECURSION AND LINKED LISTS 3

DM502 Programming A. Peter Schneider-Kamp.

Department of Mathematical Sciences, FAU. Instructions:

Data structure and algorithm in Python

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

Reals 1. Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method.

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Flow Control: Branches and loops

ENGR 102 Engineering Lab I - Computation

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

CSC 1351: Quiz 6: Sort and Search

Loops / Repetition Statements

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

Chapter 1. Fundamentals of Higher Order Programming

Unit #2: Recursion, Induction, and Loop Invariants

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Fruitful Recursion (recursion that returns a value)

APCS-AB: Java. Recursion in Java December 12, week14 1

DM550 Introduction to Programming part 2. Jan Baumbach.

TECH. Recurrence Equations vs. Recursive Procedures. Recursion and Induction. e.g. Fibonacci Function. The working of recursive procedure

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

Chapter 7. Iteration. 7.1 Multiple assignment

Streams and Evalutation Strategies

CSc 110, Spring 2017 Lecture 39: searching

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Lecture 22. While Loops

Exercise 1 ( = 24 points)

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Introduction to Programming I

Variable and Data Type I

Intro. Scheme Basics. scm> 5 5. scm>

Fundamentals of Programming (Python) Getting Started with Programming

BBM 101. Introduction to Programming I. Lecture #06 Recursion

Transcription:

DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/!

Python & Linux Install Party Tomorrow (Tuesday, September 12) from 10 14 Fredagsbar (area south of Kantine II) Participants are those who want Python (& Swampy) on their computer, who want Linux on their computer, who want some study-related software on their computer, who have problems with some study related software, or who just like to hang out and help other people! drinks and some snacks will be provided by IMADA! 2

RECURSION: SEE RECURSION 3

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 4

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) 5

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

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

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

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

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

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

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

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

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 14

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 15

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 16

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 17

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 18

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 19

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! 20

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 21

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) 22

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 23

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 24

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 25

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 26

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 27

ITERATION 28

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 29

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! 30

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 31

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 32

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) 33

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!" 34

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 35

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 36

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 37

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 38

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!" 39

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 40

STRINGS 41

Strings as Sequences strings can be viewed as 0-indexed sequences Examples: "Slartibartfast"[0] == "S" "Slartibartfast"[1] == "l" "Slartibartfast"[2] == "Slartibartfast"[7] "Phartiphukborlz"[-1] == "z" grammar rule for expressions: <expr> => <expr 1 >[<expr 2 >] <expr 1 > = expression with value of type string index <expr 2 > = expression with value of type integer negative index counting from the back 42

Length of Strings length of a string computed by built-in function len(object) Example: name = "Slartibartfast" length = len(name) print name[length-4] Note: name[length] gives runtime error identical to write name[len(name)-1] and name[-1] more general, name[len(name)-a] identical to name[-a] 43