Saint Louis University |
Computer Science 1300/5001
|
Computer Science Department |
All of these problems are for practice. You are freely encouraged to work together and you do not need to submit any of this work for a grade.
Python's abs(x) function accepts a single argument that can be an integer or floating-point number. Given the beginning of a hypothetical implementation of such a function that validates the parameter.
Spoiler: my code
The random module includes a function
Spoiler: my code
Python's fractions module provides a function
We will not concern ourselves with the algorithm for computing that gcd (typically Euclid's algorithm), nor will we concern ourselves with how gcd's are defined when negative values are given. Instead, assume we were to author our own version of such a function and insist that both parameters be nonnegative integers. Give the beginning of the function body that validates those parameters.
Spoiler: my code
Python's int constructor can also be used to
compute the integer value associated with a string in a
non-decimal base. For example, in base 8 (i.e., octal) the string
'132' represents the decimal value 90, as it
represents
$1 \cdot 8^2 + 3 \cdot 8^1 + 2 \cdot 8^0 = 64 + 24 + 2$. You can determine
this in Python by sending the base as a second optional
parameter to the constructor, as in
We will not concern ourselves with the logic of doing such a base conversion (though it is an interesting exercise). Instead, we look at the task of rigorously error checking the parameters to determine if they are legitimate. Instead of using the int constructor, assume we want to design a function with signature
def toDecimal(value, base):such that base is an integer between 2 and 10 (inclusive), and value is a nonemptystring that is composed entirely of valid digits for the given base. Your task is to write the beginning of such a function body to perform the appropriate error-checking.
Spoiler: my code
We have previously considered the implementation of a function
Spoiler: my code
For the previous problem, we considered tuples or lists as the way to describe a sequence, but functions such as Python's max will accept more general objects (such as sets, ranges, comprehension generators) that are not actually lists or tuples. For such a parameter to be valid, it must simply support the for-loop syntax.
Knowing that an attempt at a for-loop over a non-iterable object raises a TypeError, redo the previous problem to allow for this more general type of iterable parameter.
Spoiler: my code