20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff

Size: px
Start display at page:

Download "20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff"

Transcription

1 4/9/26 2. More Complicated Classes Class For Manipulating Fractions Topics: Example: The class Fraction Operator Overloading Class Invariants Example: The class SimpleDate Class Variables deepcopy You in Grade School: Python in College: 2/3 + 3/6 = (2*6+3*3)/(3*6) = 5/8 = 7/6 >>> x = Fraction(2,3) >>> y = Fraction(3,6) >>> z = x+y >>> print z 7/6 You in Grade School: Class For Manipulating Fractions 2/3 * 3/4 = (2*3)/(3*4) = 6/2 = /2 Let s Define a Class to Do This Stuff class Fraction(object): num: the numerator [int] den: the denominator [int] Python in College: >>> x = Fraction(2,3) >>> y = Fraction(3,4) >>> z = x+y >>> print z /2 Not good enough. Do not want zero denominators! Let s Define a Class to Do This Stuff class Fraction(object): num: the numerator [int] den: the denominator [nonzero int] Note bout Greatest Common Divisors p q gcd(p,q) p/q / / /5 Still not good enough. Fractions should be reduced to lowest terms, e.g., -3/2 not -24/6 Reducing a fraction to lowest terms involves finding the gcd of the numerator and denominator and dividing.

2 4/9/26 Computing the Greatest Common Divisor def gcd(a,b): a = abs(a) b = abs(b) r = a%b while r>: a = b b = r r = a%b return b Euclid s lgorithm 3BC We will assume this is given and won t worry why it works Back to the Class Definition class Fraction(object): num: the numerator [int] den: the denominator [nonzero int] num/den is reduced to lowest terms These rules define a class invariant. Properties that all Fraction objects obey. The Constructor def init (self,p,q=): d = gcd(p,q) self.num = p/d self.den = q/d >>> x = Fraction(,4) >>> print x 5/2 >>> x = Fraction() >>> print x / Whole numbers are fractions too. Handy to use the optional argument feature. Let s Look at the Methods Defined in the Class Fraction Informal synopsis: in out negate 2/3-2/3 Invert 2/3 3/2 add 2/3 + /6 5/6 mul 2/3 * /6 /9 The double underscore methods make a nice notation possible. Instead of f.add(f2) we can just write f+f2. The negate Method def negate(self): Returns the negative of self F = Fraction(-self.num,self.den) return P >>> x = Fraction(6,-5) >>> print x -6/5 >>> y = x.negate() >>> print y 6/5 The invert Method def invert(self): Returns the reciprocal of self PreC: self is not zero F = Fraction(self.den,self.num) return F >>> x = Fraction(,95) >>> print x 2/9 >>> y = x.invert() >>> print y 9/2 2

3 4/9/26 Consider ddition Let s Define + For Fractions s = dogs + and + cats x = def add (self,f): N = self.num*f.den + self.den*f.num y = What + signals depends on the operands. Python figures it out. We say that the + operation is overloaded. >>> = Fraction(2,3) >>> B = Fraction(,4) >>> C = + B >>> print C /2 By defining add this way we can say +B instead of. add (B) Underlying math: a/b + c/d = (ad+bc)/bd Likewise for Multiplication Would Like Some Flexibility def mul (self,f): N = self.num*f.num Sometimes we would like to add an integer to a fraction: 2/3 + 5 = 7/3 >>> = Fraction(2,3) >>> B = Fraction(,4) >>> C = *B >>> print C /6 By defining mul this way we can say *B instead of. mul (B) To make this happen Python needs to know the type of the operands, i.e., who is to the right of the + and who is to the left of the +? Using the Built-In Boolean- Valued Function isinstance >>> x = 3/2 >>> isinstance(x,fraction) False >>> y = Fraction(3,2) >>> isinstance(y,fraction) True Feed isinstance it the mystery object and a class and it will tell you if the object is an instance of the class. More Flexible add def add (self,f): if isinstance(f,fraction): N = self.num*f.den + self.den*f.num else: N = self.num + self.den*f D = self.den If f is a Fraction, use (a/b + c/d) = (ad+bc)/(bd) 3

4 4/9/26 More Flexible add More Flexible mul def add (self,f): if isinstance(f,fraction): N = self.num*f.den + self.den*f.num else: N = self.num + self.den*f D = self.den def mul (self,f): if isinstance(f,fraction): N = self.num*f.num else: N = self.num*f D = self.den If f is an integer, use (a/b + f) = (a+bf)/b If f is a Fraction, use (a/b)(c/d) = (ac)/(bd) More Flexible mul Be Careful! def mul (self,f): if isinstance(f,fraction): N = self.num*f.num else: N = self.num*f D = self.den If f is an int, use (a/b)(f) = (af)/b >>> F = Fraction(2,3) >>> G = F + >>> print G 5/3 >>> H = + F When you add an int to a Fraction, the int must be on the right side of the + Traceback (most recent call last): File "<stdin>", line, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'instance' n Example Let s compute + /2 + /3 + + /5 n = 5 s = Fraction() for k in range(,n+): s = s + Fraction(,k) print s Next, a Class that Supports Computations with Dates 95757/3636 This + invokes add. 4

5 4/9/26 If Today is July 4, 776, then What is Tomorrow s Date? The Check is in the Mail and will rrive in Days >>> D = SimpleDate('7/4/776') >>> print D July 4, 776 >>> E = D.Tomorrow() >>> print E July 5, 776 >>> D = SimpleDate('//26') >>> = D+ >>> print September 27, 28 How Many Days from Pearl Harbor to 9/? >>> D = SimpleDate('9//2') >>> D2 = SimpleDate('2/7/94') >>> NumDays = D-D2 >>> print NumDays 2828 Class Variables To pull this off, it will be handy to have a class variable that houses information that figures in date-related computations ndays =[,3,28,3,3,3,3,3,3,3,3,3,3] The ttributes class SimpleDate(object): m: index of month [int] d: the day [int] y: the year [int] m, d, and y identify a valid date. The Leap Year Problem n integer y is a leap year if it is not a century year and is divisible by 4 or if is a century year and is divisible by 4. def isleapyear(self): Returns True if and only if self encodes a date that part of a leap year. thisway = ((y%>) and y%4==) thatway = ((y%==) and (y%4==)) return thisway or thatway 5

6 4/9/26 Visualizing a SimpleDate Object >>> D = SimpleDate( 7/4/776 ) D m d y SimpleDate The SimpleDate Constructor def init (self,s): Returns a reference to a SimpleDate representation of the date encoded in s. PreC: s is a date string of the form 'M/D/Y'where M, D and Y encode the month index, the day, and the year. v = s.split('/') m = int(v[]),d = int(v[]),y = int(v[2]) self.m = m, self.d = d, self.y = y If s = 7/4/776 then v = [ 7, 4, 776 ] The SimpleDate Constructor The SimpleDate Constructor Note that D = SimpleDate( 7/32/776 ) def init (self,s): Returns a reference to a SimpleDate representation of the date encoded in s. and D = SimpleDate( 2/29/25 ) produce SimpleDate objects that encode invalid dates. PreC: s is a date string of the form 'M/D/Y'where M, D and Y encode the month index, the day, and the year. v = s.split('/') m = int(v[]);d = int(v[]);y = int(v[2]) self.m = m; self.d = d; self.y = y good place to guard against bad input using assert. Use Class Variable ndays Some SimpleDate Methods ndays =[,3,28,3,3,3,3,3,3,3,3,3,3] Informally Tomorrow the next day s date v = s.split('/') m = int(v[]);d = int(v[]);y = int(v[2]) assert <=m<=2, 'Invalid Month' assert <=d<=self.ndays[m], 'Invalid Day' eq when are two dates the same? add 7/4/ is 7/3/777 Needs more work. Does not handle leap year situations. Nothing wrong with SimpleDate( 2/29/26 ) sub 3/2/26 2/28/26 is 3 6

7 4/9/26 Visualizing the Overall Class class SimpleDate(object): ndays = [ blah ] Class Variables def init (self,s): Constructor def str (self): def eq (self,other): def add (self,other) Methods def sub (self,other): def Tomorrow(self): def isleapyear(self): The Method Tomorrow >>> D = SimpleDate( 7/4/776 ) >>> T = D.Tomorrow() >>> print T July 5, 776 Pretty printing via str D T m d y m d y SimpleDate SimpleDate The Method Tomorrow Need a bunch of if constructions to handle end-of-month and end-of-year situations with possible leap year issues: 7/4/ > 7/5/776 2/28/ > 2/29/776 2/28/ > 3//777 7/3/ > 8//776 2/3/ > //777 The eq Method def eq (self,other): Returns True if and only if other encodes the same date as self B = self.m == other.m B2 = self.d == other.d B3 = self.y == other.y return B and B2 and B3 >>> D = SimpleDate('7/4/776') >>> D2 = SimpleDate('4//66') >>> D==D2 False The add Method def add (self,n): Returns a date that is n days later than self. PreC: n is a nonegative integer. Day = self for k in range(n): Day = Day.Tomorrow() return Day >>> D = SimpleDate( //26 ) >>> E = D >>> print E December 3, 26 The sub Method def sub (self,other): "" D2-D returns the number of days from D to D2. D2 must be the later date. k = Day = other while not (Day==self): k+= Day = Day.Tomorrow() return k >>> D = SimpleDate('9//2') >>> D2 = SimpleDate('2/7/94') >>> D-D

8 4/9/26 Referencing a Class Variable def Tomorrow(self): m = self.m d = self.d y = self.y Last = self.ndays[m] if isleapyear(y) and m==2: Last+= : subtle issue is involved if you try to copy objects that have attributes that are objects themselves. ndays =[,3,28,3,3,3,3,3,3,3,3,3,3] To illustrate consider this class >>> = MyColor([,,], red ) class MyColor: : length-3 float list : str def init (self,,): self. = self. = >>> B = copy() >>> B = copy() Now let s make a yellow B B 8

9 4/9/26 >>>.[]= >>>. = yellow >>> B = deepcopy() Unintended Effect B.Rgb refers to a yellow triple B yellow deepcopy copies everything B 9

Creating a new data type

Creating a new data type Appendix B Creating a new data type Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building

More information

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

Lecture 18. Classes and Types

Lecture 18. Classes and Types Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

COMPSCI 105 S Principles of Computer Science. Classes 3

COMPSCI 105 S Principles of Computer Science. Classes 3 S2 2017 Principles of Computer Science Classes 3 Exercise } Exercise } Create a Student class: } The Student class should have three attributes: id, last_name, and first_name. } Create a constructor to

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions User Defined Functions In previous labs, you've encountered useful functions, such as sqrt() and pow(), that were created by other

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Structure and Flow. CS 3270 Chapter 5

Structure and Flow. CS 3270 Chapter 5 Structure and Flow CS 3270 Chapter 5 Python Programs Are made up of modules One module is the main (top-level) module The first one loaded (even if it s the interpreter) Its module object has main as its

More information

Extended Introduction to Computer Science CS1001.py Lecture 13: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP)

Extended Introduction to Computer Science CS1001.py Lecture 13: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Extended Introduction to Computer Science CS1001.py Lecture 13: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants:

More information

Functions and Decomposition

Functions and Decomposition Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the

More information

Extended Introduction to Computer Science CS1001.py Lecture 15: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP)

Extended Introduction to Computer Science CS1001.py Lecture 15: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Extended Introduction to Computer Science CS1001.py Lecture 15: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Instructors: Benny Chor, Amir Rubinstein Teaching Assistants:

More information

Lecture 18. Methods and Operations

Lecture 18. Methods and Operations Lecture 18 Methods and Operations Announcements for This Lecture Assignments A4 Due Thursday at midnight Hopefully you are on Task 4 Extra consultants available Will post A5 on Thursday Written assignment

More information

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99 1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College September 6, 2017 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9 CS1110 Spring 2016 Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9 You must work either on your own or with one partner. If you work with a partner, you and your partner must first register

More information

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013 , part Deux CSE 231, Rich Enbody Three Groups Users Programmers Class Designers 1 Getters and Setters getters: methods that fetch the value setters: methods set a value 2 GetterSetter Example Why do this?

More information

CS 215 Fundamentals of Programming II Spring 2011 Project 2

CS 215 Fundamentals of Programming II Spring 2011 Project 2 CS 215 Fundamentals of Programming II Spring 2011 Project 2 20 points Out: February 2, 2011 Due: February 9, 2011 Reminder: Programming Projects (as opposed to Homework exercises) are to be your own work.

More information

CIT 590 Homework 6 Fractions

CIT 590 Homework 6 Fractions CIT 590 Homework 6 Fractions Purposes of this assignment: Get you started in Java and Eclipse Get you comfortable using objects in Java Start looking at some common object uses in Java. General Idea of

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1 OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13]

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

CS1110 Lab 6 (Mar 17-18, 2015)

CS1110 Lab 6 (Mar 17-18, 2015) CS1110 Lab 6 (Mar 17-18, 2015) First Name: Last Name: NetID: The lab assignments are very important and you must have a CS 1110 course consultant tell CMS that you did the work. (Correctness does not matter.)

More information

isinstance and While Loops

isinstance and While Loops CS 1110: Introduction to Computing Using Python Lecture 20 isinstance and While Loops [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements A4: Due 4/20 at 11:59pm Should only use our str method

More information

Recitation #2 Abstract Data Types, Collection Classes, and Linked List

Recitation #2 Abstract Data Types, Collection Classes, and Linked List Recitation #2 Abstract Data Types, Collection Classes, and Linked List (1) Create an ADT Fraction that describes properties of fractions. Include the constructor, setter, getter, and tostring() methods

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

Rational number operations can often be simplified by converting mixed numbers to improper fractions Add EXAMPLE:

Rational number operations can often be simplified by converting mixed numbers to improper fractions Add EXAMPLE: Rational number operations can often be simplified by converting mixed numbers to improper fractions Add ( 2) EXAMPLE: 2 Multiply 1 Negative fractions can be written with the negative number in the numerator

More information

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5'

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5' 7 Unit Testing Lab Objective: Finding and fixing programming errors can be difficult and time consuming, especially in large or complex programs. Unit testing is a formal strategy for finding and eliminating

More information

Lecture 19. Operators and Abstraction

Lecture 19. Operators and Abstraction Lecture 19 Operators and Abstraction Announcements Reading Tuesday: Chapter 18 Thursday reading online Assignments A4 due tonight at Midnight 10 pts per day late Consultants available tonight A5 posted

More information

02157 Functional Programming Lecture 2: Functions, Basic Types and Tuples

02157 Functional Programming Lecture 2: Functions, Basic Types and Tuples Lecture 2: Functions, Basic Types and Tuples nsen 1 DTU Informatics, Technical University of Denmark Lecture 2: Functions, Basic Types and Tuples MRH 13/09/2012 Outline A further look at functions, including

More information

Objectives Getting Started What Is Computer Science? Review of Basic Python Summary. Introduction 1/25/06. Introduction

Objectives Getting Started What Is Computer Science? Review of Basic Python Summary. Introduction 1/25/06. Introduction Brad Miller David Ranum 1/25/06 Outline Objectives 1 Objectives 2 3 What Is Programming? Why Study Data Structures and Abstract Data Types? Why Study Algorithms? 4 with Data Object-Oriented Programming

More information

Python Development with PyDev and Eclipse -

Python Development with PyDev and Eclipse - 1 of 11 4/4/2013 9:41 PM 130 Free tutorial, donate to support Python Development with PyDev and Eclipse - Tutorial Lars Vogel Version 1.8 Copyright 2009, 2010, 2011, 2012 Lars Vogel 01.07.2012 Revision

More information

Conditionals !

Conditionals ! Conditionals 02-201! Computing GCD GCD Problem: Compute the greatest common divisor of two integers. Input: Two integers a and b. Output: The greatest common divisor of a and b. Exercise: Design an algorithm

More information

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) Class 2: Variables and Memory Variables A variable is a value that is stored in memory It can be numeric or a character C++ needs to be told what type it is before it can store it in memory It also needs

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

27. Means and Medians. What? What? Three Instructive Problems: The Apportionment Problem The Polygon Averaging Problem The Median Filtering Problem

27. Means and Medians. What? What? Three Instructive Problems: The Apportionment Problem The Polygon Averaging Problem The Median Filtering Problem 2. Means and Medians What? Three Instructive Problems: The Apportionment Problem The Polygon Averaging Problem The Median Filtering Problem The Apportionment Problem How to fairly distribute 435 Congressional

More information

Lecture 18: Using Classes Effectively (Chapter 16)

Lecture 18: Using Classes Effectively (Chapter 16) http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 18: Using Classes Effectively (Chapter 16) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner,

More information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-Liang Lu Java Programming 45 / 79 1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Writing a Fraction Class

Writing a Fraction Class Writing a Fraction Class So far we have worked with floa0ng-point numbers but computers store binary values, so not all real numbers can be represented precisely In applica0ons where the precision of real

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information

Week 2. Classes and Objects

Week 2. Classes and Objects Week 2 Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

More information

Arithmetic and Bitwise Operations on Binary Data

Arithmetic and Bitwise Operations on Binary Data Arithmetic and Bitwise Operations on Binary Data CSCI 2400: Computer Architecture ECE 3217: Computer Architecture and Organization Instructor: David Ferry Slides adapted from Bryant & O Hallaron s slides

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Python for Informatics

Python for Informatics Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.

More information

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern CSE 399-004: Python Programming Lecture 12: Decorators April 9, 200 http://www.seas.upenn.edu/~cse39904/ Announcements Projects (code and documentation) are due: April 20, 200 at pm There will be informal

More information

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output? Arithmetic Operators Section 2.15 & 3.2 p 60-63, 81-89 1 Today Arithmetic Operators & Expressions o Computation o Precedence o Associativity o Algebra vs C++ o Exponents 2 Assigning floats to ints int

More information

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Final, December 8th, Question Points Score Total: 100 CS 1110 Final, December 8th, 2016 This 150-minute exam has 8 questions worth a total of 100 points. Scan the whole test before starting. Budget your time wisely. Use the back of the pages if you need more

More information

Computational Mathematics with Python

Computational Mathematics with Python Numerical Analysis, Lund University, 2012 1 Computational Mathematics with Python Unit 8: Object oriented programming with classes Numerical Analysis, Lund University Claus Führer, Olivier Verdier, Tony

More information

ISA 563 : Fundamentals of Systems Programming

ISA 563 : Fundamentals of Systems Programming ISA 563 : Fundamentals of Systems Programming Variables, Primitive Types, Operators, and Expressions September 4 th 2008 Outline Define Expressions Discuss how to represent data in a program variable name

More information

Exceptions. raise type(message) raise Exception(message)

Exceptions. raise type(message) raise Exception(message) Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

CSC-140 Assignment 6

CSC-140 Assignment 6 CSC-140 Assignment 6 1 Introduction In this assignment we will start out defining our own classes. For now, we will design a class that represents a date, e.g., Tuesday, March 15, 2011, or in short hand

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Genome Sciences 373 Genome Informa1cs. Quiz Sec1on #1 March 31, 2015

Genome Sciences 373 Genome Informa1cs. Quiz Sec1on #1 March 31, 2015 Genome Sciences 373 Genome Informa1cs Quiz Sec1on #1 March 31, 2015 About me, course logistics, etc. Matthew s contact info Email: mwsnyder@uw.edu Phone: 206-685-3720 Office hours: Mondays 2:00-3:00pm

More information

Computational Mathematics with Python

Computational Mathematics with Python Numerical Analysis, Lund University, 2015 1 Computational Mathematics with Python Unit 7: Object oriented programming with classes Numerical Analysis, Lund University Lecturer: Claus Führer 2015 Classes

More information

Intro. Classes & Inheritance

Intro. Classes & Inheritance Intro Functions are useful, but they're not always intuitive. Today we're going to learn about a different way of programming, where instead of functions we will deal primarily with objects. This school

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

More information

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck! CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, 2011 Name: EID: Section Number: Friday discussion time (circle one): 9-10 10-11 11-12 12-1 2-3 Friday discussion TA(circle one): Wei Ashley Answer

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Functional Programming in Haskell Part I : Basics

Functional Programming in Haskell Part I : Basics Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian

More information

Exceptions. raise type(message) raise Exception(message)

Exceptions. raise type(message) raise Exception(message) Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

3. Conditional Execution

3. Conditional Execution 3. Conditional Execution Topics: Boolean values Relational operators if statements The Boolean type Motivation Problem: Assign positive float values to variables a and b and print the values a**b and b**a.

More information

Lecture 7 Number Theory Euiseong Seo

Lecture 7 Number Theory Euiseong Seo Lecture 7 Number Theory Euiseong Seo (euiseong@skku.edu) 1 Number Theory God created the integers. All else is the work of man Leopold Kronecker Study of the property of the integers Specifically, integer

More information

Lecture 10: Boolean Expressions

Lecture 10: Boolean Expressions Lecture 10: Boolean Expressions CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (12/10/17) Lecture 10: Boolean Expressions

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #06 Loops: Operators We have seen comparison operators, like less then, equal to, less than or equal. to and

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Rational Numbers: Multiply and Divide

Rational Numbers: Multiply and Divide Rational Numbers: Multiply and Divide Multiplying Positive and Negative Numbers You know that when you multiply a positive number by a positive number, the result is positive. Multiplication with negative

More information

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators Sven Schmit stanford.edu/~schmit/cme193 6: Classes and iterators 6-1 Contents Classes Generators and Iterators Exercises 6: Classes

More information

Names and Functions. Chapter 2

Names and Functions. Chapter 2 Chapter 2 Names and Functions So far we have built only tiny toy programs. To build bigger ones, we need to be able to name things so as to refer to them later. We also need to write expressions whose

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

DESIGN OF A COMPOSITE ARITHMETIC UNIT FOR RATIONAL NUMBERS

DESIGN OF A COMPOSITE ARITHMETIC UNIT FOR RATIONAL NUMBERS DESIGN OF A COMPOSITE ARITHMETIC UNIT FOR RATIONAL NUMBERS Tomasz Pinkiewicz, Neville Holmes, and Tariq Jamil School of Computing University of Tasmania Launceston, Tasmania 7250 AUSTRALIA Abstract: As

More information

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018 Fundamentals of Programming (Python) Object-Oriented Programming Ali Taheri Sharif University of Technology Outline 1. Python Data Types 2. Classes and Objects 3. Defining Classes 4. Working with Objects

More information

Lecture 19. Using Classes Effectively

Lecture 19. Using Classes Effectively Lecture 19 Using Classes Effectively Announcements Reading Tuesday: Chapter 18 Thursday reading online Assignments A4 due tonight at Midnight 10 pts per day late Consultants available tonight A5 & A6 posted

More information

Lecture 9: July 14, How to Think About Debugging

Lecture 9: July 14, How to Think About Debugging Lecture 9: July 14, 2011 How to Think About Debugging So, you wrote your program. And, guess what? It doesn t work. L Your program has a bug in it Somehow, you must track down the bug and fix it Need to

More information

Last Name: UTION First Name: SOL Cornell NetID: CS1110. Solution: CS 1110 Prelim 2 April 26, 2016

Last Name: UTION First Name: SOL Cornell NetID: CS1110. Solution: CS 1110 Prelim 2 April 26, 2016 Last Name: UTION First Name: SOL Cornell NetID: CS1110 CS 1110 Prelim 2 April 26, 2016 1. [6 points] What is the output if the following module is run: def F1(x): y = [] # empty list n = len(x) for k in

More information

CS 1110 Prelim 2 April 21, 2015 GRADING GUIDE

CS 1110 Prelim 2 April 21, 2015 GRADING GUIDE CS 1110 Prelim 2 April 21, 2015 GRADING GUIDE Problem 1 15 points Problem 2 15 points Problem 3 15 points Problem 4 20 points Problem 5 20 points Problem 6 15 points Problem Total 20 points 95-100 xxxxxxxxxxxxxxxxxxxxxxxxx

More information

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Syntax and Grammars 1 / 21

Syntax and Grammars 1 / 21 Syntax and Grammars 1 / 21 Outline What is a language? Abstract syntax and grammars Abstract syntax vs. concrete syntax Encoding grammars as Haskell data types What is a language? 2 / 21 What is a language?

More information

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

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016 CS 31: Intro to Systems Binary Arithmetic Martin Gagné Swarthmore College January 24, 2016 Unsigned Integers Suppose we had one byte Can represent 2 8 (256) values If unsigned (strictly non-negative):

More information

Lecture 15: Intro to object oriented programming (OOP); Linked lists

Lecture 15: Intro to object oriented programming (OOP); Linked lists Extended Introduction to Computer Science CS1001.py Lecture 15: Intro to object oriented programming (OOP); Linked lists Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal Kleinbort,

More information

Working with classes and objects COSC346

Working with classes and objects COSC346 Working with classes and objects COSC346 Initialisation An object should be self-contained: independent and selfsufficient Should allocate resources (memory) required for its operation Should initialise

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Section A Arithmetic ( 5) Exercise A

Section A Arithmetic ( 5) Exercise A Section A Arithmetic In the non-calculator section of the examination there might be times when you need to work with quite awkward numbers quickly and accurately. In particular you must be very familiar

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

Getting Started Values, Expressions, and Statements CS GMU

Getting Started Values, Expressions, and Statements CS GMU Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter

More information

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018 CS 31: Intro to Systems C Programming Kevin Webb Swarthmore College September 13, 2018 Reading Quiz Agenda Basics of C programming Comments, variables, print statements, loops, conditionals, etc. NOT the

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

User s Guide for BDDs in Jython

User s Guide for BDDs in Jython User s Guide for BDDs in Jython Mark Greenstreet, January 29, 2013 1 Overview I ll add something here about downloading the package, running it on UBC CS department machines, etc. 2 Class SymBool Class

More information

PREPARING FOR PRELIM 1

PREPARING FOR PRELIM 1 PREPARING FOR PRELIM 1 CS 1110: FALL 2012 This handout explains what you have to know for the first prelim. There will be a review session with detailed examples to help you study. To prepare for the prelim,

More information