Homework 5 - Lists
Due Date: October 24, 2023
To solve the following problems, use only what we have learned so far. In particular, do not use any built-in functions that we have not covered yet. Assignments are due by 11:59 pm on the due date.
Problems
- What is the difference between a Python list and a tuple? Name at least four similarities between lists and tuples? What is at least one advantage of using tuples over lists?
In Python, define the following list:
>>> numbers = [8.8, 4.3, -2.1, 5.4]
In the Python console, type
numbers.
and then press the TAB key (note the period afternumbers
). You should see a list of methods that can be applied to the listnumbers
. What are all the methods? Then, choose three methods, describe what they do, and apply them to the listnumbers
. Hint: You may find the following site useful: List methods- Write a function that receives one argument which is a list of numbers and returns a list obtained by evaluating the function \(f(x) = 2\sin(2x) - 11\cos(3x)\) at each number in the input list. Thus, if the argument passed into your function is the list \(x = [x_0, x_1, x_2, x_3]\) then the list returned by your function is \([f(x_0), f(x_1), f(x_2), f(x_3)]\). Before you can use \(\cos\) and \(\sin\) you will need to import them from the
math
module:from math import sin, cos
ASCII stands for American Standard Code for Information Interchange. An ASCII code is the numerical representation of a character. To find the ASCII code for a character you can use Python's built-in function
ord()
. For example:>>> ord('a') 97 >>> ord('b') 98 >>> ord('z') 122 >>> ord(' ') 32
The built-in function
chr()
is the inverse of theord()
function:>>> chr(97) 'a' >>> chr(98) 'b' >>> chr(122) 'z' >>> chr(32) ' '
The printable ASCII characters have numerical values in the range 32 to 126. Write a function called
code_convert()
that receives one parameter which is a list containing positive integers in the range from 32 to 126 and returns the equivalent string encoded in the input list. For example:>>> code_convert([104, 101, 108, 108, 111]) 'hello' >>> code_convert([99, 111, 100, 105, 110, 103, 32, 114, 111, 99, 107, 115, 33]) 'coding rocks!'
If any of the values of the input list is outside the range from 32 to 126, your function should immediately print an error message and return the value of
None
. To test your function, apply it to the list:[108, 101, 97, 114, 110, 32, 116, 111, 32, 99, 111, 100, 101]
Google the phrase "list comprehensions in Python". Then, using a list comprehension, with one line of code create the list
Hint: If \(k\) is an odd integer then \((-1)^k = -1\) and if \(k\) is an even integer then \((-1)^k = 1\).[-1, 4, -9, 16, -25, 36, -49, 64, -81, 100]