Fundamentals of Programming I Design with Functions

Slides:



Advertisements
Similar presentations
Computer Science 111 Fundamentals of Programming I
Advertisements

COMPSCI 105 S Principles of Computer Science Recursion 1.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Program Design and Development
Fundamentals of Python: From First Programs Through Data Structures
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
Lecture 8. How to Form Recursive relations 1. Recap Asymptotic analysis helps to highlight the order of growth of functions to compare algorithms Common.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Chapter 15: Advanced Topics: Introducing Data Structures and Recursion Visual Basic.NET Programming: From Problem Analysis to Program Design.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
1 CS161 Introduction to Computer Science Topic #9.
Data Structure and Algorithms. Algorithms: efficiency and complexity Recursion Reading Algorithms.
Lecture 7. Solution by Substitution Method T(n) = 2 T(n/2) + n Substitute n/2 into the main equation 2T(n/2) = 2(2(T(n/4)) + n/2) = 4T(n/4) + n And T(n)
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Fundamentals of Python: First Programs Chapter 6: Design with Functions.
Question of the Day  What three letter word completes the first word and starts the second one: DON???CAR.
A First Book of ANSI C Fourth Edition
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion (Continued) Prof. Katherine Gibson Prof. Jeremy Dixon Based on slides from UPenn’s.
Recursion Powerful Tool
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Chapter 19: Recursion.
Recursion Version 1.0.
Computer Science 111 Fundamentals of Programming I
Introduction to Computing Science and Programming I
CMSC201 Computer Science I for Majors Lecture 20 – Recursion (Continued) Prof. Katherine Gibson Based on slides from UPenn’s CIS 110, and from previous.
Chapter 15 Recursion.
Introduction to Recursion
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Introduction to Computing Science and Programming I
Fundamentals of Programming I A Sentence Generator
Introduction To Repetition The for loop
Chapter 6: Modular Programming
Chapter 15 Recursion.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Java 4/4/2017 Recursion.
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
Fundamentals of Programming I Dictionaries redux
Chapter 6 Functions.
Applied Algorithms (Lecture 17) Recursion Fall-23
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Functions Recursion CSCI 230
Recursion Chapter 18.
Computer Science 111 Fundamentals of Programming I
Week 4 Lecture-2 Chapter 6 (Methods).
Recursion Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Another Example Problem
Last Class We Covered Recursion Stacks Parts of a recursive function:
Algorithms, Part 3 of 3 Topics Top down-design Structure charts
Text Files and Random Numbers
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Topics Introduction to File Input and Output
CMSC201 Computer Science I for Majors Lecture 12 – Program Design
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Recursive functions.
Lecture 6 - Recursion.
Presentation transcript:

Fundamentals of Programming I Design with Functions Computer Science 111 Fundamentals of Programming I Design with Functions

Why Design? As problems become more complex, so do their solutions There is more to programming than just hacking out code We can decompose a complex problem into simpler subproblems and solve each of these Divide up the work and assign responsibilities to individual actors (functions)

Top-Down Design In top-down design, we decompose a complex problem into simpler subproblems, and solve these with different functions. Function-1 Function-2 Function-3 Function-4 Function-5 Function-6 Function-7

Example: The doctor Program Each function has its own responsibilities; in a well-designed program, no function does too much main input reply random.choice changePerson

Example: The doctor Program Functions communicate via arguments and returned values main string reply string string changePerson string

Example: The doctor Program Functions also go to shared data pools for information Data Pool hedges qualifiers replacements string string main string string reply string string changePerson string

Example: The Sentence Program main string sentence string string nounPhrase verbPhrase string string nounPhrase prepositionalPhrase string nounPhrase articles nouns verbs prepositions Data Pool

Design Strategies: Top Down Start with the main function and pretend that the functions that it calls are already defined Work your way down by defining those functions, etc. Cannot test anything until they’re all finished

Drivers and Stubs Start with the main function and pretend that the functions that it calls are already defined Define these functions using simple headers and almost no code If a function returns a value, return a reasonable default (0 or empty string) If a function does not return a value, return None The main function is known as a driver, and the other functions are called stubs

Skeletal Design Drivers/stubs allow you to sketch out the structure of a program in terms of cooperating functions without finishing everything at once Set up their communication links, which are the arguments and return values Run the program to check these before filling in the details

Design Strategies: Bottom Up Start with simple functions at the bottom of the chart and work your way up Each new function can be tested as soon as it’s defined Easier to get the little pieces of a program up and running, then integrate them into a more complete solution

Good Design? Do you divide up the work so that each function does one coherent thing? Do the functions communicate via arguments and return values rather than a common pool of data? When a common pool of data seems necessary, do you confine access to just a few functions? Do you name the functions and arguments to reflect their purpose in the program? Do you document your design?????

Recursive Design As a special case of top-down design, we decompose a problem into smaller subproblems that have the same form, and solve these with the same function. Function-1 Function-1 Function-1

Recursive Design As a special case, we decompose a problem into smaller subproblems that have the same form, and solve these with the same function. sentence = nounPhrase verbPhrase [ “and” sentence ] sentence nounPhrase verbPhrase sentence

Example: Get a Valid Integer The function getValidInteger prompts the user for an integer and inputs it The integer is returned if it is within the specified range Otherwise, the function displays an error message and calls getValidInteger to try again

Define a Recursive Function def getValidInteger(prompt, low, high): number = int(input(prompt)) if number >= low and number <= high: return number else: print('ERROR: Input number is out of range') return getValidInteger(prompt, low, high) A recursive function calls itself There will be 0 or more recursive calls of this function A recursive process is similar to an iterative process (the same thing is done repeatedly, 0 or more times)

The Base Case A recursive process stops when a base case is reached def getValidInteger(prompt, low, high): number = int(input(prompt)) if number >= low and number <= high: return number else: print('ERROR: Input number is out of range') return getValidInteger(prompt, low, high) A recursive process stops when a base case is reached In this function, a valid input number is simply returned

The Recursive Step def getValidInteger(prompt, low, high): number = int(input(prompt)) if number >= low and number <= high: return number else: print('ERROR: Input number is out of range') return getValidInteger(prompt, low, high) Otherwise, a recursive step drives the recursion forward, until a base case is reached

Computing Factorial (!) 4! = 4 * 3 * 2 * 1 = 24 N! = N * (N - 1) * (N - 2) * … * 1 Recursive definition of factorial: N! = 1, when N = 1 N! = N * (N - 1)!, otherwise

Define factorial Recursively # N! = 1, when N = 1 # N! = N * (N - 1)!, otherwise def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) What is the base case? What is the recursive step? Does the recursive step advance the process toward the base case?

Tracing factorial # N! = 1, when N = 1 # N! = N * (N - 1)!, otherwise def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) >>> factorial(4) # With a trace of the process n = 4 n = 3 n = 2 n = 1 factorial(1) = 1 factorial(2) = 2 factorial(3) = 6 factorial(4) = 24

Gathering File System Stats Count the files Get the size of a directory (number of bytes) D D F F F D F F F F D F F F

Modules os and os.path os.getcwd() os.listdir(dirname) os.chdir(dirname) os.path.isfile(name) os.path.isdir(name) os.path.getsize(filename) Define functions: countFiles(dirname) getSize(dirname)

Counting the Files Use a recursive strategy Sum all of the items in the current directory If the item is a file, add 1 Otherwise, the item is a directory, so add the count obtained from a recursive call of the function

Define and Use countFiles import os import os.path def countFiles(dirname): """Counts the files in a directory and its subdirectories.""" count = 0 listOfItems = os.listdir(dirname) for item in listOfItems: if os.path.isfile(item): count += 1 # It’s a file else: os.chdir(item) # It’s a directory count += countFiles(os.getcwd()) os.chdir("..") return count countFiles(os.getcwd())

Summary A recursive algorithm passes the buck repeatedly to the same function Recursive algorithms are well-suited for solving problems in domains that exhibit recursive patterns Recursive strategies can be used to simplify complex solutions to difficult problems

Read Section 6.5 on managing the namespace For Wednesday Read Section 6.5 on managing the namespace