Exercises

Ex. 1 → Write a method simplify to the class RationalNumber. This method should return the simplified version of the fraction as a tuple.

Ex. 2 → To provide results with confidence intervals a special calculus, so-called interval arithmetic is introduced in numerical mathematics; (refer to [3, 14]). Define a class called Interval and provide it with methods for addition, subtraction, division, multiplication, and power (with positive integers only). These operations obey the following rules:

Exercises.

Provide this class with methods that allow operations of the type a + I, a I, I + a, I a, where I is an interval and a an integer or float. Convert an integer or float to an interval [a,a] first. (Hint: you may want to use function decorators for this; (refer to section Function as decorators in Chapter 7, Functions). Furthermore, implement the __contains__ method, which enables you to check if a given number belongs to the interval using the syntax x in I for an object I of type Interval. Test your class by applying a polynomial f=lambda x: 25*x**2-4*x+1 to an interval.

Ex. 3 → Consider the example under section Classes as decorators. Extend this example to obtain a function decorator that counts how often a certain function is called.

Ex. 4 → Compare the two ways to implement a method for reverse addition __radd__ in the class RationalNumber: the one given in the example in section Special methods and the one given here:

class RationalNumber:
    ....
    def __radd__(self, other):
        return other + self

Do you expect an error in this version? What is the error and how do you explain it? Test your answer by executing:

q = RationalNumber(10, 15)
5 + q

Ex. 4 → Consider the decorator class CountCalls as in example in section Classes as decorators. Provide this class with a method, reset, which sets the counters of all functions in the dictionary, CountCalls.instances, to zero. What would happen if the dictionary were replaced by an empty dictionary instead?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.221