New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Anne Ward
Anne Ward
GPA 3.93


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in Electrical Engineering & Computer Science

This 6 page Class Notes was uploaded by Anne Ward on Saturday September 12, 2015. The Class Notes belongs to EECS 12 at University of California - Irvine taught by Staff in Fall. Since its upload, it has received 27 views. For similar materials see /class/201878/eecs-12-university-of-california-irvine in Electrical Engineering & Computer Science at University of California - Irvine.

Similar to EECS 12 at UCI

Popular in Electrical Engineering & Computer Science




Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/12/15
Appendix B Creating a new data type Objectoriented programming languages allow programmers to create new data types that behave much like builtin data types We will explore this capability by building a Fraction class that works very much like the builtin numeric types integers longs and oats Fractions also known as rational numbers are values that can be expressed as a ratio of whole numbers such as 56 The top number is called the numerator and the bottom number is called the denominator We start by de ning a Fraction class with an initialization method that pro vides the numerator and denominator as integers 230 Creating a new data type class Fraction def initself numerator denominator1 selfnumerator numerator selfdenominator denominator The denominator is optional A Fraction with just one just one parameter represents a whole number If the numerator is n we build the Fraction 711 The next step is to write a str method that displays fractions in a way that makes sense The form numeratordenominator is natural here class Fraction def str return quotZdZdquot 39Z selfnumerator selfdenominator To test what we have so far we put it in a le named Fractionpy and import it into the Python interpreter Then we create a fraction object and print it gtgtgt from Fraction import Fraction gtgtgt spam Fraction56 gtgtgt print quotThe fraction isquot spam The fraction is 56 As usual the print command invokes the str method implicitly B1 Fraction multiplication We would like to be able to apply the normal addition subtraction multipli cation and division operations to fractions To do this we can overload the mathematical operators for Fraction objects We ll start with multiplication because it is the easiest to implement To mul tiply fractions we create a new fraction with a numerator that is the product of the original numerators and a denominator that is a product of the original denominators mul is the name Python uses for a method that overloads the operator class Fraction def mulself object return Fractionself numeratorobjectnumerator self denominator object denominator We can test this method by computing the product of two fractions B 1 Fraction multiplication 231 gtgtgt print Fraction56 Fraction34 1524 It works but we can do better We can extend the method to handle multipli cation by an integer We use the type function to test if other is an integer and convert it to a fraction if it is class Fraction def mulself other if typeother type 5 other Fractionother return Fractionselfnumerator othernumerator self denominator other denominator Multiplying fractions and integers now works but only if the fraction is the left operand gtgtgt print Fraction56 4 206 gtgtgt print 4 Fraction56 TypeError mul nor rmul defined for these operands To evaluate a binary operator like multiplication Python checks the left operand rst to see if it provides a mul t at supports the type of the second operan In this case the builtin integer operator doesn t support fractions Next Python checks the right operand to see if it provides an rmul method that supports the rst type In this case we haven t provided rmul so it fails On the other hand there is a simple way to provide rmul class Fraction rmul mul This assignment says that the rmul is the same as mul Now if we evaluate 4 Fraction5 6 Python invokes rmul on the Fraction object and passes 4 as a parameter gtgtgt print 4 Fraction56 206 Since rmul is the same as mul and mul can handle an integer param eter we re all set 232 Creating a new data type B2 Fraction addition Addition is more complicated than multiplication but still not too bad The sum of ab and cd is the fraction adcbbdi Using the multiplication code as a model we can write add and radd class Fraction def addse1f other if typeother type 5 other Fractionltother return Fractionselfnumerator otherdenominator selfdenominator othernumerator selfdenominator otherdenominator radd add We can test these methods with Fractions and integers gtgtgt print Fraction56 Fraction56 6036 gtgtgt print Fraction56 3 236 gtgtgt print 2 Fraction56 17 6 The rst two examples invoke add the last invokes radd B3 Euclid s algorithm In the previous example we computed the sum 56 56 and got 6036 That is correct but it s not the best way to represent the answer To reduce the fraction to its simplest terms we have to divide the numerator and denominator by their greatest common divisor GCD which is 12 The result is 53 In general whenever we create a new Fraction object we should reduce it by dividing the numerator and denominator by their GCD If the fraction is already reduced the GCD is 1 Euclid of Alexandria approx 3257265 BCE presented an algorithm to nd the GCD for two integers m and 71 If n divides m evenly then 71 is the GCD Otherwise the GCD is the GCD of n and the remainder of m divided by n B4 Comparing fractions 233 This recursive de nition can be expressed concisely as a function def gcd m n if m X n return n else return gcdn m39Zn In the rst line of the body we use the modulus operator to check divisibility On the last line we use it to compute the remainder after division Since all the operations we ve written create new Fractions for the result we can reduce all results by modifying the initialization method class Fraction def initself numerator denominator1 g gcd numerator denominator selfnumerator numerator g selfdenominator denominator g Now whenever we create a Fraction it is reduced to its simplest form gtgtgt Fraction 100 36 25 9 A nice feature of gcd is that if the fraction is negative the minus sign is always moved to the numerator B4 Comparing fractions Suppose we have two Fraction objects a and b and we evaluate a b The default implementation of tests for shallow equality so it only returns true if a and b are the same object More likely we want to return true if a and b have the same valueithat is deep equality We have to teach fractions how to compare themselves As we saw in Sec tion 154 we can overload all the comparison operators at once by supplying a cmp met 0 By convention the cmp method returns a negative number if self is less than other zero if they are the same and a positive number if self is greater than other The simplest way to compare fractions is to crossmultiply lf ab gt cd then ad gt bc With that in mind here is the code for cmp 234 Creating a new data type class Fraction def cmpself other diff selfnumerator otherdenominator othernumerator selfdenominator return diff lf self is greater than other then diff will be positive If other is greater then diff will be negative If they are the same diff is zero B5 Taking it further Of course we are not done We still have to implement subtraction by overriding sub and division by overriding divl One way to handle those operations is to implement negation by overriding neg and inversion by overriding invertl Then we can subtract by negat ing the second operand and adding and we can divide by inverting the second operand and multiplying Next we have to provide rsub and rdivl Unfortunately we can t use the same trick we used for addition and multiplication because subtraction and division are not commutative We can t just set rsub and rdiv equal to sub and divl In these operations the order of the operands makes a difference To handle unary negation which is the use of the minus sign with a single operand we override negl We can compute powers by overriding pow but the implementation is a little tricky If the exponent isn t an integer then it may not be possible to represent the result as a Fraction For example Fraction2 Fraction1 2 is the square root of 2 which is an irrational number it can t be represented as a fraction So it s not easy to write the most general version of powl There is one other extension to the Fraction class that you might want to think about So far we have assumed that the numerator and denominator are integers We might also want to allow them to be long integers As an exercise nish the implementation of the Fraction class so that it handles subtraction division exponentiation and long inte gers as numerato39rs and denominators


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.