COMPSCI 105 S Principles of Computer Science. Classes 3

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

Creating a new data type

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum

Computational Mathematics with Python

Computational Mathematics with Python

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

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

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

CSI33 Data Structures

Accuplacer Arithmetic Study Guide

Student Success Center Arithmetic Study Guide for the ACCUPLACER (CPT)

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

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

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

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

Lecture 18. Methods and Operations

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators

The Bracket Strategy

1. To add (or subtract) fractions, the denominators must be equal! a. Build each fraction (if needed) so that both denominators are equal.

Lecture 19. Operators and Abstraction

Fractions. There are several terms that are commonly used when working with fractions.

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter Lab 8 - Structures

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

Object Oriented Programming

Week 2. Classes and Objects

Class Design (Section 9 of 17)

Object Oriented Programming

Python Programming. Introduction Part II

Lecture 21. Programming with Subclasses

CSCE 110: Programming I

What is a Fraction? A fraction is a part or piece of something. The way we write fractions tells us the size of the piece we are referring to

MATH REVIEW SUPPLEMENT. For The ARITHMETIC SECTION. of the. ACCUPLACER Entry Assessment

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

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

CSC148 Intro. to Computer Science

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

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

UCT Algorithm Circle: Number Theory

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

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

Lesson 1: Arithmetic Review

Lecture 07: Python Generators, Iterators, and Decorators

Course Learning Outcomes for Unit I. Reading Assignment. Unit Lesson. UNIT I STUDY GUIDE Number Theory and the Real Number System

Section A Arithmetic ( 5) Exercise A

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

Accuplacer Arithmetic Review

Lecture 18. Classes and Types

Unit: Rational Number Lesson 3.1: What is a Rational Number? Objectives: Students will compare and order rational numbers.

What is a Fraction? Fractions. One Way To Remember Numerator = North / 16. Example. What Fraction is Shaded? 9/16/16. Fraction = Part of a Whole

Section 2.3 Rational Numbers. A rational number is a number that may be written in the form a b. for any integer a and any nonzero integer b.

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

Any Integer Can Be Written as a Fraction

Building Equivalent Fractions, the Least Common Denominator, and Ordering Fractions

CS 215 Fundamentals of Programming II Spring 2011 Project 2

Rational numbers as decimals and as integer fractions

Mini-Lesson 1. Section 1.1: Order of Operations PEMDAS

Lecture 18: Using Classes Effectively (Chapter 16)

CS 234 Python Review Part 2

Supplemental Worksheet Problems To Accompany: The Pre-Algebra Tutor: Volume 2 Section 12 Variables and Expressions

CS177 Python Programming. Recitation 2 - Computing with Numbers

Operators in C. Staff Incharge: S.Sasirekha

FUNDAMENTAL ARITHMETIC

A.4 Rationalizing the Denominator

Introduction to Programming: Lecture 10

Writing a Fraction Class

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

Shell programming. Introduction to Operating Systems

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

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

6.3 ADDING and SUBTRACTING Rational Expressions REVIEW. When you ADD rational numbers (fractions): 1) Write each number with common denominator

Islamic University Gaza Engineering Faculty Department of Computer Engineering ECOM 2125: Assembly Language LAB

Python 2 Conditionals and loops Matthew Egbert CS111

CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes

Review 2. Classes and Subclasses

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

Lesson 1: Arithmetic Review

ECEN 468 Advanced Logic Design

Programming I. Course 9 Introduction to programming

Modesto Junior College Course Outline of Record CMPSC 241

Chapter 1 An Introduction to Computer Science. INVITATION TO Computer Science 1

Arithmetic Review: Decimal Fractions *

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2.

CSE 2021 Computer Organization. Hugh Chesser, CSEB 1012U W4-W

Algebra2go: Working with Fractions and Mixed Numbers

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

DESIGN OF A COMPOSITE ARITHMETIC UNIT FOR RATIONAL NUMBERS

A. Incorrect! To simplify this expression you need to find the product of 7 and 4, not the sum.

Computational Physics

EE 152 Advanced Programming LAB 7

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Loops / Repetition Statements

50 MATHCOUNTS LECTURES (6) OPERATIONS WITH DECIMALS

Fifth Grade Math Rubric

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

CSC324 Principles of Programming Languages

ARM Shift Operations. Shift Type 00 - logical left 01 - logical right 10 - arithmetic right 11 - rotate right. Shift Amount 0-31 bits

Lecture 21. Programming with Subclasses

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

Transcription:

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 initialize the values } Implement the repr method and str method >>> s1 = Student(1, 'Angela', 'Chang') >>> s1 >>> print(s1) Student(1, Angela, Chang) 1: Angela Chang 2

Reminder Fraction class } Write a class to represent fractions in Python } create a fraction } add } subtract } multiply } divide } text representation numerator ½ denominator 3

Overloading Operators } Python operators work for built-in classes. } But same operator behaves differently with different types. } E.g. the + operator: } perform arithmetic addition on two numbers, } merge two lists } concatenate two strings. } Allow same operator to have different meaning according to the context is called operator overloading Operator Expression Internally Addition f1 + f2 f1. add (f2) Subtraction f1 - f2 f1. sub (f2) Equality f1 == f2 f1. eq (f2) 4

The add method } The add method is called when the + operator is used } If we implement add then we can use + to add the objects } f1 + f2 gets translated into f1. add (f2) def add (self, other): new_num = self. num * other. den + \ self. den * other. num new_den = self. den * other. den return Fraction(new_num, new_den) x = Fraction(1, 2) y = Fraction(1, 4) z = x + y print(z) 6/8 5

The sub method } The sub method is called when the - operator is used } If we implement sub then we can use - to do subtraction } f1 - f2 gets translated into f1. sub (f2) def sub (self, other): new_num = self. num * other. den - \ self. den * other. num new_den = self. den * other. den return Fraction(new_num, new_den) x = Fraction(1, 2) y = Fraction(1, 4) z = x - y print(z) 2/8 6

The eq method } The eq method checks equality of the objects } Default behaviour is to compare the references } We want to compare the contents def eq (self, other): return self. num * other. den == \ other. num * self. den 7

Exercise 1 } What is the output of the following code? x = Fraction(2, 3) y = Fraction(1, 3) z = y + y print(x == z) print(x is z) w = x + y print(w == 1) True False AttributeError: 'int' object has no attribute '_Fraction den' Print(w == Fraction(1, 1) Print(w == Fraction(9, 9) False True 8

Improving the eq method } Check the type of the other operand } If the type is not a Fraction, then not equal? } What other decisions could we make for equality? def eq (self, other): if not isinstance(other, Fraction): return False return self. num * other. den == \ other. num * self. den 9

Improving your code } Fractions: } 12/30 } 2/5 } The first fraction can be simplified to 2/5 } The Common Factors of 12 and 30 were 1, 2, 3 and 6, } The Greatest Common Factor is 6. } So the largest number we can divide both 12 and 30 evenly by is 6 } And so 12/30 can be simplified to 2/5 10

Greatest Common Divisor } Use Euclid's Algorithm } Given two numbers, n and m, find the number k, such that k is the largest number that evenly divides both n and m. def gcd(m, n): while m % n!= 0: old_m = m old_n = n m = old_n n = old_m % old_n return n 11

Improve the constructor } We can improve the constructor so that it always represents a fraction using the "lowest terms" form. } What other things might we want to add to a Fraction? class Fraction: def init (self, top, bottom): #get the greatest common divisor common = Fraction. gcd(top, bottom) self. num = top // common self. den = bottom // common #numerator #denominator def gcd(m, n): while m % n!= 0: old_m = m old_n = n m = old_n n = old_m % old_n return n 12

Exercise 2 } What is the output of the following code? x = Fraction(2,3) y = Fraction(3,4) z = x + y print(z) w = z - Fraction(7, 12) print(w) print(w + Fraction(1,6) == Fraction(1,1)) 17/12 5/6 True 13

Other standard Python operators } Many standard operators and functions: https://docs.python.org/3.4/library/operator.html } Common Arithmetic operators } object. add (self, other) } object. sub (self, other) } object. mul (self, other) } object. truediv (self, other) Inplace arithmetic operators Ø object. iadd (self, other) Ø object. isub (self, other) Ø object. imul (self, other) Ø object. itruediv (self, other) } Common Relational operators } object. lt (self, other) } object. le (self, other) } object. eq (self, other) } object. ne (self, other) } object. gt (self, other) } object. ge (self, other) 14

Exercise 3 } Implement the following methods of the Fraction class: } Multiplication } i.e. mul } Division } i.e. truediv a = Fraction(1, 3) b = Fraction(4, 5) c = a * b d = a / b print (c) print (d) 4/15 5/12 15

Summary } A class is a template, a blueprint and a data type for objects. } A class defines the data fields of objects, and provides an initializer for initializing objects and other methods for manipulating the data. } The initializer always named init. The first parameter in each method including the initializer in the class refers to the object that calls the methods, i.e., self. } Data fields in classes should be hidden to prevent data tampering and to make class easy to maintain. } We can overwrite the default methods in a class definition. 16