CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

Similar documents
CONTROL AND ENVIRONMENTS 1

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

C ONTROL AND H IGHER O RDER F UNCTIONS

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

CONTROL AND HIGHER ORDER FUNCTIONS 1

HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS 2

CONTROL AND HIGHER ORDER FUNCTIONS 1

CONTROL AND HIGHER ORDER FUNCTIONS 2

HIGHER-ORDER FUNCTIONS 2

ENVIRONMENT DIAGRAMS AND RECURSION 2

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, Higher Order Functions. HOFs in Environment Diagrams

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, 2018 Solutions. 1 Higher Order Functions. HOFs in Environment Diagrams

61A Lecture 3. Friday, September 5

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Flow Control. So Far: Writing simple statements that get executed one after another.

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

HIGHER ORDER FUNCTIONS 2

61A Lecture 2. Wednesday, September 4, 2013

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Structure and Interpretation of Computer Programs Summer 2015 Midterm 1

Structure and Interpretation of Computer Programs

Test #2 October 8, 2015

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Structure and Interpretation of Computer Programs

Statements 2. a operator= b a = a operator b

Structure and Interpretation of Computer Programs

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Structure and Interpretation of Computer Programs

Making Decisions In Python

Intro. Scheme Basics. scm> 5 5. scm>

Problem Solving for Intro to Computer Science

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Data 8 Final Review #1

Structure and Interpretation of Computer Programs

61A Lecture 2. Friday, August 28, 2015

Structure and Interpretation of Computer Programs

CSC Software I: Utilities and Internals. Programming in Python

The SPL Programming Language Reference Manual

Structure and Interpretation of Computer Programs

CS61A Notes Week 13: Interpreters

Quiz Determine the output of the following program:

CS1 Lecture 3 Jan. 18, 2019

Control Structures 1 / 17

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs

How Do Robots Find Their Way?

Structure and Interpretation of Computer Programs

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

CS1 Lecture 3 Jan. 22, 2018

Structure and Interpretation of Computer Programs

Conditionals and Recursion. Python Part 4

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

CS 1301 CS1 with Robots Summer 2007 Exam 1

Python 1: Intro! Max Dougherty Andrew Schmitt

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

FRAC: Language Reference Manual

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

CS1 Lecture 5 Jan. 26, 2018

Structure and Interpretation of Computer Programs

Scheme Quick Reference

Short Answer Questions (40 points)

Measuring Efficiency

CSc 110, Autumn Lecture 13: Cumulative Sum and Boolean Logic. Adapted from slides by Marty Stepp and Stuart Reges

61A Lecture 4. Monday, September 9

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Structure and Interpretation of Computer Programs

Organization of Programming Languages CS3200/5200N. Lecture 11

Control Structures in Java if-else and switch

Python Activity 5: Boolean Expressions and Selection Statements

RECURSION: n. SEE RECURSION 3

Lecture #10: Sequences. Last modified: Mon Feb 22 16:33: CS61A: Lecture #10 1

ASSIGNMENT 4 SOLUTIONS

Structure and Interpretation of Computer Programs

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

Control Flow: Loop Statements

Functionally Modular. Self-Review Questions

The PCAT Programming Language Reference Manual

Scheme Quick Reference

Score score < score < score < 65 Score < 50

Functional Programming. Pure Functional Programming

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Control Flow: Branching booleans and selection statements CS GMU

Introduction to Python (All the Basic Stuff)

PREPARING FOR PRELIM 1

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

CS 1110: Introduction to Computing Using Python Loop Invariants

Transcription:

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, 2018 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program to skip sections of code, while iteration (while), allows a program to repeat a section. If statements Conditional statements let programs execute different lines of code depending on certain conditions. Let s review the if- elif-else syntax. Recall the following points: The else and elif clauses are optional, and you can have any number of elif clauses. if <conditional expression>: <suite of statements> elif <conditional expression>: <suite of statements> else: <suite of statements> A conditional expression is a expression that evaluates to either a true value (True, a non-zero integer, etc.) or a false value (False, 0, None, "", [], etc.). Only the suite that is indented under the first if/elif with a conditional expression evaluating to a true value will be executed. If none of the conditional expressions evaluate to a true value, then the else suite is executed. There can only be one else clause in a conditional statement! Boolean Operators Python also includes the boolean operators and, or, and not. These operators are used to combine and manipulate boolean values. not returns the opposite truth value of the following expression. and stops evaluating any more expressions (short-circuits) once it reaches the first false value and returns it. If all values evaluate to a true value, the last value is returned. or short-circuits at the first true value and returns it. If all values evaluate to a false value, the last value is returned. >>> not None True >>> not True False >>> -1 and 0 and 1 0 >>> False or 9999 or 1/0 9999

2 Control and Environments 1.1 Alfonso will only wear a jacket outside if it is below 60 degrees or it is raining. Write a function that takes in the current temperature and a Boolean value telling if it is raining and returns True if Alfonso will wear a jacket and False otherwise. This should only take one line of code! def wears_jacket(temp, raining): >>> wears_jacket(90, False) False >>> wears_jacket(40, False) True >>> wears_jacket(100, True) True 1.2 To handle discussion section overflow, TAs may direct students to a more empty section that is happening at the same time. Write a function that takes in the number of students in two sections and prints out what to do if either section exceeds 30 students. def handle_overflow(s1, s2): >>> handle_overflow(27, 15) No overflow >>> handle_overflow(35, 29) Move to Section 2: 1 >>> handle_overflow(20, 32) Move to Section 1: 10 >>> handle_overflow(35, 30) No space left in either section

Control and Environments 3 While loops Iteration lets a program repeat statements multiple times. block of code is the while loop. A common iterative while <conditional clause>: <body of statements> As long as <conditional clause> evaluates to a true value, <body of statements> will continue to be executed. The conditional clause gets evaluated each time the body finishes executing. 1.3 What is the result of evaluating the following code? def square(x): return x * x def so_slow(num): x = num while x > 0: x = x + 1 return x / 0 square(so_slow(5)) 1.4 Write a function that returns True if n is a prime number and False otherwise. After you have a working solution, think about potential ways to make your solution more efficient. Hint: use the % operator: x % y returns the remainder of x when divided by y. def is_prime(n): >>> is_prime(10) False >>> is_prime(7) True

4 Control and Environments 2 Higher Order Functions A higher order function (HOF) is a function that manipulates other functions by taking in functions as arguments, returning a function, or both. Functions as Arguments One way a higher order function can manipulate other functions is by taking functions as input (an argument). Consider this higher order function called negate. def negate(f, x): return -f(x) negate takes in a function f and a number x. It doesn t care what exactly f does, as long as f is a function, takes in a number and returns a number. Its job is simple: call f on x and return the negation of that value. 2.1 Write a function that takes in a function cond and a number n and prints numbers from 1 to n where calling cond on that number returns True. def keep_ints(cond, n): Print out all integers 1..i..n where cond(i) is true >>> def is_even(x):... # Even numbers have remainder 0 when divided by 2.... return x % 2 == 0 >>> keep_ints(is_even, 5) 2 4

Control and Environments 5 Functions as Return Values Often, we will need to write a function that returns another function. One way to do this is to define a function inside of a function: The return value of outer is the function inner. This is a case of a function returning a function. In this example, inner is defined inside of outer. Although this is a common pattern, we can also define inner outside of outer and still use the same return statement. However, note that in this second example (unlike the first example), inner doesn t have access to variables defined within the outer function, like x. def outer(x): def inner(y):... return inner def inner(y):... def outer(x): return inner 2.2 Use this definition of outer to fill in what Python would display when the following lines are evaluated. >>> def outer(n):... def inner(m):... return n - m... return inner >>> outer(61) >>> f = outer(10) >>> f(4) >>> outer(5)(4)

6 Control and Environments 2.3 Write a function similar to keep_ints like before, but now it takes in a number n and returns a function that has one parameter cond. The returned function prints out numbers from 1 to n where calling cond on that number returns True. def keep_ints(n): Returns a function which takes one parameter cond and prints out all integers 1..i..n where calling cond(i) returns True. >>> def is_even(x):... # Even numbers have remainder 0 when divided by 2.... return x % 2 == 0 >>> keep_ints(5)(is_even) 2 4

Control and Environments 7 3 Environment Diagrams An environment diagram keeps track of all the variables that have been defined and the values they are bound to. x = 3 def square(x): return x ** 2 square(2) When you execute assignment statements in an environment diagram (like x = 3), you need to record the variable name and the value: 1. Evaluate the expression on the right side of the = sign 2. Write the variable name and the expression s value in the current frame. When you execute def statements, you need to record the function name and bind the function object to the name. 1. Write the function name (e.g., square) in the frame and point it to a function object (e.g., func square(x) [parent=global]). The [parent=global] denotes the frame in which the function was defined. When you execute a call expression (like square(2)), you need to create a new frame to keep track of local variables. 1. Draw a new frame. a Label it with a unique index (f1, f2, f3 and so on) the intrinsic name of the function (square), which is the name of the function object itself. For example, if the function object is func square(x) [parent=global], the intrinsic name is square. the parent frame ([parent=global]) 2. Bind the formal parameters to the arguments passed in (e.g. bind x to 3). 3. Evaluate the body of the function. If a function does not have a return value, it implicitly returns None. Thus, the Return value box should contain None. a Since we do not know how built-in functions like add(...) or min(...) are implemented, we do not draw a new frame when we call built-in functions.

8 Control and Environments 3.1 Draw the environment diagram that results from executing the code below. a = 1 def b(b): return a + b a = b(a) a = b(a) 3.2 Draw the environment diagram that results from executing the code below. What will be the output (note this separately from the diagram)? from operator import add def sub(a, b): sub = add return a - b add = sub sub = min print(add(2, sub(2, 3)))