15-110: Principles of Computing

Slides:



Advertisements
Similar presentations
Control Statements. Define the way of flow in which the program statements should take place. Control Statements Implement decisions and repetitions.
Advertisements

CSC 110 Decision structures [Reading: chapter 7] CSC 110 H1.
1 Decision Structures Chapter 7 (Skip 7.1.3, 7.4) Adapted from the online slides provided by John Zelle (
Chapter 3 Computing with Numbers
Chapter 7 Decision Structures
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e1.
Exceptions COMPSCI 105 S Principles of Computer Science.
Vahé Karamian Python Programming CS-110 CHAPTER 3 Computing with Numbers.
The University of Texas – Pan American
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Conditional Control Flow Constructs. Sequential Control Flow Execution order follows the textual order straight line flow Many simple problems can not.
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.
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.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
1 Example: Solution of Quadratic Equations We want to solve for real values of x, for given values of a, b, and c. The value of x can be determined from.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 7 Conditionals and Loops 4/18/09 Python Mini-Course: Day 2 - Lesson 7.
Decision Making CMSC 201. Overview Today we will learn about: Boolean expressions Decision making.
Python Conditionals chapter 5
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.
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Decision Making CMSC 201 Chang (rev ).
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
11 Making Decisions in a Program Session 2.3. Session Overview  Introduce the idea of an algorithm  Show how a program can make logical decisions based.
Python Programming, 3/e1 Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures.
Python Boot Camp Booleans While loops If statements Else clauses
Control Flow (Python) Dr. José M. Reyes Álamo.
Control Structures I Chapter 3
Python Programming: An Introduction to Computer Science
Introduction to Computing Science and Programming I
CNG 140 C Programming (Lecture set 3)
Chapter 4: Making Decisions.
CMSC201 Computer Science I for Majors Lecture 06 – Decision Structures
Python: Control Structures
Python Programming: An Introduction to Computer Science
EGR 2261 Unit 4 Control Structures I: Selection
CS1371 Introduction to Computing for Engineers
Topic: Functions – Part 2
Programming 101 Programming for non-programmers.
Midterm Exam 答題分布 Python Programming, 2/e.
CMSC201 Computer Science I for Majors Lecture 04 – Decision Structures
Conditional Execution
Ruth Anderson UW CSE 160 Winter 2017
Selection CIS 40 – Introduction to Programming in Python
Python - Conditional Execution
Class 12.
Conditional Execution
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Ruth Anderson UW CSE 140 Winter 2014
Conditional Execution
Design and Implementation
Control flow : if statements
3. Decision Structures Rocky K. C. Chang 19 September 2018
Conditional and iterative statements
15-110: Principles of Computing
Class 13 function example unstring if if else if elif else
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Jurassic Park Python Programming, 2/e.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Decision Structures Zelle - Chapter 7
The IF Revisited A few more things Copyright © Curt Hill.
Presentation transcript:

15-110: Principles of Computing Decision Structures- Part II Lecture 6, September 18, 2018 Mohammad Hammoud Carnegie Mellon University in Qatar

Today… Last Session: Today’s Session: Announcement: Functions- Part II Decision Structures- Part II: Multi-way Decisions A Study on Design Announcement: HA2 will be out by tonight; it is due on September 27 by 10:00AM

Revisiting Our Quadratic Equation Solver #The following line will make the math library in Python available for us. import math def rootsQEq(): print("This program finds the real solutions to a quadratic.") print() a = eval(input("Enter the value of coefficient a: ")) b = eval(input("Enter the value of coefficient b: ")) c = eval(input("Enter the value of coefficient c: "))

Revisiting Our Quadratic Equation Solver #To call a function from the math library, we can use the #dot operator as follows: s_root_val = math.sqrt(b*b - 4 * a * c) root1 = (-b + s_root_val)/(2*a) root2 = (-b - s_root_val)/(2*a) print() print("The solutions are: ", root1, root2) #Call the function rootsQEq() rootsQEq()

Revisiting Our Quadratic Equation Solver A sample run: This program finds the real solutions to a quadratic. Enter the value of coefficient a: 1 Enter the value of coefficient b: 2 Enter the value of coefficient c: 3 Traceback (most recent call last): File "/Users/mhhammou/Desktop/CMU-Q/Courses/15-110/Programs/Lecture4/RootsQE.py", line 22, in <module> rootsQEq() File "/Users/mhhammou/Desktop/CMU-Q/Courses/15-110/Programs/Lecture4/RootsQE.py", line 14, in rootsQEq s_root_val = math.sqrt(b*b - 4 * a * c) ValueError: math domain error What is the problem?

Revisiting Our Quadratic Equation Solver The problem is that the discriminant 𝑏 2 −4𝑎𝑐 <0 The sqrt function is unable to compute the square root of a negative number How can we avoid this problem? We can first compute the discriminant 𝑏 2 −4𝑎𝑐 <0 Then, we can check if it is negative (via using the if statement) If it is negative, we can print out that the equation has no real roots Otherwise (via using the else clause), we can compute the solutions and print them out

A Refined Quadratic Equation Solver import math def rootsQEq(): print("This program finds the real solutions to a quadratic.") print() a = eval(input("Enter the value of coefficient a: ")) b = eval(input("Enter the value of coefficient b: ")) c = eval(input("Enter the value of coefficient c: ")) discriminant = b * b – 4 * a * c

A Refined Quadratic Equation Solver if discriminant < 0: print(“The equation has no real roots!”) else: s_root_val = math.sqrt(discriminant) root1 = (-b + s_root_val)/(2*a) root2 = (-b - s_root_val)/(2*a) print(“\nThe solutions are: ", root1, root2) rootsQEq()

Revisiting Our Quadratic Equation Solver A sample run: This program finds the real solutions to a quadratic. Enter the value of coefficient a: 1 Enter the value of coefficient b: 2 Enter the value of coefficient c: 3 The equation has no real roots!

Good, But… This new version of the quadratic solver is certainly a big improvement, but it still has some quirks! Let us illustrate that through examples: This program finds the real solutions to a quadratic. Enter the value of coefficient a: 1 Enter the value of coefficient b: 2 Enter the value of coefficient c: 1 The solutions are: -1.0 -1.0 A double root at -1.0; printed twice, thus might seem confusing to some people (a styling issue)!

Good, But… Another sample run: This program finds the real solutions to a quadratic. Enter the value of coefficient a: 0 Enter the value of coefficient b: 2 Enter the value of coefficient c: 1 Traceback (most recent call last): File "/Users/mhhammou/Desktop/CMU-Q/Courses/15-110/Programs/Lecture4/RootsQE.py", line 27, in <module> rootsQEq() File "/Users/mhhammou/Desktop/CMU-Q/Courses/15-110/Programs/Lecture4/RootsQE.py", line 22, in rootsQEq root1 = (-b + s_root_val)/(2*a) ZeroDivisionError: float division by zero Coefficient a CANNOT be zero since we cannot divide by zero (a serious issue)!

The Need for a Three-Way Decision Let us start with the double-root situation, which occurs when the discriminant is exactly 0 If we want to catch this special case, our quadratic equation solver needs a three-way decision Here is a quick sketch of what we need: … Check the value of the discriminant when < 0: handle the case of no roots when = 0: handle the case of a double root when > 0: handle the case of two distinct roots

A Three-Way Decision Via Two if-else Statements One way to code this algorithm is to use two if-else statements … if discriminant < 0: print(“Equation has no real roots”) else: if discriminant == 0: root = -b / (2 * a) print(“There is a double root at”, root) #Do stuff for two roots…

Digging Deeper… If we trace this code carefully, we will observe that there are exactly three possible paths Yes Discriminant < 0 ? No Print “no roots” Yes Discriminant == 0 ? No Do Double Roots Do Unique Roots

Multi-Way Decisions We managed to finesse a 3-way decision by using 2 2-way decisions What happens if we needed to make a 5-way decision using this technique? The if-else structures would nest four levels deep, and the Python code would march off the right-hand edge of the page Is there any other way in Python to write multi-way decisions? Yes, by using if-elif-else statements

Multi-Way Decisions Here is how the if-elif-else form looks like: if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> … else: <default statements> The else clause is optional; if omitted, it is possible that no indented statement block will be executed!

Revisiting Our Quadratic Equation Solver import math def rootsQEq(): print("This program finds the real solutions to a quadratic.") print() a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discriminant = b * b – 4 * a * c

Revisiting Our Quadratic Equation Solver if discriminant < 0: print("The equation has no real roots!") elif discriminant == 0: root = -b/(2*a) print("\nThere is a double root at", root) else: s_root_val = math.sqrt(discriminant) root1 = (-b + s_root_val)/(2*a) root2 = (-b - s_root_val)/(2*a) print("\nThe solutions are: ", root1, root2) rootsQEq()

Three Sample Runs When discriminant < 0 When discriminant == 0 This program finds the real solutions to a quadratic. Please enter the coefficients (a, b, c): 1, 2, 3 The equation has no real roots! When discriminant < 0 This program finds the real solutions to a quadratic. Please enter the coefficients (a, b, c): 1, 2, 1 There is a double root at -1.0 When discriminant == 0 This program finds the real solutions to a quadratic. Please enter the coefficients (a, b, c): 3, 4, -2 The solutions are: 0.38742588672279316 -1.7207592200561266 When discriminant < 0

Avoid Dividing By Zero Let us now handle the case of avoiding a division by zero import math def rootsQEq(): print("This program finds the real solutions to a quadratic.") print() a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discriminant = b * b – 4 * a * c if a == 0: print("Cannot divide by zero")

Avoid Dividing By Zero Let us now handle the case of avoiding a division by zero elif discriminant < 0: print("The equation has no real roots!") elif discriminant == 0: root = -b/(2*a) print("\nThere is a double root at", root) else: s_root_val = math.sqrt(discriminant) root1 = (-b + s_root_val)/(2*a) root2 = (-b - s_root_val)/(2*a) print("\nThe solutions are: ", root1, root2) rootsQEq()

Avoid Dividing By Zero Let us try to divide by zero: This program finds the real solutions to a quadratic. Please enter the coefficients (a, b, c): 0, 1, 2 Cannot divide by zero

Study in Design: Max of Three Numbers (v1) def main(): x1, x2, x3 = eval(input("Please enter three values: ")) if x1 >= x2 and x1 >= x3: max = x1 elif x2 > x1 and x2 > x3: max = x2 else: max = x3 print("The largest value is", max) main() Difficult to scale the program to more numbers (say, 10, 100, or even more)– i.e., following this strategy will make the code very long, complex, and prone to errors! This program uses a strategy that can be referred to as “compare each to all”

Study in Design: Max of Three Numbers (v2) def main(): x1, x2, x3 = eval(input("Please enter three values: ")) if x1 >= x2: if x1 >= x3: max = x1 else: max = x3 if x2 >= x3: max = x2 print("The largest value is", max) main() This program uses a strategy that can be referred to as “decision tree”

Study in Design: Max of Three Numbers (v2) Yes x1 >= x2 No Yes X1 >= x3 No Yes X2 >= x3 No max = x1 max = x3 max = x2 max = x3 Still, this strategy (i.e., decision tree) makes it very difficult to scale the program to more numbers (say, 10, 100, or even more)!

Study in Design: Max of Three Numbers (v3) def main(): x1, x2, x3 = eval(input("Please enter three values: ")) max = x1 if x2 > max: max = x2 if x3 > max: max = x3 print("The largest value is", max) main() This program uses a strategy that can be referred to as “sequential processing”

Study in Design: Max of Three Numbers (v3) Interestingly, this version (i.e., v3) of the program allows us to scale to larger problems In particular, we can easily write a program that computes the largest of n numbers by folding our algorithm into a loop A loop is a device that tells a program to do the same thing over and over again! (more on this next lecture) for i in range(10): print(“Hello”) This will print Hello ten times!

Study in Design: Max of Three Numbers (v3) def main(): n = eval(input("How many numbers are there? ")) #set max to be the first value; we can involve conditions here to #ensure that n is greater than or equal to 1 max = eval(input("Enter a number >> ")) #Now compare the n-1 successive values for i in range(n-1): x = eval(input("Enter a number >> ")) if x > max: max = x print("The largest value is", max) main() This is a more general solution!

Study in Design: Max of Three Numbers (v4) We can even go green! def main(): x1, x2, x3 = eval(input("Please enter three values: ")) print("The largest value is", max(x1, x2, x3)) main() This program uses a strategy that can be referred to as “use Python”!

Study in Design: Lessons Learned There is typically more than 1 way to solve a problem! Do not rush to code up the first idea that pops into your head; rather, think about your design and ask yourself if there is a better way to solve the problem Generality is good – we arrived at the best solution to the max of three problem by considering the more general max of n numbers problem Do not reinvent the wheel– you can use Python’s existing libraries!

Summary Decision structures are control structures that allow a program to execute different sequences of instructions for different cases Decisions are implemented in Python as follows: A simple decision with 1 condition (i.e., one-way decision) can be implemented with 1 if clause A decision with 2 conditions (i.e., two-way decision) can be implemented with 1 if and 1 else (i.e., if-else) clauses A decision with 3 or more conditions (i.e., multi-way decision) can be implemented with 3 or more if-elif-else clauses E.g., for 3-way, you can use 1 if, 1 elif, and 1 else E.g., for 4-way, you can use 1 if, 2 elifs, and 1 else E.g., for n-way, you can use 1 if, n elifs, and 1 else

Summary Decisions are based on the evaluations of conditions, which are simple Boolean expressions that can be constructed using different kinds of operators (e.g., relational, logical, membership, and identity operators) A Boolean expression is either True or False Algorithms that incorporate decisions can become quite complicated as decision structures are nested Usually a number of solutions are possible, and careful thought should be given to produce correct, efficient, and understandable programs

Next Lecture… Loop Structures- Part I