1.17. Programming Exercises - Problem Solving With Algorithms and Data Structures
1.17. Programming Exercises - Problem Solving With Algorithms and Data Structures
2. In many w ays it w ould be better if all f ractions w ere maintained in low est terms right f rom
the start. Modif y the constructor f or the Fraction class so that GCD is used to reduce
f ractions immediately. Notice that this means the __add__ f unction no longer needs to
reduce. Make the necessary modif ications.
3. Implement the remaining simple arithmetic operators ( __sub__ , __mul__ , and __truediv__ ).
4. Implement the remaining relational operators ( __gt__ , __ge__ , __lt__ , __le__ , and
__ne__ )
5. Modif y the constructor f or the f raction class so that it checks to make sure that the numerator
and denominator are both integers. If either is not an integer the constructor should raise an
exception.
6. In the def inition of f ractions w e assumed that negative f ractions have a negative
numerator and a positive denominator. Using a negative denominator w ould cause some of
the relational operators to give incorrect results. In general, this is an unnecessary
constraint. Modif y the constructor to allow the user to pass a negative denominator so that
all of the operators continue to w ork properly.
7. Research the __radd__ method. How does it diff er f rom __add__ ? When is it used? Implement
__radd__ .
8. Repeat the last question but this time consider the __iadd__ method.
9. Research the __repr__ method. How does it diff er f rom __str__ ? When is it used? Implement
__repr__ .
10. Research other types of gates that exist (such as NAND, NOR, and XOR). Add them to the
1 of 2
1.17. Programming Exercises Problem Solving with Algorithms
6/11/17,
an... 2:50 PM
circuit hierarchy. How much additional coding did you need to do?
11. The most simple arithmetic circuit is know n as the half -adder. Research the simple half -adder
circuit. Implement this circuit.
13. The circuit simulation show n in this chapter w orks in a backw ard direction. In other w ords, given
a circuit, the output is produced by w orking back through the input values, w hich in turn cause
other outputs to be queried. This continues until external input lines are f ound, at w hich point the
user is asked f or values. Modif y the implementation so that the action is in the f orw ard direction;
upon receiving inputs the circuit produces an output.
14. Design a class to represent a playing card. Now design a class to represent a deck of
cards. Using these tw o classes, implement a f avorite card game.
15. Find a Sudoku puzzle in the local new spaper. Write a program to solve the puzzle.
2 of 2