DS 202 Midterm #1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Why is this wrong? 'I have eaten ' + 99 + 'burritos'

'I have eaten ' + '99' + 'burritos'

What happens if you try to access spam['foo'] if spam is {'bar': 100}?

A keyerror error

The string value "Howl's Moving Castle" is a valid string. Why isn't it a problem that the single quote character in the word Howl's isn't escaped?

It is okay because double quoted are beginning and ending the expressoin

Let's say spam contains the list ['a', 'b', 'c', 'd']. What does spam[int(int('3' * 2) // 11)] evaluate to? What does spam[-1] evaluate to? What does spam[:2] evaluate to?

'd' because string 3, multiplied, is string '33' and 33/11 = 3. [3] = d 'd' because negative index count from the end. ['a','b'], first 2 elements in a list

Given a list of numbers contained in a list: lst = [1, 345, 2, 3, 1, 345, ... 592, 2]Print out a report of what numbers appear in the list and how frequently they occur.

from collections import Counter z = ['1', '2', '1', '3', '2', '1'] Counter(z) Out: Counter({'1': 3, '2': 2, '3': 1})

Write a loop that produces the following pattern with n rows: X XX XXX XXXX

for i in range (1,5): val = "" for j in range (1, i+1) val = val +x print(val)

Write a loop that displays the following numbers: 20, 22, 24, 26, ..., 58, 60

for i in range (20,62): if (i % 2 == 0): print(i)

Consider the following dictionary: dict = {"Tina":[1,2,3], "Fred":[4,5,6], "Bob":[7,8,9]} Write out the Python code to print out the first entry in each of the user's lists

for key in dict print(dict[key][0]

What is the difference between break and continue

A break stops the loop where the statement is placed and a continue statement skips a single iteration in a loop

given two dictionaries dict1 and dict2 write code to create a merged dictionary d3.

def Merge(dict1, dict2): return(dict2.update(dict1)) dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} (Merge(dict1, dict2)) print(dict2) out: {'d': 6, 'c': 4, 'a': 10, 'b': 8}

What is printed by the following Python code? for i in range(1,6): val = "" for j in range(1,i+1): val = val + "*" print(val)

* ** *** **** *****

Let's say bacon contains the list [3.14, 'cat', 11, 'cat', True]. What does bacon.index('cat') evaluate to? What does bacon.append(99) make the list value in bacon look like? What does bacon.remove('cat') make the list value in bacon look like?

1, 'cat' is element [1] in a list [3.14, 'cat', 11, 'cat', True, 99] (it adds 99 to the end) [3.14, 11, 'cat', True]

What is printed by the following Python code? print(3/2) print(3//2) print((3/2) > (3%2))

1.5 1 True

What is the main difference between a dictionary and a list?

A dictionary is accessed by a key and a list is by position

Write code that prints hello if 1 is stored in spam, prints howdy if 2 is stored in spam and prints greetings if anything else is stored in spam

spam = 1 if (spam == 1): print ("Hello") elif (spam ==2): print("Howdy") else: print( "greetings")

What do the following two expressions evaluate to 'spam' + 'spamspam' 'spam' * 3

spamspamspam

What do the following expressions evaluate to? 'Hello world!'[1] 'Hello world!'[0:5] 'Hello world!'[:5] 'Hello world!'[3:]

'e' 'Hello' 'Hello' 'lo world!'

What happens to variables in a local scope when the function call returns?

They are destroyed. A local variables life ends when the function has run to completion

given two dictionaries dict1 and dict2 write code to create a merged dictionary d3. (For example if you have the inputs dict1={1:10, 2:20}, dict2={3:30, 4:40} the result should be dict3 = {1: 10, 2: 20, 3: 30, 4: 40})

def Merge(dict1, dict2): return(dict2.update(dict1)) dict1 = {'1:10, 2:20'} dict2 = {'3:30, 4:40'} (Merge(dict1, dict2)) print(dict2) out: {'3:30, 4:40', '1:10, 2:20'}

Write a loop that finds the smallest value of n such that n2 is greater than 1200.

n = 0; while ((n*n) < 1200): ++n print (n + " is the lowest number, such that n^2 is greater than 12,000");

Write a function that returns true if a list of items (of same type) is in sorted order and false if not.

test_list = [1, 4, 5, 8, 10] flag = 0 i = 1 while i < len(test_list): if(test_list[i] < test_list[i - 1]): flag = 1 i += 1 if (not flag) : print ("Yes, List is sorted.") else : print ("No, List is not sorted.")

Write a boolean expression to check whether x and y are both positive or they are both negative

x = 2 y= -3 if x and y > 0: print("Both numbers are positive") elif x and y ==0: print("Zero") else: print("Negative numbers present")

What is the difference between range(10), range(0, 10), and range(0, 10, 1) in a for loop?

There is no difference

Why is eggs a valid variable name while 100 is invalid?

Though you can use numbers in a variable name, it must start w/ a letter or underscore

What do the expressions evaluate too? (5>4) and (3==5) not (5>4) (5>4) or (3==5) not ((5>4) or (3==5) (True and True) and (True == False) (not False) or (not True)

False False True False False True

Write code to create a Python list containing multiples of 3 from 9 up to (and including) 27.

a = [i for i in range (3,30) if i % 3 ==0] print a

What is printed by the following Python code? b = [i for i in range(3,10)] print(b) c = [x**2 for x in b] print(c) d = [y for y in c if y < 25] print(d)

[3,4,5,6,7,8,9] [9,16,25,36,49,64,81] [9,16]

Why does the following code generate the error message "NameError: name 'total' is not defined"? def f1(n): total = 0 for i in range(n): total = total + i return total f1(5) print(total)

Because 'total' is a local variable defined under f1, it needs to be declared globally to work

What is the difference between copy.copy() and copy.deepcopy()?

Copy will only do a shallow copy and deep copy will duplicate any lists inside of the list

Either indicate what is printed by the following code, or explain why an error occurred. one = [3, 4, 5, 6] one[1] = -1 print(one)

[3,-1,5,6]

What is the difference between lists and tuples? mutable / immutable

Lists are mutable (add, remove, change) and tuples are not

What do the \n and \t escape characters represent?

Newline new tab

If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in spam.values()?

No difference, operator checks if the value exists as a key in the dictionary value

Find three mistakes in the following method: def String test-function2(x): strVal = 'xyz' + 'abc' print(strVal) return strVal

No spaces are allowed in function names no dashes are allowed in function names should be calling strVal and not x

How many global scopes are there in a Python program? How many local scopes?

One global scope, as many local scopes as one includes in a function

What are two ways to remove values from a list?

The del statement and the remove() list method are two ways to remove values from a list.

Either indicate what is printed by the following code, or explain why an error occurred. one = (3, 4, 5, 6) one[1] = -4 print(one)

Tuples are NOT mutable

How can you put a backlash character in a string

Use the syntax "\\'

What is printed by the following Python code? a = "Discovering Computer Science " a = a * 2 a = a.split() print(a)

['Discovering','Computer','ScienceDiscovering','Computer', 'Science']

What does the following expression evaluate to?'Remember, remember, the fifth of November.'.split()

['Remember', 'remember', 'the', 'fifth', 'of', 'November.']

What is printed by the following Python code? animals = ["dog", "cat", "monkey", "donkey"] y = [x[0] for x in animals] print(y)

['d','c','m','d']

Either indicate what is printed by the following code, or explain why an error occurred. one = [3, 4, 5, 6] two = one one[2] = 300 print(one) print(two)

[3,4,300,6] [3,4,300,6]

What is the difference between the append() and insert() list methods?

append() only adds values to the end while insert() can add anywhere

Write a short program that prints the numbers 1 to 10 using a for loop. Then write an equivalent program that prints the numbers 1 to 10 using a while loop.

for i in range (1,11): print(i) i = 1 while(i<=10): print(i) i += 1

Given a dictionary of the form dict = {"one":[1,2,3], "two":[4,5,6], "four":[7,8,9]} (possibly with additional entries), write Python code to print out the second entry in each of the lists.

for key in dict print(dict[key][1]

Write a function to roll a pair of dice until you get a desired sum and return the number of rolls that was required

import random summed = 0 rolls=0 while summed < 12: summed = random.randint(1,6) + random.randint(1,6) rolls += 1 print("You arrived at the desired sum after" , rolls , "rolls.")

What does the code for an empty dictionary look like?

items = {} items = dict()


Set pelajaran terkait

Network+ Chapter 10 Network Operations

View Set

chapter 30 : lesson 2 : world war two

View Set

International Management Exam #3 (Chapters 8, 9, & 10)

View Set

Organizational Behavior Chapter 8 Smartbook stuff

View Set