PPT3. Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?

Slides:



Advertisements
Similar presentations
What gets printed out? def f(n): if (n == 0): return (" ") else: print(“blug ") return f(n-1) f(3)
Advertisements

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
ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Introduction to Computing Science and Programming I
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
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.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Algorithms: Selected Exercises Goals Introduce the concept & basic properties of an algorithm.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in python!
PPT 2. Other things: functions  Can you have a function with no inputs?  Yes: def f( ): return (3 + 4 )  Can you have a function with no outputs? 
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
PAGES:51-59 SECTION: CONTROL1 : DECISIONS Decisions.
Programming Training Main Points: - Problems with repetitions. - Discuss some important algorithms.
1 Logical Assertions. 2 Logical assertions assertion: A statement that is either true or false. Examples: –Java was created in –The sky is purple.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
PPT 4. Variables: (assignment)  A variable: holds a value.  A space in RAM we give a name to  A lot like parameters, only we create them within the.
REVIEW A relation is a set of ordered pairs. {(2,3), (-1,5), (4,-2), (9,9), (0,-6)} This is a relation The domain is the set of all x values.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Strings:  Strings?  concatenate (join) +  make multiple copies using *  compare: > =
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Largest of x random numbers def find_largest(x,y): largest = 0; count = 0; while count < x: rnum = randrange(0,y) if rnum > largest: largest = rnum count.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Week 61 Introduction to Programming Ms. Knudtzon C Period Tuesday October 12.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
GCSE Computing: Programming GCSE Programming Remembering Python.
The ‘while’ loop ‘round and ‘round we go.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
A Introduction to Computing II Lecture 5: Complexity of Algorithms Fall Session 2000.
1 CS1110 Lecture 16, 26 Oct 2010 While-loops Reading for next time: Ch (arrays) Prelim 2: Tu Nov 9 th, 7:30-9pm. Last name A-Lewis: Olin 155 Last.
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in python!
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
CompSci Today’s Topics Computer Science Noncomputability Upcoming Special Topic: Enabled by Computer -- Decoding the Human Genome Reading Great.
1 Recursive Definitions and Structural Induction CS/APMA 202 Rosen section 3.4 Aaron Bloomfield.
LISTS: A NEW TYPE! We've got: ints floats booleans strings and now… (drum roll) LISTS! sets of a thing (e.g., sets of ints)
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Python Basics.
INC 161 , CPE 100 Computer Programming
Other things: functions
ECS10 10/10
Formatted and Unformatted Input/Output Functions
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Building Java Programs
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Programming Training Main Points: - Problems with repetitions.
Conditional and iterative statements
CISC101 Reminders All assignments are now posted.
What is printed out? def f(x): print(x+3) return(x + 7) def g(k): return(f(k) + 2) print(g(1)) 4 10 def f2(x): return(x + 7) print(x+3) def g2(k): return(f2(k)
February , 2009 CSE 113 B.
More While Loops.
Strings: Strings? concatenate (join) + make multiple copies using *
Lecture 6 - Recursion.
Presentation transcript:

PPT3

Quick function:  Write a function that checks to see if a number is even or not.  What TYPE does this return?

Boolean Values  We now know functions can return:  Numbers (int, double)  Strings  True or False ?  AKA Boolean Values  Yes, No  1, 0  We can use True and False as if they are a type)  E.g., return(True)

def ismultof3(x): if ((x%3) == 0): return(True) else: return(False) When python executes the following statement, what is the result? (x%3)==0 def ismultof3(x): return((x%3) == 0) def func2(x): if (ismultof3(x)): # Can we see why specifying what type # is returned from a function is critical?!? return(str(x) + " is a multiple of 3") else: return(str(x) + " is not a multiple of 3")

Returning to Boolean Values:  Quadratic Equation:  x 2 - 3x – 4 = 0  Is this true for 1? 2? 3? 4?  Can you write a function that returns the answer to this question?  Hint: the function needs to return a boolean value.  What is the input?  How do you check for the output?

Function to represent this: #Name: eqcheck #Calculation: Determines if input value (x) will solve #the problem: # x 2 - 3x – 4 = 0 #Input: x: a number #Output: a boolean value def eqcheck(x): return (x**2 – 3*x – 4) == 0 What is returned? print(eqcheck(3)) What is returned? print(eqcheck(4))

Remember? def Squr(par1): return(par1 ** 2) def dbl(par2): return(par2 + par2) def Func4(p1,p2): return(dbl(Squr(p2)+ Squr(p2)+3)) print(Func4(2,4)) def Func5(p1): return(dbl(dbl(dbl(p1)))) print(Func5(4))

What gets printed out? def f(n): if (n == 0): return (" ") else: print(“blug ") return f(n-1) f(3)

What about? def f(x): if (x == 0): return x else: return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): return (str(x)) else: return(str(x) + f2(x-1)) print(f2(4))

Recursion (one of 3 types of loops)  Recursion is when a function is defined in terms of itself (it calls itself).  Def: A recursive definition is one that defines something in terms of itself (that is, recursively)  Recursion is, in essence, making a function happen again and again without our having to call it (convenient, huh?)  It is one of 3 types of loops we will learn  all do the same thing, just different syntax) #This is recursion def recurse(): return(recurse()) #This isn’t def nonrecurse(): return(“nope”)

Try: def f(x): return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): return x else: return(x + f2(x+1)) print(f2(4)) def f3(x): if (x == 1): return x else: return(x + f3(x-2)) print(f3(4))

How about: def f(x): if x == 100: return(“none") else: if (x**2 - 3 *x - 4) == 0: print(str(x) + " solves the equation ") return(f(x+1)) print(f(-100))

Loop Essentials  We now have the basics: 1. Must formulate a problem in terms of itself. (Recursion: the function must call itself) 2. Must include a condition for stopping the recursion (base case) 3. Must make sure that we will always hit that stopping condition.

Sum numbers (1-5) def summing(x): 1. If we start by calling the function with 1, when should we stop? if (x >= 5): # must return something that does not make the loop happen again!!!!! return(x) #why x?  Assume the smallest case possible: Summing one number.  No matter what the number is, if you are summing that number and that number only, you want to return that number.  Alt: if we start summing 1-5 by calling the function with 5, when should we stop? if (x <= 1): return(x) Note: Sometimes we can have MORE THAN ONE stopping condition (you only have to make one of them happen)

Sum numbers (1-5) def summing(x): 1. Stopping Condition? if (x >= 5): return(x) 2. How do we make sure that we get to the stopping condition?  Increase x every time we “loop”  E.g., summing(x+1)  Alternative: summing(x-1)  If we do these two things, we will likely avoid an infinite loop

Sum numbers 1-5 (cont.) def summing(x): 1. Stopping condition if (x >= 5): return (x) 2. Progressing towards stopping condition:  summing(x+1) 3. Finally, we need to write our function:  Pretend there are only 2 cases – the last case (step 1, above) and the case right before that. (e.g., summing 4-5)  We want to return(x + summing(x+1)), right?  From step 1 we know summing (x+1) returns 5  And we know x holds 4.  So summing(4) returns 9  Now what if we summed from 3-5? Can we use what we just did?

Sum Numbers 1-5 (cont.)  Put it all together: def summing(x): if (x >= 5): return(x) else: return(x + summing(x+1)) print(summing(1))

Let’s try : 1. Write a recursive function that creates a string of every other number starting at 1 and ending at Write a recursive function that sums every other number between two integers (you can assume the second integer is greater than the first integer) 3. Write a recursive function that counts the number of numbers that is evenly divisible by 3 between x and y

Problem 1:Write a recursive function that prints out every other number starting at 1 and ending at 10 def g(x): if x == 10: return(str(x)) elif x > 10: return() else: return(str(x) + g(x+2)) print(g(1))

Problem 2: Write a recursive function that sums every other number between two integers def g(x,y): if x == y: return(x) elif x > y: return() else: return(x + g(x+2)) print(g(3,12))

Problem 3: Write a recursive function that counts the number of numbers that is evenly divisible by 3 between x and y def h(x,y): if x >=y: return(0) elif x%3 == 0: return (1 + h(x + 1,y)) else: return(h(x+1,y)) print(h(3,28)) Same? def h(x,y,z): if x >=y: return(z) elif x%3 == 0: return (h(x + 1,y,z+1)) else: return(h(x+1,y,z)) print(h(3,28,0))

Let’s try : 1. Write a recursive function that calculates x to the yth power, assuming we’ve only got multiplication (i.e., you can’t use **) 2. Write a recursive function that determines whether a number is prime or not (and returns True if it is, and False if it isn’t)

Problem 3: Write a recursive function that finds x to the yth power, assuming we’ve only got multiplication (i.e., you can’t use **) def k(x,y): if y == 0: return(1) else: return(x * k(x,y-1)) print(k(3,4)) print(k(2,4)) Same? def k(x,y): if y == 0: return(x) else: return( k(x*x,y-1)) print(k(3,4)) print(k(2,4)) Now? def k(x,y,z): if y == 0: return(z) else: return( k(x,y-1,z*x)) print(k(3,4,___)) print(k(2,4,___)) What does z need to start at?

Write a recursive function that determines whether a number is prime or not (and returns True if it is, and False if it isn’t) def f(x,y): if (y>(x//2)): return(True) elif (x%y==0): print(y) return(False) else: return (f(x,y+1)) print(f(6,2)) print(f(137,2)) print(f(55,2)) print(f(29,2)) def f(x,y): if (y>(x//2)): return(True) else: return (x%y!=0 and f(x,y+1)) print(f(6,2)) print(f(137,2)) print(f(55,2)) print(f(29,2))

Lab cheat sheet  Random numbers: from random import * #imports the random library, including all the functions to generate random numbers  And then x=randrange(1,10) #x now holds a number between 1 and 9 (doesn’t include 10)  Example: from random import * import turtle def f(x): if (x == 5): return("Done") else: x = randrange(0,10) print("the random number is " + str(x)) return(f(x)) print(f(10))

Turtle colors cheat sheet:  Colors in turtle are represented with r g b values (red,green, and blue). Each value should be between 0 and 1.  So.9,.1,.1 will be pretty red, whereas .9,.1,.9 will be purple.  To use colors in turtle: from random import * import turtle def f(x,r,g,b): if (x == 0): return("Done") else: r = randrange(0,100)/100 g = randrange(0,100)/100 b = randrange(0,100)/100 turtle.color(r,g,b) turtle.circle(10) turtle.penup() turtle.goto(randrange(0,100),randrange(0,100)) turtle.pendown() return(f(x-1,r,g,b)) print(f(10,.5,.5,.5))