Starting from:

$24.99

CMPSC 442: Homework 1 [94 points] Solution



TO PREPARE AND SUBMIT HOMEWORK CODE
Follow these steps exactly, so the Gradescope autgrader can grade your homework. Failure to do so will result in a zero grade:
1. You *must* download the homework template file homework1_cmpsc442.py from Canvas. Each template file is a python file that gives you a headstart in creating your homework python script with the correct function names for autograding.
2. You *must* rename the file by replacing cmpsc442 with your PSU id from your official PSU. For example, if your PSU email id is abcd1234, you would rename your file as homework1_abcd1234.py to submit to Canvas, and to Gradescope.
4. Make sure your file can import before you submit; the autograder imports your file. If it won't import, you will get a zero.
Instructions
The template file homework1-cmpsc442.py contains empty definitions for functions you must complete. Do not modify the names or function signatures in this file, or the autograder will not work and your homework will not be graded. However, you are free to introduce additional variables or functions if needed.
In addition to a problem specification, each programming question also includes a pair of examples from the Python interpreter. These are meant to illustrate typical use cases to clarify the assignment, and are not comprehensive test suites!!!! Your own creation of appropriate test suites is part of verifying your code.
You are strongly encouraged to follow the Python style guidelines set forth in PEP 8, which was written in part by the creator of Python.
1. Working with Lists (15 points) [15 points]
1. [5 points] [5 points] Consider the function extract_and_apply(l, p, f) shown below, which extracts the elements of a list l satisfying a boolean predicate p, applies a function f to each such element, and returns the result.

Rewrite extract_and_apply(l, p, f) in one line using a list comprehension.
2. [5 points] [5 points] Write a function concatenate(seqs) that returns a list containing the concatenation of the elements of the input sequences. Your implementation should consist of a single list comprehension, and should not exceed one line.
>>> concatenate([[1, 2], [3, 4]]) >>> concatenate(["abc", (0, [0])])
[1, 2, 3, 4] ['a', 'b', 'c', 0, [0]]
3. [5 points] [5 points] Write a function transpose(matrix) that returns the transpose of the input matrix, which is represented as a list of lists. Recall that the transpose of a matrix is obtained by swapping its rows with its columns. More concretely, the equality
matrix[i][j] == transpose(matrix)[j][i] should hold for all valid indices i and j. You
>>> transpose([[1, 2, 3]]) >>> transpose([[1, 2], [3, 4], [5, 6]])
[[1], [2], [3]] [[1, 3, 5], [2, 4, 6]]
2. Sequence Slicing (6 points) [6 points]
1. [2 points] [2 points] Write a function copy(seq) that returns a new sequence containing the same elements as the input sequence.

2. [2 points] [2 points] Write a function all_but_last(seq) that returns a new sequence containing all but the last element of the input sequence. If the input sequence is empty, a new empty sequence of the same type should be returned.

3. [2 points] [2 points] Write a function every_other(seq) that returns a new sequence containing every other element of the input sequence, starting with the first. Hint: This function can be written in one line using the optional third parameter of the slice notation.

3. Combinatorial Algorithms (11 points) [11 points]
Although generators in Python can be used in a variety of ways, you will not need to use any of their more sophisticated features here. Simply keep in mind that where you might normally return a list of elements, you should instead yield the individual elements.
Since the contents of a generator cannot be viewed without employing some form of iteration, we wrap all function calls in this section's examples with the list function for convenience.
1. [6 points] [6 points] The prefixes of a sequence include the empty sequence, the first element, the first two elements, etc., up to and including the full sequence itself. Similarly, the suffixes of a sequence include the empty sequence, the last element, the last two elements, etc., up to and including the full sequence itself. Write a pair of functions prefixes(seq) and suffixes(seq) that yield all prefixes and suffixes of the input sequence.
>>> list(prefixes([1, 2, 3])) >>> list(prefixes("abc"))
[[], [1], [1, 2], [1, 2, 3]] ['', 'a', 'ab', 'abc']
>>> list(suffixes([1, 2, 3])) >>> list(suffixes("abc"))
[[1, 2, 3], [2, 3], [3], []] ['abc', 'bc', 'c', '']
2. [5 points] [5 points] Write a function slices(seq) that yields all non-empty slices of the input sequence.
>>> list(slices([1, 2, 3])) >>> list(slices("abc"))
[[1], [1, 2], [1, 2, 3], [2], [2, 3], ['a', 'ab', 'abc', 'b', 'bc', 'c'] [3]]
4. Text Processing (20 points) [20 points]
1. [5 points] [5 points] A common preprocessing step in many natural language processing tasks is text normalization, wherein words are converted to lowercase, extraneous whitespace is removed, etc. Write a function normalize(text) that returns a normalized version of the input string, in which all words have been converted to lowercase and are separated by a single space. No leading or trailing whitespace should be present in the output.
>>> normalize("This is an example.") >>> normalize(" EXTRA SPACE ")
'this is an example.' 'extra space'
2. [5 points] [5 points] Write a function no_vowels(text) that removes all vowels from the input string and returns the result. For the purposes of this problem, the letter 'y' is not considered to be a vowel.
>>> no_vowels("This Is An Example.") >>> no_vowels("We love Python!")
'Ths s n xmpl.' 'W lv Pythn!'
3. [5 points] [5 points] Write a function digits_to_words(text) that extracts all digits from the input string, spells them out as lowercase English words, and returns a new string in which they are each separated by a single space. If the input string contains no digits, then an empty string should be returned.
>>> digits_to_words("Zip Code: 19104") >>> digits_to_words("Pi is 3.1415...")
'one nine one zero four' 'three one four one five'
4. [5 points] [5 points] Although there exist many naming conventions in computer programming, two of them are particularly widespread. In the first, words in a variable name are separated using underscores. In the second, words in a variable name are written in mixed case, and are strung together without a delimiter. By mixed case, we mean that the first word is written in lowercase, and that subsequent words have a capital first letter. Write a function to_mixed_case(name) that converts a variable name from the former convention to the
latter. Leading and trailing underscores should be ignored. If the variable name consists solely of underscores, then an empty string should be returned.
>>> to_mixed_case("to_mixed_case") >>> to_mixed_case("__EXAMPLE__NAME__")
'toMixedCase' 'exampleName'
5. Polynomials (37 points) [37 points]
In this section, you will implement a simple Polynomial class supporting basic arithmetic, simplification, evaluation, and pretty-printing. An example demonstrating these capabilities is shown below.

1. [2 points] [2 points] In this problem, we will think of a polynomial as an immutable object, represented internally as a tuple of coefficient-power pairs. For instance, the polynomial 2x + 1 would be represented internally by the tuple ((2, 1), (1, 0)). Write an initialization method __init__(self, polynomial) that converts the input sequence polynomial of coefficient-power pairs into a tuple and saves it for future use. Also write a corresponding method get_polynomial(self) that returns this internal representation.
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial(((2, 1), (1, 0)))
>>> p.get_polynomial() >>> p.get_polynomial()
((2, 1), (1, 0)) ((2, 1), (1, 0))
2. [4 points] [4 points] Write a __neg__(self) method that returns a new polynomial equal to the negation of self. This method will be used by Python for unary negation.
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial([(2, 1), (1, 0)])
>>> q = -p; q.get_polynomial() >>> q = -(-p); q.get_polynomial()
((-2, 1), (-1, 0)) ((2, 1), (1, 0))
3. [3 points] [3 points] Write an __add__(self, other) method that returns a new polynomial equal to the sum of self and other. This method will be used by Python for addition. No simplification should be performed on the result.
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial([(2, 1), (1, 0)])
>>> q = p + p; q.get_polynomial() >>> q = Polynomial([(4, 3), (3, 2)]) ((2, 1), (1, 0), (2, 1), (1, 0)) >>> r = p + q; r.get_polynomial()
((2, 1), (1, 0), (4, 3), (3, 2))
4. [3 points] [3 points] Write a __sub__(self, other) method that returns a new polynomial equal to the difference between self and other. This method will be used by Python for subtraction. No simplification should be performed on the result.
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial([(2, 1), (1, 0)])
>>> q = p - p; q.get_polynomial() >>> q = Polynomial([(4, 3), (3, 2)]) ((2, 1), (1, 0), (-2, 1), (-1, 0)) >>> r = p - q; r.get_polynomial()
((2, 1), (1, 0), (-4, 3), (-3, 2))
5. [5 points] [5 points] Write a __mul__(self, other) method that returns a new polynomial equal to the product of self and other. This method will be used by Python for multiplication. No simplification should be performed on the result. Your result does not need to match the examples below exactly, as long as the same terms are present in some order.
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial([(2, 1), (1, 0)])
>>> q = p * p; q.get_polynomial() >>> q = Polynomial([(4, 3), (3, 2)]) ((4, 2), (2, 1), (2, 1), (1, 0)) >>> r = p * q; r.get_polynomial()
((8, 4), (6, 3), (4, 3), (3, 2))
6. [3 points] [3 points] Write a __call__(self, x) method that returns the result of evaluating the current polynomial at the point x. This method will be used by Python when a polynomial is called as a function. Hint: This method can be written in one line using Python's exponentiation operator, **, and the built-in sum function.
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial([(2, 1), (1, 0)])
>>> [p(x) for x in range(5)] >>> q = -(p * p) + p
[1, 3, 5, 7, 9] >>> [q(x) for x in range(5)]
[0, -6, -20, -42, -72]
7. [8 points] [8 points] Write a simplify(self) method that replaces the polynomial's internal representation with an equivalent, simplified representation. Unlike the previous methods, simplify(self) does not return a new polynomial, but rather acts in place. However, because the fundamental character of the polynomial is not changing, we do not consider this to violate the notion that polynomials are immutable.
The simplification process should begin by combining terms with a common power. Then, terms with a coefficient of zero should be removed, and the remaining terms should be sorted in decreasing order based on their power. In the event that all terms have a coefficient of zero after the first step, the polynomial should be simplified to the single term 0 · x0, i.e. (0, 0).
>>> p = Polynomial([(2, 1), (1, 0)]) >>> p = Polynomial([(2, 1), (1, 0)])
>>> q = -p + (p * p); q.get_polynomial() >>> q = p - p; q.get_polynomial()
((-2, 1), (-1, 0), (4, 2), (2, 1), ((2, 1), (1, 0), (-2, 1), (-1, 0)) (2, 1), (1, 0)) >>> q.simplify(); q.get_polynomial()
>>> q.simplify(); q.get_polynomial() ((0, 0),) ((4, 2), (2, 1))
8. [9 points] [9 points] Write a __str__(self) method that returns a human-readable string representing the polynomial. This method will be used by Python when the str function is called on a polynomial, or when a polynomial is printed.
In general, your function should render polynomials as a sequence of signs and terms each separated by a single space, i.e. "sign1 term1 sign2 term2 ... signN termN", where signs can be "+" or "-", and terms have the form "ax^b" for coefficient a and power b. However, in adherence with conventional mathematical notation, there are a few exceptional cases that require special treatment:
The first sign should not be separated from the first term by a space, and should be left blank if the first term has a positive coefficient.
The variable and power portions of a term should be omitted if the power is 0, leaving only the coefficient.
The power portion of a term should be omitted if the power is 1.
Coefficients with magnitude 0 should always have a positive sign.
Coefficients with magnitude 1 should be omitted, unless the power is 0.

powers.
>>> p = Polynomial([(1, 1), (1, 0)])
>>> qs = (p, p + p, -p, -p - p, p * p) >>> p = Polynomial([(0, 1), (2, 3)])
>>> str(p); str(p * p); str(-p * p) >>> for q in qs: q.simplify(); str(q)
...
'x + 1'
'2x + 2'
'-x - 1'
'-2x - 2'
'x^2 + 2x + 1'
'0x + 2x^3'
'0x^2 + 0x^4 + 0x^4 + 4x^6'
'0x^2 + 0x^4 + 0x^4 - 4x^6'
>>> q = Polynomial([(1, 1), (2, 3)])
>>> str(q); str(q * q); str(-q * q)
'x + 2x^3'
'x^2 + 2x^4 + 2x^4 + 4x^6'

'-x^2 - 2x^4 - 2x^4 - 4x^6'
6. Feedback (5 points) [5 points]
1. [1 point] [1 point] Approximately how long did you spend on this assignment? For your answer, enter the total time in hours as a decimal number (e.g., 1.0, 6.5, 14.75). Again, the measurement unit is *hours*.
2. [2 points] [2 points] Which aspects of this assignment did you find most challenging? Were there any significant stumbling blocks?
3. [2 points] [2 points] Which aspects of this assignment did you like? Is there anything you would have changed?

More products