PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

Genome 559: Introduction to Statistical and Computational Genomics
Introduction to Recursion and Recursive Algorithms
Python Basics: Statements Expressions Loops Strings Functions.
Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
Modular Programming With Functions
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Monday, 12/9/02, Slide #1 CS 106 Intro to CS 1 Monday, 12/9/02  QUESTIONS??  On HW #5 (Due 5 pm today)  Today:  Recursive functions  Reading: Chapter.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
Topic 7 – Recursion (A Very Quick Look). CISC 105 – Topic 7 What is Recursion? A recursive function is a function that calls itself. Recursive functions.
Chapter 2 Writing Simple Programs
Structure of program You must start with a module import# You must then encapsulate any while loop in a main function at the start of the program Then.
CS 116 Tutorial 5 Introduction to Python. Review Basic Python Python is a series of statements def f(p1, p2,…pn): x = 5 if x > p1: x = p1 + p2 return.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
1 Chapter 18-1 Recursion Dale/Weems. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
C++ Beginner Tutorial: Functions IV Recursion. What is recursion? A property of function to be able to call itself… Get factorial of a given number: Factorial.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #001 (January 9, 2015)
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 9 Iteration: Recursion 5/02/09 Python Mini-Course: Day 3 - Lesson 9 1.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Algorithmic Recursion. Recursion Alongside the algorithm, recursion is one of the most important and fundamental concepts in computer science as well.
Recursion.
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
Data Structures Recursion Phil Tayco Slide version 1.0 Mar. 8, 2015.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 12: A few other things.
How to start Visual Studio 2008 or 2010 (command-line program)
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Functions Chapter 4 Python for Informatics: Exploring Information
Recursion, pt. 1 The Foundations. What is Recursion? Recursion is the idea of solving a problem in terms of itself. – For some problems, it may not possible.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Question : How many different ways are there to climb a staircase with n steps (for example, 100 steps) if you are allowed to skip steps, but not more.
Python Functions : chapter 3
W1-1 University of Washington Computer Programming I Recursion © 2000 UW CSE.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Recursion Function calling itself
Python Basics.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Java 4/4/2017 Recursion.
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Algorithm design and Analysis
Lecture 5 Fruitful Functions
Coding Concepts (Basics)
Unit 3 Test: Friday.
Lesson #6 Modular Programming and Functions.
Recursion Taken from notes by Dr. Neil Moore
Recursion Review Spring 2019 CS 1110
Recursion Examples.
Lecture 6 - Recursion.
Presentation transcript:

PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST

RETURN VALUES The majority of functions return a value such as those we have been using from the math module such as sqrt(), sin() and atan2(). We of course can write our own and will do so often. Lets look at a few as examples(math is assumed to be imported) def absolute_value(x) if x<0: return –x else: return x def VolumeSphere(r) v = 4/3*pi*r**3 def distance(x1,y1,x2,y2) temp = (x2-x1)**2+(y2-y1)**2 return sqrt(temp)

INCREMENTAL DEVELOPMENT One does not need to write the entire function initially during development. Start with as “stub” and let it grow!! For example we could start the distance function this way. def distance(x1,y1,x2,y2) return 0 We can then test it to see if the call works. Simple things can be tested within the interactive mode or in script mode if they are more complicated. >>>distance(2,1,3,4) 0

CONTINUING WE HAVE def distance(x1,y1,x2,y2) temp = (x2-x1)**2+(y2-y1)**2 return temp #And test it >>>distance(1,2,3,4) 8 #And then the final step is def distance(x1,y1,x2,y2) temp = (x2-x1)**2+(y2-y1)**2 return sqrt(temp) Check this by hand (3-1)**2 is 4 (4-2)**2 is 4 so the answer should be 8 You might need to check other cases as well for some functions

INTERMEDIATE PRINTING def distance(x1,y1,x2,y2) temp = (x2-x1)**2+(y2-y1)**2 print ‘The value of temp is’,temp return sqrt(temp) Generally you should slowly build a function by adding a line at a time, often using prints to check intermediate results. Study the example in chapter 6.0 This is very important to do. WHY. BECAUSE when something goes wrong YOU know where the error is. CAPICE!

COMPOSITION It is often the case that you call functions within functions. Here is an example you may have already seen def polygon(t,n,length): angle = 360.0/n for i in range(n): fd(t,length) lt(t,angle) def circle(t,r): circumference = 2 * pi * r n = int(circumference /3)+1 length = circumference / n polygon(t,n,length) Be sure and put polygon() before circle() in the script!

RECURSION It is even ok to call yourself !!!!!!! If you do so it is called recursion. Lets look at a very simple example. You may recall that the mathematical operation factorial looks like 5! = 5*4*3*2*1 or in general N! = N*(N-1)*(N-2)*(N-3) * … * 2*1 or it can be defined in terms of itself as N! = N * (N-1)! where 0! =1 (base case)

AN INTERESTING EXAMPLE To become a citizen at birth, you must: Have been born in the United States or certain territories or outlying possessions of the United States, and subject to the jurisdiction of the United States; OR had a parent or parents who were citizens at the time of your birth (if you were born abroad) and meet other requirementsborn abroad Note that the definition of citizenship is defined recursively!

FACTORIAL IN PYTHON RECURSIVELY def factorial(n) if n == 0: return 1 else: return n * factorial(n-1) Test this out! # print the first 10 factorials for i in range(10): print factorial(i) output is Just how big a factorial can Python handle?

HERE IS THEN END OF FACTORIAL(50) Try factorial(100) or more

FIBONACCI SEQUENCE The Fibonacci sequence is very well known. It has a serious relationship with biological feedback loops (rabbit reproduction, cellular growth, botanical structure etc.) see Its definition is almost always stated recursively Fib(1) = 1 Fib(2) = 1 Fib(n) = Fib(n-1) + F(n-2) and so on. +

FIBONACCI IN PYTHON Definition is Fib(1) = 1 Fib(2) = 1 Fib(n) = Fib(n-1) + F(n-2) #method 1 def Fib(n): if n==1: return 1 elif n==2: return 2 else: return Fib(n-1)+Fib(n-2) #method 2 def Fib(n): if n==1 or n==2: return 1 else: return Fib(n-1)+Fib(n-2)

A RUN def Fib(n): if n==1 or n==2: return 1 else: return Fib(n-1)+Fib(n-2) for i in range(20): print Fib(i+1), >>> >>> As n in Fib(n) gets larger something happens. Try Fib(30)

WHAT IF YOU REQUEST FIB(2.2)? You get something like the following. File "C:/PythonCode/factorial.py", line 7, in Fib return Fib(n-1)+Fib(n-2) File "C:/PythonCode/factorial.py", line 7, in Fib return Fib(n-1)+Fib(n-2) ……………………………. File "C:/PythonCode/factorial.py", line 7, in Fib return Fib(n-1)+Fib(n-2) File "C:/PythonCode/factorial.py", line 7, in Fib return Fib(n-1)+Fib(n-2) File "C:/PythonCode/factorial.py", line 4, in Fib if n==1 or n==2: RuntimeError: maximum recursion depth exceeded in cmp >>> What’s up with that?

WE CAN CHECK THE ARGUMENT TYPE def Fib(n): if not isinstance(n,int): print ‘Fib is only defined for integers.’ return # Don’t return a value here if n<0: print ‘Fib is not defined for negative numbers’ return # Don’t return a value or here if n==1 or n==2: return 1 else: return Fib(n-1)+Fib(n-2) Guardian code If the argument is incorrect get out of here! Returns true if n is an integer! There a little issue here? It slows it down somewhat!

A STRING EXAMPLE Write a recursive function to test if a string is a palindrome. Remember we can access each character in a string via subscripting. Name = ‘risttsir’ Here Name[0] is r, Name[1] is I, Name[2] is s, and so on Also Name[-1] is the last character of the string, i.e. r To test for this attribute we can do the following if the first char is equal to the last character and the middle section is a palindrome then the string is a palindrome. You agree?

THE CODE ( A BOOLEAN EXAMPLE) word = ‘asdfghiihgfdsa’ word[0] word[-1] word[1:-1] def is_palin(w): if len(w)==0 or len(w)==1: #base case return True if w[0]==w[-1]: # is first == last? return is_palin(w[1:-1]) #this is the middle else: return False