[Tutor] Fraction Class HELP ME PLEASE!

Quiles, Stephanie stephanie.quiles001 at albright.edu
Fri Aug 7 01:50:59 CEST 2015


thanks Cameron! Here is what i have so far… new question… how do i test the iadd, imul, etc. operators? Hopefully this time the indents show up. And yes the beginning code came out of our text book I added on some functions myself but they give you a big chunk of it. I am hoping that this is what the professor was looking for. I want to add some more operators but am unsure how to put them in or test them? For example I want to add __ixor__, itruediv, etc. Any other suggestions would be great! 

Thanks 


def gcd(m, n):
    while m % n != 0:
        oldm = m
        oldn = n

        m = oldn
        n = oldm % oldn
    return n

class Fraction:
    def __init__(self, top, bottom):
        self.num = top
        self.den = bottom

    def __str__(self):
        if self.den == 1:
            return str(self.num)
        elif self.num == 0:
            return str(0)
        else:
            return str(self.num) + "/" + str(self.den)

    def simplify(self):
        common = gcd(self.num, self.den)

        self.num = self.num // common
        self.den = self.den // common

    def show(self):
        print(self.num, "/", self.den)

    def __add__(self, otherfraction):
        newnum = self.num * otherfraction.den + \
                 self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __sub__(self, otherfraction):
        newnum = self.num * otherfraction.den - \
                 self.den * otherfraction.num
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __mul__(self, otherfraction):
        newnum = self.num * otherfraction.num * \
                 self.den * otherfraction.den
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __imul__(self, otherfraction):
        if isinstance(otherfraction):
            return self__mul__(otherfraction)

    def __iadd__(self, otherfraction):
        if isinstance(otherfraction):
            return self__iadd__(otherfraction)

    def __truediv__(self, otherfraction):
        newnum = self.num * otherfraction.num // self.den * otherfraction.den
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def __pow__(self, otherfraction):
        newnum = self.num * otherfraction.num ** self.den * otherfraction.den
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)


    def __radd__(self, otherfraction):
        newnum = self.num * otherfraction.num // self.den * otherfraction.den
        newden = self.den * otherfraction.den
        common = gcd(newnum, newden)
        return Fraction(newnum // common, newden // common)

    def getNum(self):
        return self.num

    def getDen(self):
        return self.den

    def __gt__(self, otherfraction):
        return (self.num / self.den) > (otherfraction.num / otherfraction.den)

    def __lt__(self, otherfraction):
        return (self.num / self.den) < (otherfraction.num / otherfraction.den)

    def __eq__(self, otherfraction):
        return (self.num / self.den) == (otherfraction.num / otherfraction.den)

    def __ne__(self, otherfraction):
        return (self.num /self.den) != (otherfraction.num /otherfraction.den)

    def __is__(self, otherfraction):
        return (self.num / self.den) is (otherfraction.num / otherfraction.den)




def main():
    F1 = Fraction(1,2)
    F2 = Fraction(2,3)
    print("F1 = ", F1)
    print("F2 = ", F2)
    print("Add Fractions: F1 + F2=", Fraction.__add__(F1, F2))
    print("Subtract Fractions: F1 - F2=", Fraction.__sub__(F1, F2))
    print("Multiply Fractions: F1 * F2=", Fraction.__mul__(F1, F2))
    print("True Division with Fractions: F1 / F2=", Fraction.__truediv__(F1, F2))
    print("Exponentiation with Fractions: F1 // F2=", Fraction.__pow__(F1, F2))
    print("Is F1 Greater than F2?:", Fraction.__gt__(F1, F2))
    print("Is F1 less than F2?:", Fraction.__lt__(F1, F2))
    print("Is F1 Equal to F2?:", Fraction.__eq__(F1, F2))
    print("Is F1 different than F2?:", Fraction.__ne__(F1, F2))
    print ("Is F1 same as F2?:", Fraction.__is__(F1, F2))
    print("Is:", Fraction.__iadd__(F1, F2))

if __name__ == '__main__':
    main()

> On Aug 6, 2015, at 5:44 PM, Cameron Simpson <cs at zip.com.au> wrote:
> 
> On 06Aug2015 16:55, Quiles, Stephanie <stephanie.quiles001 at albright.edu> wrote:
>> I need to do the following assignment. I need to know how do i hard code an example for each of the operators I am implementing? What i have so far is below? He said he does not care if we plug in some numbers or if we have user input numbers, however I am unsure of how to write a program that tests each operator? Or can i write one that tests all of them? I don’t know where to start with this. Please help!
> 
> For someone who doesn't know where to start, you seem to have a lot of decent looking code. Is the code below all yours? If so, a good start.
> 
> Also, please try to preserve the indentation when pasting in code; indentation is critical in Python as you know and incorrect indentation, when not an outright syntax error, can be a source of bugs. I'll presume your code was originally indented correctly.
> 
> Note that in this list we _do_ like code to be pasted inline where it can be seen directly and commented on like any other part of the message text. We're not big on attachments or links to external things (other than doco citations like your reference to the operators Python page).
> 
>> You may implement as many of these operators as you like (such as isub,
>> itruediv, etc.) You MUST indicate in your header information which operators
>> you are implementing, and you MUST hard code an example for each.
> 
> "Header information" is usually an opening comment. So perhaps start the program with text like this:
> 
> # Here is a Fraction class implementing variaous operators. It currently
> # supports:
> #
> # + (addition)
> # - (subtraction)
> # * (multiplication)
> # / (true division)
> #
> 
> and so forth.
> 
> Regarding examples and tests, one workable approach to to make your program work as a "main program". The idea is that is invoked as a main program it will run the examples or tests.
> 
> As your code sits now it could be used as a module - someone could place it into python's library tree and import it, and use your Fraction class.  However, you can of course run it directly at the command prompt, eg:
> 
> % python your-fraction-file.py
> 
> When you do that, the code is still imported as a module but with the special name '__main__'. So what a lot of python modules do is have a "main" function which is to be fired only in the command line circumstance, such as:
> 
> def main():
>   F1 = Fraction(1, 2)     # 1/2
>   F2 = Fraction(2, 3)     # 2/3
>   print("F1 =", F1)
>   print("F2 =", F2)
>   print("F1 + F2 =", F1 + F2)
>   print("F1 - F2 =", F1 - F2)
>   print("F1 * F2 =", F1 * F2)
> 
> In order to make your program work as both an importable module which defines the Fraction class but does not run the main function and also as a main program which defines the class and then runs the main function you put this piece of boilerplate code on the very bottom of the program:
> 
> if __name__ == '__main__':
>   main()
> 
> which checks if you're invoking it directly from the command line. If so, run the main function.
> 
> Hopefully that gives you an idea about hardwiring examples also.
> 
> Regarding tests, you might write a simple function like this:
> 
> def check(label, computed, expected):
>   ok = computed == expected
>   if ok:
>     print(label, 'OK', computed, '==', expected)
>   else:
>     print(label, 'BAD', computed, '!=', expected)
>   return ok
> 
> Then you might consider modifying your main program to run tests instead of bare examples, replacing:
> 
> print("F1 + F2 =", F1 + F2)
> 
> with:
> 
> check("F1 + F2", F1 + F2, Fraction(7, 6))
> 
> Because check() returns whther the check was ok, you might even count the number of failures for some kind of report:
> 
> fail_count = 0
> ...
> if not check("F1 + F2", F1 + F2, Fraction(7, 6)):
>   fail_count += 1
> ... more checks ...
> print(fail_count, "failures")
> 
> and so forth.
> 
> This also gets you test code so that you can test your own program for correctness before submitting your assignment.
> 
> Feel free to return to this list with updated code and new questions.
> 
> Cheers,
> Cameron Simpson <cs at zip.com.au>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list