Functions and Recursion

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

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

Conditionals and Recursion. Python Part 4

DM502 Programming A. Peter Schneider-Kamp.

CSC326 Python Imperative Core (Lec 2)

RECURSION: n. SEE RECURSION 3

Test #2 October 8, 2015

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

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

CS1 Lecture 15 Feb. 19, 2018

Conditionals: Making Choices

Fundamentals of Programming Session 13

Introduction to Recursion

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

Last week. Another example. More recursive examples. How about these functions? Recursive programs. CSC148 Intro. to Computer Science

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

CS 1301 CS1 with Robots Summer 2007 Exam 1

DM502 Programming A. Peter Schneider-Kamp.

Instructors: Daniel Deutch, Amir Rubinstein, Teaching Assistants: Amir Gilad, Michal Kleinbort

ITERATION AND RECURSION 3

EE 368. Weeks 4 (Notes)

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

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Chapter 5: Control Structures

Python Crash Course. João Pedro Pedroso. Departmento de Ciência de Computadores Faculdade de Ciências, Universidade do Porto

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Why Is Repetition Needed?

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

61A Lecture 3. Friday, September 5

RECURSION, RECURSION, (TREE) RECURSION! 3

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

Python Boot Camp. Day 3

RECURSION, RECURSION, (TREE) RECURSION! 2

DM536 Introduction to Programming. Peter Schneider-Kamp.

Recursion. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

CISC 3115 TY3. C21a: Recursion. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/6/2018 CUNY Brooklyn College

Data structure and algorithm in Python

DM536 Introduction to Programming. Peter Schneider-Kamp.

Control structure: Repetition - Part 2

ENVIRONMENT DIAGRAMS AND RECURSION 2

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

CSI 32. Lecture 15. Chapter 11 Recursion Functional Recursion 11.4 Binary Search

CSE 230 Intermediate Programming in C and C++ Recursion

PROGRAMMING FUNDAMENTALS

Python for Informatics

Introduction to Problem Solving and Programming in Python.

1.7 Recursion. Department of CSE

recursive algorithms 1

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Chapter 4 Introduction to Control Statements

n 1 i = n + i = n + f(n 1)

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

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Lecture 15. Lecturer: Prof. Sergei Fedotov Calculus and Vectors. Length of a Curve and Parametric Equations

IT 1033: Fundamentals of Programming Loops

Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

COP 4020 Fall 2005 Presentation Joshua Burkholder 2005 NOV 27. Recursion. What, Why, How, When, and What If?

ENVIRONMENT DIAGRAMS AND RECURSION 2

Introduction to Python

Control Structures 1 / 17

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

RECURSION, RECURSION, (TREE) RECURSION! 3

Algorithms and Data Structures

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Chapter 7. Iteration. 7.1 Multiple assignment

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CS116 - Module 5 - Accumulative Recursion

A library of recursive functions

CONTROL AND HIGHER ORDER FUNCTIONS 1

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

Module 05: Types of recursion

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

8. Control statements

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Repetition and Loop Statements Chapter 5

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Chapter 4: Conditionals and Recursion

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

MEIN 50010: Python Recursive Functions

REPETITION CONTROL STRUCTURE LOGO

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

ALGORITHM DESIGN DYNAMIC PROGRAMMING. University of Waterloo

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

Compound Data Types 1

15-110: Principles of Computing Sample Exam #1

Chapter 15: Recursion

A Function that Calls Itself. It Doesn t Do Anything! Defining a Recursive Function. 2) Base Case. 1) Divide and Conquer 11/22/2010

Programming Languages and Program Development Life Cycle Fall Introduction to Information and Communication Technologies CSD 102

a function that calls itself It doesn t do anything! Defining a recursive function 1) divide and conquer 2) base case 6/21/2018 chapter 15

Programming for Engineers Iteration

Transcription:

Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it

Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2

Absolute value Which one is correct? def absolutevalue(x): if x < 0: return x else: return x def absolutevalue(x): if x < 0: return x elif x > 0: return x

Incremental development Writing larger functions implies spending more time debugging. Incremental development: an approach to deal with increasingly complex programs.. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time.

Example: distance between two points Pitagora Theorem - (x1,y1) - (x2,y2) distance = x2 x1 2 y2 y1 2

First step The first step is to consider what a distance functions should look like in Python. what are the inputs (parameters)? what is the output (return value)? def distance(x1, y1, x2, y2): return 0.0 TEST? >>> distance(1, 2, 4, 6) 0.0

Second step def distance(x1, y1, x2, y2): dx = x2 x1 dy = y2 y1 print "dx is", dx print "dy is", dy return 0.0

Third step def distance(x1, y1, x2, y2): dx = x2 x1 dy = y2 y1 dsquared = dx**2 + dy**2 print "dsquared is: ", dsquared return 0.0

Fourth step def distance(x1, y1, x2, y2): dx = x2 x1 dy = y2 y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result

Summary 1) Start with a small working program and modify it introducing and testing small incremental changes. 3) Use local variables to store intermediate values so that you can print and test them. 3) Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.

Exercise 1 - Debugging

Exercise 2 Write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle. Hints: Represent the two points respectively with variables x1, y1 and variables x2, y2. Can you compute the radius of this circle?

Recursion It is legal for one function to call another. It is also legal for a function to call itself. A function that calls itself is recursive; the process is called recursion. def countdown(n): if n == 0: print "Blastoff!" else: print n countdown(n 1)

Tracing a recursive function def countdown(n): if n == 0: print "Blastoff!" else: print n countdown(n 1) >>>countdown(3) 3 2 1 Blastoff! countdown(3) 3 countdown(2) 2 countdown(1) 1 countdown(0) Blastoff! return return return return

What is doing? def nlines(n): if n > 0: print nlines(n 1)

Stack diagrams Stack diagrams can help interpret a recursive function. For a recursive function, there might be more than one frame on the stack at the same time. The four frames have different values for the parameter n. The bottom of the stack, where n=0, is called the base case.

Infinite recursion! The base case is fundamental for termination. If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. def recurse(): recurse() >>>recurse() File "<stdin>", line 2, in recurse (98 repetitions omitted) File "<stdin>", line 2, in recurse RuntimeError: Maximum recursion depth exceeded

Defining recursive functions Analyse the base case carefully (termination). Implement the function. Verify if the following conditions hold: The recursive call should approach the base case. The base case works (testing it) If these conditions hold the recursive function should work correctly.

Use of recursion We have seen two programs that use recursion to perform repetition, which is also called iteration. Thus, recursion can be used to perform repetition. Several mathematical functions are implemented in a natural way using recursive functions.

A calculator exit = False def calculator(command): prompt = "Enter an expression: " command = input(prompt) if not command: return print "the result is ", command calculator(command) calculator(true)

Exercise 3 & 4 There is a semantic error in the calculator program, are you able to find it? Write a dummy python interpreter that always returns syntax error.

Example Factorial 0! = 1 n! = n (n-1)! def factorial(n): if n == 0: return 1

Factorial (cont) def factorial(n): if n == 0: return 1 else: recurse = factorial(n 1) result = n * recurse return result def factorial(n): if n == 0: return 1 else: return n * factorial(n 1)

Exercise 5 One of the most common example of a recursively defined mathematical function is the the fibonacci function, which has the following definition: fibonacci(0) = 1 fibonacci(1) = 1 fibonacci(n) = fibonacci(n 1) + fibonacci(n 2); Write a python script which includes a recursive fibonacci function and test it with several values

Exercise: Ackermann Function