Transcript Paul

Rational numbers in Python
• Strange rounding-off errors:
>>> 2/3.0
0.6666666666666663
>>> 2/6.0
0.3333333333333331
>>> 5/6.0
0.8333333333333337
• Create class for representing rational numbers by
storing numerator and denominator
15
rational.py
Rational numbers
• Use float to make sure result of division will be a float, not
a rounded down integer
• Object reference self first argument in all methods
• self refers to the object on which the method is called
16
Creating and using RationalNumber objects
>>> from rational import RationalNumber
>>> a = RationalNumber(3, 4)
>>> b = RationalNumber(3, 6)
>>> a.getValue()
0.75
>>> b.getValue()
0.5
>>> b.getNumerator()
1
>>> b.getDenominator()
2
No self argument in
method calls!
Python puts object reference
in place of self
17
Forgetting the self. prefix when
referencing object attributes
Initializes only local variables which go out of scope
when constructor terminates!
18
Binary search tree
a
elements < a
elements >= a
19
Binary search tree
a
b
elements < a
elements < b < a
elements >= a
b <= elements < a
20
Binary search tree of rational numbers
21
binary_tree.py
Node class
from course
notes
Use this class to
represent the
search tree nodes:
Each data attribute
will be a
RationalNumber
22
searchtree.py (part 1)
Creating RationalNumber objects, adding them to a tree
23
searchtree.py (part 2)
Adding a node to a binary search tree
Recursive function, keeps order in tree
24
Testing
%:~ python –i searchtree.py
Numerator: 2
Denominator: 3
Numerator: 3
Denominator: 4
Numerator: 7
Denominator: 14
Numerator:
>>> root.getData().getvalue()
0.666666666666663
>>> root.getRight().getData().getvalue()
0.75
>>> root.getLeft().getData().getvalue()
0.50
25
searchtree.py (part 3)
Searching for a node
Fast searching if tree is balanced
26
Searching for a node, demonstration
searchtreetest.py
Search in big tree of random rational numbers
27
Numerator: 2
Denominator? 3
Closest match:
Numerator: 4
Denominator? 5
Closest match:
Numerator: 1
Denominator? 2
Closest match:
Numerator: 4
Denominator? 9
Closest match:
Numerator: 10
Denominator? 1
Closest match:
Numerator: 5
Denominator? 3
Closest match:
433/650
43/54
370/737
391/878
994/103
521/313
28
.. on to the exercises
29