Exercise 1
Problem Description
In this exercise, we are asked to create a class named Prime
that keeps track of prime numbers, ensuring certain values are considered valid primes and others are not. The class needs to be capable of:
Raising an error when an input is not a valid integer prime.
Tracking previously seen primes to prevent duplicates.
Resetting the state to allow reprocessing of the primes.
The following Python script is used to test the functionality:
1 | from exercise_8_1 import * |
The expected output from running the above code is:
1 | '1 is not a prime number\n' |
My Solution
1 | # isinstance() is useful. |
Standard Solution
1 | # isinstance() is useful. |
Summary
Here’s a comparison of my version with the standard answer, highlighting the main differences and potential advantages:
Prime Checking Method:
- My Version: I use
sqrt(num)
as the upper limit for prime checking, iterating throughfor i in range(2, int(num ** 0.5) + 1)
. This approach is more efficient, especially for larger numbers, as it reduces the number of iterations by only checking up to the square root. - Standard Answer: It checks from
2
top // 2
for factors, which is slightly less efficient for larger numbers because it performs more division operations.
- My Version: I use
Code Structure:
- My Version: Separates the prime-checking logic into a static method
_is_prime
, making the code more modular and reusable. - Standard Answer: Integrates the prime-checking logic directly into the constructor. This keeps the code concise but might make it less reusable if the prime-checking logic is needed elsewhere.
- My Version: Separates the prime-checking logic into a static method
Reset Method:
- My Version: Uses
@classmethod
for resetting the_seen_primes
set, which is more conventional and allows direct calling as a class method. - Standard Answer: Defines
reset
as a standalone function without decorators. While it works, it may seem less consistent with typical class conventions.
- My Version: Uses
Exercise 2
Problem Description
In this exercise, we need to implement a class named Modulo
that represents numbers in modular arithmetic. The class should:
Validate that the modulus is a prime number.
Ensure that both the number and the modulus are integers.
Represent the number in modular form.
The following Python script is used to test the functionality:
1 | from exercise_8_2 import * |
The expected output from running the above code is:
1 | '1 is not a prime number\n' |
Standard Solution
1 | # isinstance() is useful. |
Summary
The Modulo
class validates its inputs and provides a representation for modular arithmetic:
Exception Handling:
PrimeError
is used when the modulus is not a valid prime number.IntError
is used when the input is not an integer.
Prime Check:
- The constructor checks if the modulus is a prime number using a similar approach to the one used in
Exercise 8.1
(so I use standard solution directly). If not, it raisesPrimeError
.
- The constructor checks if the modulus is a prime number using a similar approach to the one used in
Representation:
- The class overrides
__repr__
and__str__
to provide appropriate representations for instances ofModulo
.
- The class overrides
Modular Arithmetic:
- The value of
k
is stored in its modular form by computingk % p
, which ensures it always remains within the bounds of0
top - 1
.
- The value of
Exercise 3
Problem Description
In this exercise, we extend the Modulo
class from Exercise 8.2
to support arithmetic operations, specifically addition and multiplication between two Modulo
objects. The class should:
Support addition (
+
) and multiplication (*
) betweenModulo
objects with the same modulus.Raise appropriate errors if operations are attempted with incompatible objects.
The following Python script is used to test the functionality:
1 | from exercise_8_3 import * |
The expected output from running the above code is:
1 | '20 is not a Modulo object\n' |
My Solution
1 | # exercise_8_3.py |
Standard Solution
1 | class IntError(Exception): |
Summary
The differences between the two solutions are as follows:
Validation Method:
- The standard solution defines a
_validate
method to handle checks for the operands (Modulo
type and modulus equality), improving code reuse. - My solution performs these checks directly inside the
__add__
and__mul__
methods.
- The standard solution defines a
In-Place Operations:
The standard solution includes in-place addition (
__iadd__
) and multiplication (__imul__
) methods, which modify the current object directly.My solution does not include these in-place methods, focusing only on returning new
Modulo
objects.
Exercise 4
Problem Description
In this exercise, we need to create an iterable class Prime that generates prime numbers in a sequence. Each instance of Prime should be able to independently generate the sequence of prime numbers.
The following Python script is used to test the functionality:
1 | from exercise_8_4 import * |
The expected output from running the above code is:
1 | '2, 3, 5, 7, 11, 13, 17, 19, 23, 29\n' |
My Solution
1 | class Prime: |
Standard Solution
1 | class Prime: |
Exercise 5
Shoelace Formula
The shoelace formula, also known as Gauss’s area formula or the surveyor’s formula, is a mathematical method used to calculate the area of a polygon when given the coordinates of its vertices. This method is especially useful for polygons whose vertices are defined on a Cartesian coordinate system. It is called the “shoelace formula” because of the crisscross pattern formed when calculating the terms.
$ A = \frac{1}{2} \left| \sum_{i=1}^{n} (x_i y_{i+1} - y_i x_{i+1}) \right|$
Example Calculation
Consider a triangle with vertices $(x_1, y_1)=(2,4)$, $(x_2, y_2)=(5,11)$ and $(x_3, y_3)=(12, 8)$:
Write the coordinates as:
$(2, 4), (5, 11), (12, 8), (2, 4)$
Multiply diagonally from left to right:
$2 \times 11 + 5 \times 8 + 12 \times 4 = 22 + 40 + 48 = 110$
Multiply diagonally from right to left:
$4 \times 5 + 11 \times 12 + 8 \times 2 = 20 + 132 + 16 = 168$
Subtract and divide by
2
:$A = \frac{1}{2} \left| 110 - 168 \right| = \frac{1}{2} \times 58 = 29$
Thus, the area of the triangle is
29
.
Problem Description
In this exercise, we need to create a set of classes representing different shapes: Polygon
, Rectangle
, and Square
. Each shape has specific properties and a method to calculate the area. The classes should also provide informative messages when initialized or when calculating the area.
The following Python script is used to test the functionality:
1 | from exercise_8_5 import * |
The expected output from running the above code is:
1 | 'Testing a polygon\n' |
My Solution
1 | # exercise_8_5.py |
Standard Solution
1 | class Polygon: |
Exercise 6
Problem Description
In this exercise, we need to implement a class named CircularTuple
that represents an immutable sequence of elements. The class should:
Allow circular indexing, meaning any index (positive or negative) will be wrapped around the length of the tuple using modulo arithmetic.
Be immutable, which means any attempt to modify an element should raise an appropriate error.
The following Python script is used to test the functionality:
1 | from exercise_8_6 import * |
The expected output from running the above code is:
1 | '4\n' |
My Solution
1 |
|
Standard Solution
1 | from collections.abc import Sequence |
Summary
Exception Handling:
In my solution,
CircularTupleError
includes a default error message to provide more descriptive information when an assignment is attempted.The standard solution defines
CircularTupleError
as a simple exception without additional customization.
Both solutions implement circular indexing using modulo arithmetic (index % len(self)), which allows for indexing beyond the bounds of the tuple, wrapping around as needed.