The CS 5 Black Post Penguins Invade Dormitory

Slides:



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

Python Magic Select a Lesson: Why Learn to Code? Basic Python Syntax
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
An Introduction to Textual Programming
CATHERINE AND ANNIE Python: Part 4. Strings  Strings are interesting creatures. Although words are strings, anything contained within a set of quotes.
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Functions Chapter 4 Python for Informatics: Exploring Information
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
EECS 110: Lec 4: Functions and Recursion Aleksandar Kuzmanovic Northwestern University
ICAPRG301A Week 2 Strings and things Charles Babbage Developed the design for the first computer which he called a difference engine, though.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Python Conditionals chapter 5
Decision Structures and Boolean Variables. Sequence Structures Thus far, we’ve been programming “sequence structures” Thus far, we’ve been programming.
Python Let’s get started!.
Variables, Types, Expressions Intro2CS – week 1b 1.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
The last CS 5 lecture you’ll ever need! Inducing labor for the machine! == Reducing labor for humans! On Warner Brothers' insistence, we affirm that this.
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
Input, Output and Variables GCSE Computer Science – Python.
CSC 108H: Introduction to Computer Programming Summer 2012 Marek Janicki.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
ENGINEERING 1D04 Tutorial 1. WELCOME! What we’re doing today Who am I How to do well What are computer programs Software Development Cycle Pseudo Code.
Python Basics.
Catapult Python Programming Wednesday Morning session
Algorithmic complexity: Speed of algorithms
Python Let’s get started!.
Introduction to Python
Introduction to Python
Containers and Lists CIS 40 – Introduction to Programming in Python
Catapult Python Programming Thursday Session
Python: Control Structures
CS 326 Programming Languages, Concepts and Implementation
Functions CIS 40 – Introduction to Programming in Python
EECS 110: Lec 4: Functions and Recursion
The CS 5 Black Times Penguin Leads Surfing Trip
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Logical Operators and While Loops
CS2102: Lecture on Abstract Classes and Inheritance
Conditionals (if-then-else)
Lesson 2: Building Blocks of Programming
CSE 341: Programming Langs
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Welcome Back to CS 5 Black!
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
CISC101 Reminders Slides have changed from those posted last night…
The CS 5 Times CS 5 Penguin Knocked Into Icy Waters
Data types Numeric types Sequence types float int bool list str
Teaching London Computing
Types, Truth, and Expressions (Part 2)
Control flow : if statements
EECS 110: Lec 4: Functions and Recursion
Algorithmic complexity: Speed of algorithms
A look at Python Programming Language 2018.
15-110: Principles of Computing
Python Programming Language
CISC101 Reminders All assignments are now posted.
Algorithmic complexity: Speed of algorithms
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
“Everything Else”.
Types, Truth, and Expressions
More Basics of Python Common types of data we will work with
Types, Truth, and Expressions (Part 2)
Lecture 6 - Recursion.
Presentation transcript:

The CS 5 Black Post Penguins Invade Dormitory Claremont (AP)—A wild group of unicycling, pogo-sticking, freelining penguins raced through HMC’s South Dorm yesterday, upsetting students who were diligently attempting to complete their CS 5 homework. “I had just gotten my program to work,” sobbed one student, “when the pogo stick landed directly on my ‘delete’ key and wiped it all out! Now I have to start all over. It took my hours to get my program to say ‘Hello, world’ and now I’ll never have time to finish it.

return vs print... def dbl(x): def trbl(x): return 2 * x print 2 * x def happy(input): y = dbl(input) return y + 42 def sad(input): y = trbl(input) return y + 42 def friendly(input): y = dbl(input) print(y, "is very nice!”) return y + 42 Strings are in single or double quotes

Booleans >>> 3 == 1+2 True >>> 42 == "ham" False >>> "spam" > "ham" >>> 42 > "spam" Barf! Strings! George Boole 1815-1864

The “Truth” about Python’s Booleans >>> True + 41 42 >>> 2 ** False == True True Demonstrating the True “power” of Falsity!

Lists! L doesn’t change! Lists are “polymorphic” [1, 42, 3, 4] >>> L + 10 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: can only concatenate list (not "int") to list >>> L + [50] [1, 42, 3, 4, 50] >>> L*2 [1, 42, 3, 4, 1, 42, 3, 4] >>> M = [42, "hello", 3+2j, 3.141, [1, 2, 3, 4, 5, 6]] L doesn’t change! Many animations on this slide. Things that we show: 1. Lists aren’t regular objects 2. You can append to a list if you get the syntax right. 3. Appending creates a new list; the original is unchanged. (Later, we’ll learn how to change lists.) 4. Multiplication duplicates things; this is especially useful for creating a long list with all the same value. 5. Lists are polymorphic, including being able to have other lists as members. 6. Python supports complex numbers (but “i” is “j” because Guido has an engineering background.) Lists are “polymorphic”

List Indexing and Slicing! Python slices just like slapchop! 1 2 3 >>> M = [42, 3, 98, 37] >>> M[0] >>> M[2] >>> M[0:2] >>> M[0:3:2] >>> M[1:] >>> M[:-1] >>> M[1:-2] >>> If you have time, let the class figure these out. If you have less time, demo them or just give answers. “What kind of thing does this return? Try to reverse the list!

Strings Revisited >>> S = "I love Spam!" >>> S[0] 1 2 3 4 5 6 7 8 9 10 11 >>> S = "I love Spam!" >>> S[0] >>> S[11] >>> S[2:6] >>> S[11:6:-1] >>> S*2 If you have time, let the class figure these out. If you have less time, demo them or just give answers. Hey penguins, get off my slides!

if, elif, else… Alternatively?? def special(x): """This function demonstrates the use of if and else""" if x == 42: return "Very special number!" else: return "Stupid, boring number." def special(x): if x == 42: return "Very special number!" return "Stupid, boring number." Alternatively?? Notice how lines with the same level of indentation are in the same code block!

if, elif, else… def superSpecial(x): """This function demonstrates the use of if, elif, and else""" if x < 41: return "Small number" elif x == 42 or x % 42 == 0: return "Nice!" elif 41 <= x <= 43: return "So close!" else: # We might do more stuff here... return “"Yuck!" Would swapping the order of these elif’s give the same behavior? Emphasize that whenever you have mutually exclusive conditions, you should take advantage of elif. Don’t try to write the mutual exclusion yourself; you’ll screw it up! Notice how lines with the same level of indentation are in the same code block!

Avoiding elif def unwise(x): """This function avoids using elif""" if x == 42 or x % 42 == 0: return "Nice!" if 41 <= x <= 43 or x != 42: return "So close!" if x != 42 or x % 42 != 0: return “"Yuck!" I’m getting quite confused here… Emphasize that whenever you have mutually exclusive conditions, you should take advantage of elif. Don’t try to write the mutual exclusion yourself; you’ll screw it up!

You’ll find out where their wallet is! The Alien's Life Advice Give people hugs You’ll find out where their wallet is!

What Happens Inside a Function? 8 h(3): def f(x): x = x-1 return g(x)+1 def g(x): return x*2 def h(x): if x%2 == 1: # x odd return f(x) + x else: # x even return f(f(x)) return f(3) + 3 5 f(3): return g(2) + 1 4 g(2): return 4 5 clicks of animation on this slide Two key points… Functions return to where they were called from Each function keeps its own values of its variables

Recursion… n! = n(n-1)(n-2)…1 n! = n[(n-1)!] “inductive definition” 0! = 1 “base case” Why is 0! = 1?

Math Induction = CS Recursion inductive definition Python (Functional) recursive function 0! = 1 n! = n[(n-1)!] # recursive factorial def factorial(n): Students do factorial in notes. Then, click to show solution. If you have time, write factorial in python and run it.

Math Induction = CS Recursion inductive definition Python (Functional) recursive function 0! = 1 n! = n[(n-1)!] # recursive factorial def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) Students do factorial in notes. Then, click to show solution. If you have time, write factorial in python and run it.

Is Recursion Magic? “To understand recursion, you must first understand recursion”—anonymous Mudd alum factorial(3): 6 return 3 * factorial(2) 2 return 2 * factorial(1) 1 return 1 * factorial(0) 5 clicks of animation on this slide. # recursive factorial def factorial(n): '''This computes n!''' if n == 0: return 1 else: return n*factorial(n-1)

Is Recursion Magic? “To understand recursion, you must first understand recursion”—anonymous Mudd alum factorial(3): 6 return 3 * factorial(2) 2 return 2 * factorial(1) 1 return 1 * factorial(0) 5 clicks of animation on this slide.

A Tower of Fun! 2 2 Math Python (Functional) 2 2 tower(3) = 2 recursive function 2 2 2 tower(3) = 2 2 # recursive tower def tower(n): 2 tower(4) = 2 tower(5) = 2 clicks of animation on this slide. The tower function is taking recursion to new heights!

A Tower of Fun! 2 2 2 Math Python (Functional) recursive function 2 2 2 tower(3) = 2 2 # recursive tower def tower(n): 2 2 tower(4) = 2 2 2 2 tower(5) = 2 Ask them to develop the math definition of tower. Remind them to remember the base case. Next slide has the solution. Try this on your worksheet! (Recall that xy is computed using x**y) inductive definition:

A Tower of Fun! 2 2 2 Math Python (Functional) 2 2 tower(3) = 2 recursive function 2 2 2 tower(3) = 2 2 # recursive tower def tower(n): 2 2 tower(4) = 2 2 2 2 tower(5) = 2 Now let them develop tower(n) from the inductive definition. Solution is on the next slide. inductive definition: inductive case: tower(n) = 2tower(n-1) base case: tower(0) = ?

A Tower of Fun! 2 2 2 Math Python (Functional) 2 2 tower(3) = 2 recursive function 2 2 2 tower(3) = 2 2 # recursive tower def tower(n): '''Tower of n''' if n == 0: return 1 else: return 2**tower(n-1) 2 2 tower(4) = 2 2 2 2 tower(5) = 2 First animation is the base case; click to show full solution. If you have time, demo tower(1)-tower(5). Tower(4) is just 65536, but tower(5) has 19,729 digits! (Yet Python calculates it quickly. The same isn’t true for tower(6)…) inductive definition: inductive case: tower(n) = 2tower(n-1) base case: tower(0) = 1 demo!

Computing the Length of a List >>> len([1, 42, “spam”]) 3 >>> len([1, [2, [3, 4]]]) def len(List): ‘’’returns the length of List’’’ Python has this built in! Have them figure out the length of the second list. Then have them write len together with you, starting with the base case.

Reversing a List >>> reverse([1, 2, 3, 4]) [4, 3, 2, 1] def reverse(L): ‘’’returns a new list that is the reverse of the input list’’’ If you have time, make it a worksheet problem; otherwise develop it together.

Reversing a List >>> reverse([1, [2, [4, 5], 6], 7]) What’s the reverse of this list? With simple reverse, it’s [7, [2, [4, 5], 6], 1].

Deep Reversing a List >>> reverse([1, [2, [4, 5], 6], 7]) [7, [2, [4, 5], 6], 1] >>> deepReverse([1, [2, [4, 5], 6], 7]) [7, [6, [5, 4], 2], 1]) This definitely requires recursion! Fun problem on this week’s HW! One click needed to show the deep reversal.

Recursion = :^) Recursion, conditional statements, and lists suffice to give us a Turing-complete programming language! Variables, assignment (=), if, while, etc. are all unnecessary!