COSC 1306 SET 4 REVIEW

Ace your homework & exams now with Quizwiz!

When using a with statement to open a file, the file is automatically closed when the statements in the block finish executing.

True

The plot() function of matplotlib.pyplot can accept as an argument

Two lists of x, y coordinates, e.g., plot([1, 2, 3], [4.0, 3.5, 4.2])

Only negative odd values from the list x

[(i) for i in x if ((i < 0) and (i % 2 == 1))]

Assume that the following code has been evaluated: nums = [1, 1, 2, 3, 5, 8, 13] 1)What is the result of nums[1:5]?

[1, 2, 3, 5]

Given the list nums = [[10, 20, 30], [98, 99]], what does nums[0] evaluate to?

[10, 20, 30]

What's the output of the list comprehension program in row 4 of the table above if my_list is [[5, 10], [1]]?

[15, 1]

3) What is the result of nums [3:-1]?

[3, 5, 8]

What's the output of the list comprehension program from row 3 in the table above if the user enters "4 6 100"?

[4, 6, 100]

What's the output of the list comprehension program in row 1 in the table above if my_list is [-5, -4, -3]?

[5, 6, 7]

2) What is the result of nums[5:10]?

[8, 13]

The absolute value of each element in x. Use the abs() function to find the absolute value of a number.

[abs(i) for i in x]

Only negative values from the list x

[i for i in x if i < 0]

Assign x to a bytes object containing three bytes with hexadecimal values 0x05, 0x15, and 0xf2. Use a bytes literal.

b'\x05\x15\xf2'

dotted curve

bo

Enable a legend located in the bottom right of a graph.

legend(loc="lower right")

Complete the program by echoing the second line of "readme.txt" my_file = open('readme.txt') lines = my_file.readlines() print( ___ ) # ...

lines[1]

Enable width of the plotted line to 3, and the color of the line to green. plt.plot(times, temperatures,

linewidth=3, color='g'

Set the plotted line's marker size to 10. plt.plot(times, temperatures,

markersize=10

The largest square root of any element in x. Use math.sqrt() to calculate the square root.

max([math.sqrt(i) for i in x])

Choose the answer that creates the shown array: [[ 5 10 15 ]]

np.array([5, 10, 15])

Use np.linspace() to create the sequence: [ 0.25 0.5 0.75 1.0 ]

np.linspace(0.25, 1.0, 4)

Choose the answer that creates the shown array: [[ 0. 0.] [0. 0.] [0. 0.]]

np.zeros((3, 2))

Create a nested list nums whose only element is the list [21, 22, 23].

nums = [[21, 22, 23]]

Open "myfile.txt" as read-only in binary mode. f =

open('myfile.txt', 'rb')

Complete the statement to open the file "readme.txt" for reading. my_file = _____

open('readme.txt')

What is the output of the following program? import os p = 'C:\\Programs\\Microsoft\\msword.exe' print(os.path.split(p))

('C:\\Programs\\Microsoft','msword.exe')

The function call plt.plot([5, 10, 15], [0.25, 0.34, 0.44]) plots an x,y coordinate at

(15, 0.44)

What is the output of the following program? temps = [65, 67, 72, 75] temps.append(77) print(temps[-1])

77

FIGURE1 and FIGURE2 both have a legend.

False

FIGURE1 has an x-axis label of "Seconds".

False

Given the following code: nums = [0, 25, 50, 75, 100] 1) The result of evaluating nums[0:5:2] is [25, 75].

False

The write() method immediately writes data to a file.

False

Twice the value of each element in the list variable x

[i*2 for i in x]

matplotlib is a package that _________ .

Enables creating visualizations of data using graphs and charts

The variable my_dict created with the following code contains two keys, 'Bob' and 'A+'. my_dict = dict(name='Bob', grade='A+')

False

matplotlib is installed by default with Python.

False

Assign x to a bytes object with a single byte whose hexadecimal value is 0x1a. Use a bytes literal. x =

b'\x1a'

3 dotted curves

k^

Sort the elements of x such that the greatest element is in position 0.

x.sort(reverse=True)

Annotate the data point at (100, 5), placing the text 'Peak current' at (115, 10).

xy=(100, 5), xytext=(115, 10)

Fill in the arguments to os.path.join to assign file_path as "subdir\\output.txt" (on Windows). file_path = os.path.join(_____)

'subdir', 'output.txt'

Data will be written to a new file. f = open('myfile.txt', ____ )

'w'

5) What value is returned by min(my_list)?

0

Count how many odd numbers (cnt_odd) there are. cnt_odd = for i in num: if i % 2 == 1: cnt_odd += 1

0

2) The result of evaluating nums[0: -1 :3] is [0, 75].

True

3) What value is returned by any(my_list)?

True

Dictionary entries can be modified in-place - a new dictionary does not need to be created every time an element is added, changed, or removed.

True

The flush() method (and perhaps os.fsync() as well) forces the output buffer to write to disk.

True

The statement f.write(10.0) always produces an error.

True

The output of print(sorted([-5, 5, 2])) is [2, -5, 5].

false

The output of the following is [13, 7, 5]: primes = [5, 13, 7] primes.sort() print(primes)

false

Use of a with statement is not recommended most of the time when opening files

false

What does the call os.path.isfile('C:\\Program Files\\') return?

false

all elements of a list must have the same type

false

dictionaries can contain up to three levels of nesting

false

the size of a list is determined when the list is created and can not change

false

the statement del my_list[2] produces a new list without the element in position 2

false

What is returned by os.path.join('sounds', 'cars', 'honk.mp3') on Mac OS X? Use quotes in the answer.

"sounds/cars/honk.mp3"

What is returned by os.path.join('sounds', 'cars', 'honk.mp3') on Windows? Use quotes in the answer.

"sounds\\cars\\honk.mp3"

Assume that variable my_bytes is b"\x00\x04\xff\x00". Complete the statement to assign my_num to the 4-byte integer obtained by unpacking my_bytes. Use the byte ordering given by ">" my_num = struct.unpack( )

'>I', my_bytes

Arrange the elements of x from lowest to highest, comparing the upper-case variant of each element in the list.

x.sort(key=str.upper)

Complete the statement to pack an integer variable "my_num" into a 2-byte sequence assigned to my_bytes. Use the byte ordering given by ">" my_bytes = struct.pack( )

'>h', my_num

plt.annotate()

'Q1 Sales', xy=(4,2), xytext=(4,3)

What is the value of sys.argv[1] given the following command-line input (include quotes in your answer): python prog.py 'Tricia Miller' 26

'Tricia Miller'

What is the value of sys.argv[1] given the following command-line input (include quotes in your answer): python prog.py Tricia Miller 26

'Tricia'

Data will be appended to the end of existing contents. f = open('myfile.txt', ___)

'a'

Existing contents will be read, and new data will be appended. f = open('myfile.txt', ____ )

'a+'

Open "data.txt" as read-only in binary mode. f = open('data.txt', ____)

'rb'

Given the list nums = [[10, 20, 30], [98, 99]], what does nums[0][0] evaluate to?

10

Consider the following program: nums = [10, 20, 30, 40, 50] for pos, value in enumerate(nums): tmp = value / 2 if (tmp % 2) == 0: nums[pos] = tmp 1) What's the final value of nums[1]?

10.0

2) What value is returned by max(my_list)?

15

plt.subplot() larger frequency

2, 1, 2

plt.subplot() smaller frequency

2, 2, 4

my_dict['burger'] = my_dict['sandwich'] val = my_dict.pop('sandwich') print(my_dict['burger'])

2.99

2) How many elements does scores contain? (The result of len(scores))

3

Determine the output of each code segment. If the code produces an error, type None. Assume that my_dict has the following entries: my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99) 1) my_dict.update(dict(soda=1.49, burger=3.69)) burger_price = my_dict.get('burger', 0) print(burger_price)

3.69

Assume that my_list is [0, 5, 10, 15]. 1) What value is returned by sum(my_list)?

30

Draw the string "Peak current" at coordinate (5, 10).

5, 10, 'Peak current'

Given the list nums = [[10, 20, 30], [98, 99]], what does nums[1][1] evaluate to?

99

4) What value is returned by all(my_list)?

False

set_right_ylabel() creates the right-side axis

False

What is the output of the following program? actors = ['Pitt', 'Damon'] actors.insert(1, 'Affleck') print(actors[0], actors[1], actors[2])

Pitt Affleck Damon

A 2nd y-axis is only useful if the x-axis values of all the data series in the plot are similar.

True

Count how many negative numbers (cnt_neg) there are. cnt_neg = 0 for i in num: if i < 0:

cnt_neg += 1

Complete the statement to create a csv module reader object to read myfile.csv. import csv with open('myfile.csv', 'r') as myfile: csv_reader =

csv.reader(myfile)

For a program run as "python scriptname data.txt", what is sys.argv[1]? Do not use quotes in the answer.

data.txt

Alter the list comprehension from row 2 in the table above to convert each number to a float instead of a string. my_list = [5, 20, 50] my_list = [ ____ for i in my_list] print(my_list)

flaot(i)

sharp lines

g-

Determine the number of elements in the list that are divisible by 10. (Hint: the number x is divisible by 10 if x % 10 is 0.) div_ten = 0 for i in num: if ( ): div_ten += 1

i % 10 == 0

Change all negative values in my_dict to 0. for key, value in ____: if value < 0: my_dict[key] = 0

my_dict.items()

Print each key in the dictionary my_dict. for key in _____: print(key)

my_dict.keys()

Print twice the value of every value in my_dict. for v in ___: print(2 * v)

my_dict.values()

Complete the statement to read up to 500 bytes from "readme.txt" into the contents variable. my_file = open('readme.txt') contents = ___ # ...

my_file.read(500)

Write a statement that counts the number of elements of my_list that have the value 15.

my_list.count(15)

Write the simplest two statements that first sort my_list, then remove the largest value element from the list, using list methods.

my_list.sort() my_list.pop()

A script "myscript.py" has two command line arguments, one for an input file and a second for an output file. Type a command to run the program with input file "infile.txt" and output file "out". > python

myscript.py infile.txt out

Complete the statement such that the program prints the destination of each flight in myfile.csv. import csv with open('myfile.csv', 'r') as myfile: csv_reader = csv.reader(myfile) for row in csv_reader: print( )

row[1]

Assume the following list has been created scores = [ [75, 100, 82, 76], [85, 98, 89, 99], [75, 82, 85, 5] ] 1) Write an indexing expression that gets the element from scores whose value is 100.

scores[0][1]

Alter the list comprehension from row 5 in the table above to calculate the sum of every number contained by my_list. my_list = [[5, 10, 15], [2, 3, 16], [100]] min_row = _____([sum(row) for row in my_list]) print(min_row)

sum

What does os.path.getsize(path_str) return?

the size in bytes of the file at path_str

a program can modify the elements of an existing list

true

a programmer can iterate over a copy of a list to safely make changes to that list.

true

iterating over a list and deleting elements from the original list might cause a logic program error.

true

nested dictionaries are a flexible way to organize data

true

the expression {'D1': {'D2': 'x'}} is valid.

true

the sort() method modifies a list in-place

true

the statement my_list1 + my_list2 produces a new list

true


Related study sets

5. Special Distributions, the Sample Mean, the Central Limit Theorem

View Set

Types of life insurance policies

View Set

Chapter 51: Concepts of Care for Patients With Noninflammatory Intestinal Disorders

View Set

Chapter 51: PrepU - Nursing Assessment: Integumentary Function

View Set