Finals Review

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What will the screen output be after this instruction executes? re_pattern('Michael is in Los Angeles with his family', '[A-Z][a-z]+')

'Michael is in Los Angeles with his family' 'Michael' ..............'Los' ..................'Angeles' There are 14 dots for each letter and space before Los starting from Micheal and 18 before Angeles with Los and it's spaces included within it The regular expression '[A-Z][a-z]+' will match with any term starting with an uppercase letter followed by a string of lowercase letters (of non-zero, arbitrary length due to the + special character). Hence, any capitalized substring will result in a match for this pattern. The for loop formats each occurrence so that the resulting match aligns with the input text string.

What will the screen output be after the following instruction executes? re_pattern('cdcddccddddc', 'cd{2,3}')

'cdcddccddddc' ..'cdd' ......'cddd' The regular expression 'cd{2,3}' will match with any term starting with 'c' followed by either 2 or 3 occurrences of 'd' (due to { }, which specifies the number of occurrences). Therefore, all occurrences of either 'cdd' or 'cddd' will result in a match. The for loop formats each occurrence so that the resulting match aligns with the input text string.

What will the screen output be after this instruction executes? re_pattern('cddccdddc', 'cd?')

'cddccdddc' 'cd' ...'c' ....'cd' ........'c' The regular expression 'cd?' will match with any term starting with 'c' followed by either 0 or 1 occurrences of 'd' (due to the ? special character). Therefore, all occurrences of either 'c' followed by 0 'd's or 'cd' will be output. The for loop formats each occurrence so that the resulting match aligns with the input text string. We count every cd and c and the spaces until it starts which are represented by the dots.

Repetition

* Concatenate a repeated number of times

Concatenation

+ Combine sequences together

What screen output will be generated after the following instructions execute? def funcd(d, v): for key in d: if d[key] == v: return key return [ ] dexamp={'v':1, 'w':2, 'x':3, 'y':4, 'z':5} val=2 rval=funcd(dexamp, val) if len(rval)!=0: print(rval) else: print('Value', val, 'not found')

W

. [ ] ( ) + * ? ^ $ | \

. stands for a single arbitrary character [ ] are used to define classes of characters and match any character of that class ( ) are used to define groups consisting of multiple characters in a sequence + stands for arbitrarily many repetitions of the previous character or group but at least one occurrence * stands for arbitrarily many repetitions of the previous character or group including no occurrence ? stands for zero or one occurrence of the previous character or group, so basically says that the character or group is optional {m,n} stands for at least m and at most n repetitions of the previous group where m and n are integer numbers ^ stands for the beginning of the string $ stands for the end of the string | stands between two characters or groups and matches either only the left or only the right character/group, so it is used to define alternatives \ is used in combination with the next character to define special classes of characters

The data type as a result of using the division operator / will be blank. The data type as a result of using the division operator // is an integer value which could be of blank.

/ float // float and int

Assume that a file data.txt contains the data: 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 After this code snippet runs, what screen output will be generated? f = open('data.txt') numbers=f.readline() numbers=numbers.rstrip('\n') print(numbers) numbers=f.readline() numbers=numbers.rstrip('\n') print(numbers) f.close()

0 1 2 3 4 1 2 3 4 0 The readline() method reads one line from a file and returns it as a string. Furthermore, the file pointer will be automatically incremented to the next line. Therefore, if two readline commands are executed consecutively, two consecutive lines will be read. This is the case for the code snippet in this exercise. When the file is opened for a read, the file pointer points directly at the first value in the first line. This results in the output: 0 1 2 3 4 and the file pointer has been incremented to the next line. The next readline instruction along with the print command will therefore lead to the output of the second line in the file: 1 2 3 4 0

Assuming the file str_data.txt contains the string data 'abbaabbba', what will the screen output be after this instruction executes? f = open('str_data.txt', 'r') for str_match in re.finditer('a((a+)|(b+))',f.read()): print(str_match.start(),str_match.end()) f.close()

0 3 3 5 This problem demonstrates how to iterate through string data contained within a file in order to search for a given regular expression pattern. If found, the start and end indices of the match within the string are printed out with the understanding that the Python index convention is one less than the end value. In this case, the pattern is 'a((a+)|(b+))' which means to search for a string starting with 'a' followed by a (non-empty) string of 'a's or a string starting with 'a' followed by a (non-empty) string of 'b's. Considering the input string 'abbaabbba', the first match to satisfy the pattern begins at index 0 and ends at index 2 ('abb'). The second match to satisfy the pattern begins at index 3 and ends at index 4 ('aa'). The 'abbb' occurrence would not be listed because it overlaps with the previous match. Every index that starts with a and ends with b. There are 2 instances where that happens and it's abb and aab

Assume that before this code snippet runs, the file data.txt contains: 0 1 2 3 4 After this code snippet runs, what screen output will be generated? f = open('data.txt') sval = 0 for line in f: sval += float(line) f.close() print(sval)

10 0+1+2+3+4=10

What would you predict the screen output to be after this Python code snippet executes? x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y=x [-1:-5:-1] z=X 1:31 for i in range(len (z)): print(y [il,z[il)

10 1 9 4 8 7 7 10

Mod %

10 mod 3 is 10%3 10/3=1 and 1/3 is 1R1 the numerator is the the remainder and the answer. But with negatives we have a problem -10 mod 3 -10/3=-1 and -1/3 -1R-1 THE REMAINDER MUST ALWAYS BE POSITIVE. So we take -1+mod =-1+3= 2

Predict the output generated by this snippet of code if it is executed using the middle Repl.it window: a=12 print (a) print (type(a)) b='good day' print (b) print(type (b))

12 <class'int'> good day <class'string'>

What would you predict the screen output to be after this Python code snippet executes? x=[ ] for i in range(3): x.append(i) x.extend(x) print(x)

1st interaction: i=0 append 0 [0] extend [0,0] 2nd interaction: i=1 append 1 [0, 0,1] extend [0, 0, 1, 0, 0,1] 3rd interaction: i=2 append 2 [0, 0, 1, 0, 0, 1,2] extend [0, 0, 1, 0, 0, 1, 2, 0, 0, 1, 0, 0, 1, 2]

Format of class types

<class 'int'>

Is each of the following statements about Python dictionaries true or false? A key and its value are separated by the % operator Answer 1 Each element in the dictionary can be accessed using a numerical index Answer 2 A set of key-value pairs can be assigned to a variable when they are contained between two curly brackets { } Answer 3 Dictionaries are mutable Answer 4 Dictionary keys are mutable Answer 5 Key-value pairs within a dictionary must be separated by a comma Answer 6

A key and its value are separated by the colon : operator. A value within a dictionary must be accessed using its associated key. Using { } is a syntactically correct method for creating dictionaries. Values within a dictionary are mutable meaning that they can be changed by referencing the key. Values within a dictionary are mutable, meaning that they can be changed by referencing the key; however, keys are not mutable, meaning they cannot be modified after a dictionary has been created. Key-value pairs within a dictionary must be separated by a comma; this syntax rule is similar to that for creating lists, sets, and tuples. A key and its value are separated by the % operator → False, Each element in the dictionary can be accessed using a numerical index → False, A set of key-value pairs can be assigned to a variable when they are contained between two curly brackets { } → True, Dictionaries are mutable → True, Dictionary keys are mutable → False, Key-value pairs within a dictionary must be separated by a comma → True

memo

A previously computed value that is stored for later use

mapping

A relationship in which each element of one set corresponds to an element of another set

a i m s x

ASCII a IGNORECASE i MULTILINE m DOTALL s VERBOSE x

Complete the __add__ method using a single return statement so the method returns a Circle instance whose radius attribute is the sum of the radius attributes associated with two objects from the class Circle. For instance, c1+c2 should result in a returned instance whose radius attribute is equal to 5 For the next two questions, use this class definition and the associated Python code. class Circle: def __init__(self, r): self.radius=r def circumference(self): return 2*math.pi*self.radius def area(self): return math.pi*pow(self.radius,2) def __str__(self): def __add__(self,other): c1=Circle(2) c2=Circle(3) print(c1) print(c2) print(c1+c2)

An expression involving two objects from the class Circle such as c1+c2 results in an overload of the + operator. Using the __add__ method, Circle addition can be well-defined. Once the association of the 'operands' self.radius+other.radius is made, it remains that a new instance of Circle with the new radius must be created. The only way to do this within a single return statement is to invoke the instantiation Circle(self.radius+other.radius). Doing so would allow a statement such as c3=c1+c2 to make sense. In this case, the object c3 from the class Circle would have a radius attribute equal to the sum of the radii from c1 and c2. return Circle(self.radius+other.radius)

Logical operators

And, ord, not, not equal to, etc.

Assume that, before running this code, temp.dat does not exist. What error will be raised after this code runs? f = open('temp.dat','w') f.readfile()

AttributeError

Assume that a file data.txt contains: 1 8 9.2 -5 1.4 9 8 0 12 -23 -9 1 1.6 2.3 -9.1 -42 -91 76 23 8 The goal of the code snippet f = open('data.txt') s = 0 for line in f: line = line.rstrip() numbers = line.split(' ') for item in numbers: s += item f.close() print(s) is to produce the sum of the values contained in data.txt using the variable s; however, there is an error in the code that will prevent this from happening. Which of the following describes the error? a. The open instruction must include an 'r' to read the data b. The variable item is a string and cannot be used to iterate in a for loop c. The variable item is a string and must be converted to a float value before executing the s+= instruction d. The instruction print(s) must take place before the f.close() instruction for s to be valid while the file is open

C

Which magic method should be defined within a class if you want to apply the print command to a class object? a. __add__ b. __float__ c. __init__ d. __str__

D

Assuming this script runs, what output message would be generated? try: z = 2.1/0 except ArithmeticError: print('Error: general arithmetic error') except ZeroDivisionError: print('Error: division by zero error')

Error: general arithmetic error generates a divide by zero error, which is a subclass of ArithmeticError. Since ArithmeticError is raised first within the code, it will be handled first. This question emphasizes the importance of understanding exception specificity as well as exception hierarchy with respect to the order that exceptions are handled in.

What screen output will be generated if these commands execute? r1=Rectangle(1,7) r2=Rectangle(2,3) print(r1<r2)

False Explaination: 1*7= 7 and 2*3=6 7 is not less than 6

What error will be raised by Python if the file temp.dat does not exist or is not accessible in the directory path at the time this open command executes? f = open('temp.dat') data = f.readfile() print('File read completed')

FileNotFoundError

The data type of division will always be blank. Integer division can be blank

Float & both

break, continue, pass

For break: When its greater it continues, when it's less than 4 is when the sequence stops. Because when they less than 4 it stops. 4 is not less than 4 so it's included. So it stops at 3. For continue: Does it normally, 0 can't be included For pass: performs normally, but once it gets to 4 is when it prints the statement

Relational operators

Greater than, less than, not equal to, etc.

This code is supposed to output the French word for the numbers 1 through 4. When a user enters a number contained in the dictionary, the program will output the appropriate French word. In the code given, complete the print instruction in the try clause that will cause the program to work as desired. eng2fr = {1: 'un', 2: 'deux', 3: 'trois', 4:'quatre'} numval = int(input('Input a number from 1 to 4, I will tell you your number in French: ')) try: print(f'The number {numval} in French is {fill in code here}.') except KeyError: print(f'{numval} is not in my dictionary')

In this code, numval is being used as the key into the dictionary to access a specific value. If an invalid key is entered, KeyError will be raised and an error message will be printed out. If a valid key is entered, then it can be used to refer to the appropriate value within the dictionary. Therefore, eng2fr[numval] would be allowable and also the definitive choice for referring to the correct value. The correct answer is: eng2fr[numval]

An object is an [blank] of a class

Instance

[ ]

List

The init [blank] defined within a class is invoked when an [blank] is instantiated.

Method and object

Assume that this list has been defined: z=[5,'j',9,'s','3'] Match each instruction with the appropriate error, assuming that each instruction is executed with no other variables except the list defined above z[2] + x*2

NameError, which happens when a variable is referred to that has not been defined

Programming task broken down into methods and attributes

Object-oriented

What would you predict the screen output to be after this Python code snippet executes? x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y=x[-1:-5:-1] z=x[::3] for i in range(len(z)): print(y[i],z[i])

Photos

Programming task broken down into variables, data structures, and subroutines

Procedural

Hash

Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary. Example 1: Demonstrating working of hash() Python3 # Python 3 code to demonstrate # working of hash() # initializing objects int_val = 4 str_val = 'GeeksforGeeks' flt_val = 24.56 # Printing the hash values. # Notice Integer value doesn't change # You'll have answer later in article. print("The integer hash value is : " + str(hash(int_val))) print("The string hash value is : " + str(hash(str_val))) print("The float hash value is : " + str(hash(flt_val))) Output: The integer hash value is : 4 The string hash value is : -5570917502994512005 The float hash value is : 1291272085159665688

The compile() function converts an expression string into a blank

RegexObject

Ceil

Round a number up to the nearest integer Syntax: ceil(x) rounds x up to the nearest integer. Example: math.ceil(-3.5) returns -3. log: Computes the natural logarithm (base e) of an input number. This method should not be confused with log10, which computes the base 10 logarithm. Syntax: If the variable x represents a number, log(x) computes the natural logarithm of x. Example: math.log(math.e) returns a value of 1 radians: Converts a number that represents an angle measured in degrees to the equivalent value in radians. Syntax: If the variable x represents an angle measured in degrees, radians(x)converts the value to radians. Example: math.radians(180) returns a value of 3.141592653589793 degrees: Converts a number that represents an angle measured in radians to the equivalent value in degrees. Syntax: If the variable x represents an angle measured in radians, degrees(x) converts the value to degrees. Example: math.degrees(math.pi) returns a value of 180.0 pow: Raises an input number to a power. Syntax: pow(x,y) raises an input number x to the power y. Example: math.pow(27,1/3) returns the cube root of 24 which 3.0

Code is broken down into smaller groups of instructions

Structural

No 'go to' statements

Structural

Match each regular expression predefined character class with its description. any decimal digit 0...9 Answer 1 any character that is not a digit Answer 2 any whitespace character such as space, tab, or the newline character Answer 3 any non-whitespace character Answer 4 any alphanumeric character Answer 5 any non-alphanumeric character Options are: \s, \d, \w, \W, \S, \D

The correct answer is: any decimal digit 0...9 → \d, any character that is not a digit → \D, any whitespace character such as space, tab, or the newline character → \s, any non-whitespace character → \S, any alphanumeric character → \w, any non-alphanumeric character → \W

Match the regular expression special character with its purpose. a single arbitrary character Answer 1 arbitrarily many repetitions of the previous character or group but at least one occurrence Answer 2 arbitrarily many repetitions of the previous character or group including no occurrence Answer 3 zero or one occurrence of the previous character or group Answer 4 the beginning of the string Answer 5 the end of the string Options are *^ + $* .

The correct answer is: a single arbitrary character → ., arbitrarily many repetitions of the previous character or group but at least one occurrence → +, arbitrarily many repetitions of the previous character or group including no occurrence → *, zero or one occurrence of the previous character or group → ?, the beginning of the string → ^, the end of the string → $

Which of the following strings would be considered a match when searching for the regular expression '.*\s[a-z]+'? a. 'Tom Michaels' Incorrect. '\s[a-z]+' requires a string with a whitespace followed by at least one lowercase letter. b. 'Dr. Paul Smith' c. 'John Harold Jones' d. 'William van Oranje'

The dot .* implies any number of arbitrary repetitions of any character. .*\s implies an arbitrary number of repetitions of any character followed by a white space character (like space, tab, or newline). Finally, [a-z]+ in the pattern '.*\s[a-z]+' implies an arbitrary number of occurrences (but at least one occurrence) of lower case letters following the whitespace. The only string containing this pattern in the choices given is 'William van Oranje'. It is of the utmost importance that the plus sign + in a regular expression not be confused with string concatenation. The + and * notations for regular expressions come from the theory of computation where the * operator implies that an answer can contain the possibility of the empty string (no occurrences), while the + operator implies at least one occurrence (thereby excluding the empty string).

Input

The input command returns data of type str. If numerical data is required from the user input, it must be converted to the desired data type. For example: x=float(input('enter x'))

The syntax of a user-defined function:

The keyword def informs Python that a function is being declared. • The name of the function must follow the def keyword • Input variables follow the function name and must be placed within parentheses () • If there are multiple input variables, they must be separated by a comma. • If there are no input variables, the parentheses () will be empty. • A colon : must directly follow the parentheses (). • Indentation rules, similar to conditional statements and loops, hold for all code contained within the function. • The return keyword is used for returning from the function. • Function output variables are provided directly following the return keyword • In the main code, the function name along with any input variables are used to call the user-defined function

Consider this code snippet: class Rectangle: def __init__(self, x, y): self.width=x self.height=y def area(self): return self.width*self.height r1=Rectangle(3,4) r2=Rectangle(2,5) print(r1.area(),r2.area()) The name of the class defined in this snippet is blank . The objects in this snippet are width and height . The data attributes in this snippet are blank . The methods in this snippet are blank. The screen output of this snippet will be blank .

The name of the class defined in this snippet is [Rectangle]. The objects in this snippet are [r1 and r2]. The data attributes in this snippet are [width and height]. The methods in this snippet are [init and area]. The screen output of this snippet will be [12 10]

Complete the __str__ method using a single return statement so that the print command will print out the radius attribute of an object in the form of a string. For instance, print(c1) should result in the screen output: 2 print(c2) should result in the screen output: 3 For the next two questions, use this class definition and the associated Python code. class Circle: def __init__(self, r): self.radius=r def circumference(self): return 2*math.pi*self.radius def area(self): return math.pi*pow(self.radius,2) def __str__(self): def __add__(self,other): c1=Circle(2) c2=Circle(3) print(c1) print(c2) print(c1+c2)

The print statement requires a string value. Therefore, the radius attribute (which is numerical) must be converted to a string using str. Furthermore, self refers to the instance under consideration at the time the instruction is executed. When print(c1) is invoked, __str__ operates on c1.radius and when print(c2) is invoked, __str__ operates on c2.radius return str(self.radius)

Raise

The raise statement causes an exception

syntax for invoking a list or a string method

The syntax for referring to a method uses the dot notation. For example: alist=[5,7,9,11] alist.append(30)

concatenate

To join two operands end-to-end

( )

Tuple

Assume that this list has been defined: z=[5,'j',9,'s','3'] Match each instruction with the appropriate error, assuming that each instruction is executed with no other variables except the list defined above. z[1] + 3

TypeError, which happens because z[1] (which is 'j') is a string and cannot be added to the integer numerical value of 3.

This snippet of code uses slicing to refer to various elements within the defined lists. Use the output of this snippet to explain the difference between the append method and extend method. x=[1, 2, 3, 4, 5, 6, 7, 8] y=x[::2] z=y.copy() y.append(x[1::2]) z.extend(x[1::2]) print(y) print(z)

Using append: [1, 3, 5, 7, [2, 4, 6, 8]] Using extend: [1, 3, 5, 7, 2, 4, 6, 8] append appends a single element to the end of a list extend appends a list with another list (as opposed to a single element) copy copies a list from source to a destination The goal of slicing is to extract multiple elements from a list by referencing a set of element indices using the : operator. While slicing syntax is very flexible, slicing requires (either implicitly or explicitly) three pieces of information: starting index, ending index, and the step size. The : operator is used to identify these three pieces of information. The instruction x[::2] slices out elements to create the list [x[0],x[2],x[4],x[6]] which consists of the elements [1, 3, 5, 7]. This list is then placed in the variables y and z. The instruction x[1::2] slices out elements to create the list [x[1],x[3],x[5],x[7]] which consists of the elements [2, 4, 6, 8]. The append method appends x[1::2] to the list y as a single element yielding the result that y contains the list [1, 3, 5, 7, [2, 4, 6, 8]] The extend method extends the list z using x[1::2] as a set of elements yielding the result that z contains the list [1, 3, 5, 7, 2, 4, 6, 8]

What screen output will be generated after these instructions execute? eng2fr = {'one': 'un', 'two': 'deux', 'three': 'trois', 'four':'quatre'} dx={'five':'cinq', 'six':'six','seven':'huit'} eng2fr.update(dx) eng2fr['seven']='sept' print(eng2fr)

{'one': 'un', 'two': 'deux', 'three': 'trois', 'four': 'quatre', 'five': 'cinq', 'six': 'six', 'seven': 'sept'}

What screen output will be generated after these instructions execute? def inv_dict(d): invd = dict() for key in d: val = d[key] if val not in invd: invd[val] = [key] else: invd[val].append(key) return invd hdict={'a': 1, 'b': 1, 'c': 3, 'd': 3, 'e': 1} vdict = inv_dict(hdict) print(vdict)

{1: ['a', 'b', 'e'], 3: ['c', 'd']} The function inv_dict interchanges the role of key and value within an input dictionary. A given value val in the input dictionary d will become a key in the dictionary invd. All keys associated with this value will be stored within a list and that list will become a value within the dictionary invd

Assume these variable assignments have taken place: a=[23.7, 45, 78, 'yesterday'] b='asdfasdf' c=(4,9,a,b,'zxcv') For each of the following, indicate whether or not it would generate a syntax error. c[0]=12 Answer 1 a[3]=24 Answer 2 b[5]='2' Answer 3 a[2]='3456' Answer 4 c[3]=4 Answer 5 Option: Will generate a syntax error or will not generate a syntax error

You have correctly selected 3. c[0]=12 will generate a syntax error. It is independent of replacing a numerical value with another numerical value. Tuples are immutable and their values cannot be modified. This rule is independent of the variable type of the element c[0]. a[3]=24 will not generate a syntax error. This is independent of replacing a string value with a numerical value. Lists are mutable, so any given element can be overwritten with another value (even if it is of a different data type). b[5]='2' will generate a syntax error. Strings are immutable. Once created, characters within a string cannot be modified. a[2]='3456' will not generate a syntax error. This is independent of replacing a numerical value with a string value. Lists are mutable, so any given element can be overwritten with another value (even if it is of a different data type). c[3]=4 will generate a syntax error. This is independent of replacing a string value with a numerical value. Tuples are immutable and their values cannot be modified. This rule is independent of the variable type of the element c[3]. It is important to understand the fundamental differences between lists, strings, and tuples. Each of these has elements that can be referenced using an index. Lists are mutable, while strings and tuples are immutable. Tuples are usually reserved for applications where one would not want a list of data to be (accidentally) modified during program execution.

Given the Python dictionary assignment eng2fr = {'one': 'un', 'two': 'deux', 'three': 'trois', 'four': 'quatre'} Indicate whether each of the following statements is true or false. for key in eng2fr: print(key) is valid syntax for printing out all the dictionary keys contained within eng2fr Answer 1 for key in eng2fr.keys(): print(key) is valid syntax for printing out all the dictionary keys contained within eng2fr Answer 2 print(eng2fr.key) is valid syntax for printing out all the dictionary keys contained within eng2fr Answer 3 print(eng2fr.keys()) is valid syntax for printing out all the dictionary keys contained within eng2fr

You have correctly selected 3. for key in eng2fr: print(key) is valid syntax for printing out all the dictionary keys contained within eng2fr True: The loop variable key indexes through all the keys in eng2fr. This syntax is correct. for key in eng2fr.keys(): print(key) is valid syntax for printing out all the dictionary keys contained within eng2fr True: keys() is a dictionary method that will return all the keys in a given dictionary. The loop variable key indexes through all the keys generated by the method call eng2fr.keys(). This syntax is correct. print(eng2fr.key) is valid syntax for printing out all the dictionary keys contained within eng2fr False: This syntax is not valid. The dot notation implies that a method named key is to be called; however, there is no dictionary method named key. Secondly, method calls require parentheses () as part of their syntax rules. print(eng2fr.keys()) is valid syntax for printing out all the dictionary keys contained within eng2fr True: This syntax is valid. keys() is a dictionary method that will return all the keys in a given dictionary. It should be noted that although the instructions for key in eng2fr: print(key) for key in eng2fr.keys(): print(key) print(eng2fr.keys()) will all print out the keys, they will not be output in the same manner. The output from either for key in eng2fr: print(key) for key in eng2fr.keys(): print(key) will look like one two three four because each key is printed out using a separate print statement within the for loop. On the other hand, for print(eng2fr.keys()) the output will look like dict_keys(['one', 'two', 'three', 'four']) To review, see Dictionaries and Loops. The correct answer is: for key in eng2fr: print(key) is valid syntax for printing out all the dictionary keys contained within eng2fr → True, for key in eng2fr.keys(): print(key) is valid syntax for printing out all the dictionary keys contained within eng2fr → True, print(eng2fr.key) is valid syntax for printing out all the dictionary keys contained within eng2fr → False, print(eng2fr.keys()) is valid syntax for printing out all the dictionary keys contained within eng2fr → True

In these two code snippets, assume the variable text_list contains a list of strings and the variable pattern contains a string to be searched for within the list. Snippet 1: for text_str in text_list: if re.match(pattern, text_str): print(text_str) Snippet 2: compiled_pattern = re.compile(pattern) for text_str in text_list: if compiled_pattern.match(text_str): print(text_str) Is each of the following statements true or false? Snippet 1 and snippet 2 will produce the same output Answer 1 In snippet 2, referring to the if compiled_pattern.match(text_str) statement, the match() method requires two input arguments: pattern and text_str Answer 2 Snippet 1 would be considered to be more efficient that snippet 2 because it does not invoke compiled_pattern = re.compile(pattern), and thus has fewer instructions to execute Answer 3 Explicitly compiling the pattern in snippet 2 will not allow for providing additional parameters

Your answer is partially correct. You have correctly selected 1. Snippet 1 and snippet 2 will produce the same output True: Both snippets will indicate which strings were found to match the pattern. In snippet 2, referring to the if compiled_pattern.match(text_str) statement, the match() method requires two input arguments: pattern and text_str False: The pattern is already compiled and can be used to match against text_str. Snippet 1 would be considered to be more efficient than snippet 2 because it does not invoke compiled_pattern = re.compile(pattern) and, thus, has fewer instructions to execute False: In snippet 2, inside the loop, the pattern is already in compiled form and ready for comparison using the match() method. Therefore, the step of compiling outside the loop makes snippet 2 more efficient since the compilation of the pattern occurs only once instead of occurring each time the loop iterates. Explicitly compiling the pattern in snippet 2 will not allow for providing additional parameters False: Additional parameters can be introduced as search options in the compile() method that could further qualify the search conditions. The two snippets given perform exactly the same function. The main question has to do with the processing efficiency of each approach. A method call from the re module will generally perform some type of preprocessing on the input strings. Such preprocessing can be minimized by using the compile() method. In snippet 1, inside the for loop, the pattern must be re-processed by the match() method each time the loop executes. In snippet 2, inside the loop, the pattern is already in compiled form and ready for comparison using the match() method. Snippet 2 is more efficient since the compilation of the pattern occurs only once instead of occurring each time the loop iterates. Additionally, since the pattern is compiled, compiled_pattern.match(text_str) does not require two input arguments. Finally, explicitly compiling the pattern allows for providing additional regular expression parameters (such as re.compile(pattern,re.IGNORECASE) when matching is required in a case-insensitive manner). To review, see Syntax and Usage and Delving Deeper. The correct answer is: Snippet 1 and snippet 2 will produce the same output → True, In snippet 2, referring to the if compiled_pattern.match(text_str) statement, the match() method requires two input arguments: pattern and text_str → False, Snippet 1 would be considered to be more efficient that snippet 2 because it does not invoke compiled_pattern = re.compile(pattern), and thus has fewer instructions to execute → False, Explicitly compiling the pattern in snippet 2 will not allow for providing additional parameters → False

Indexing

[ ] Access an element of a sequence

What would you predict the screen output to be after this Python code snippet executes? xvals=['there', 'everywhere', 'herehere', 'zero', 'nowhere'] y=[ ] for x in xvals: y.append(x.find('ere')) print(y)

[2, 7, 1, -1, 4]

\d \D \s \S \w \W

\d a digit \D a non-digit \s whitespace (tab, space, newline, etc.) \S non-whitespace \w alphanumeric \W non-alphanumeric

^ $ \A \Z \b \B

^ start of string, or line $ end of string, or line \A start of string \Z end of string \b empty string at the beginning or end of a word \B empty string not at the beginning or end of a word

a=True b=5 c=2.0 x=a+b//c y=b%c>=1 and a print(x) print(type(x)) print(y) print(type(y))

a + b//c ⇒ True + 5//2.0 ⇒ True + 2.0 ⇒ 1.0 + 2.0 ⇒ 3.0 will be the value assigned to the variable x which is of type float. b%c>=1 and a ⇒ 5%2.0>=1 and True ⇒ 1.0 >=1 and True ⇒ 1.0>=1.0 and True ⇒ True and True ⇒ True will be the value assigned to the variable y which is of type bool. Therefore the output will be 3.0 <class 'float'> True <class 'bool'>

flag

acts as a signal to the program to determine whether or not the program as a whole or a specific section of the program should run. In other words, you can set the flag to True and the program will run continuously until any type of event makes it False

An element that is assigned a value within a class definition is called a data [blank]

attribute

Given the Python code aset={2,3,5,7,11,13,17,19} bset={1,3,5,7,9,11,13,15,17,19} cset=set() for a in aset: for b in bset: if a==b: cset.add(a) Write a single Python instruction using a single set method that will compute the same result for the variable cset

cset=aset.intersection(bset) This code computes the intersection between the two sets aset and bset. The intersection of the two sets is defined as the set of elements that are common to both aset and bset. The nested loop cycles through all values in both sets in order to compare them. If a value common to both sets is found (that is, if a==b), then that value is added to cset. The key to this problem is relating the definition of the intersection to the code provided. Once you see that connection, then the only choice is the intersection method.

Consider these two snippets of code: Snippet 1: n = 5 fname = 'data1' output1 = open(fname + ".txt",'w') for i in range(1,n+1): output1.write(str(3*i+1)+' ') output1.close() Snippet 2: n = 5 fname = 'data2' output2 = open(fname + ".txt",'w') for i in range(1,n+1): output2.write(str(3*i+1)+' '+'\n') output2.close() What will be the data contained with the files data1.txt and data.txt

data1.txt will contain: 4 7 10 13 16 data2.txt will contain: 4 7 10 13 16 i: 1 2 3 4 5 3*i+1: 4 7 10 13 16

Given the width and height of a rectangle as inputs, complete the function named perim that will compute the perimeter of the rectangle def perim(width,height): #insert your code here

def perim(width,height): return 2*width+2*height

Complete the function named reorder that will take an input list and return a list that contains the even indexed elements followed by the odd-indexed elements. For example, if the input list is [10,11,12,13,14,15,16,17,18,19], the returned list should be [10,12,14,16,18,11,13,15,17,19] def reorder(inlist): #insert your code here

def reorder(inlist): return inlist[::2]+inlist[1::2]

Complete the function named revlist that will take an input list and return the list with its elements in reverse order. For instance, for the input list [1,2,3,4,5], revlist should return [5,4,3,2,1] revlist(inlist): #insert your code here

def revlist(inlist): return inlist[-1::-1]

Displays the error message

except

Consider this exception handler: try: # Code to try except RuntimeError: # RuntimeError handler except TypeError: # TypeError handler except NameError: # NameError handler How would you rephrase the except instructions so that all three exception conditions can be handled with one single except statement?

except (RuntimeError, TypeError, NameError):

What instruction would be appropriate to insert into the finally clause in this code to ensure it operates properly? filename = 'test.dat' try: f = open(filename) data = f.readfile() except FileNotFoundError: print('File not found, creating one') f = open(filename, 'w') except: print('An error other than FileNotFoundError occurred') finally:

f.close()

Executes independently of the try-except block results

finally

lambda

function is an anonymous function (i.e., defined without a name) that can take any number of arguments but, unlike normal functions, evaluates and returns only one expression.

Given a sphere with radius r r , the volume of the sphere can be expressed as: 43πr3 4 3 π r 3 and the surface area can be expressed as: 4πr2 4 π r 2 Construct a class named Sphere that will: Use the init method to initialize the radius upon object instantiation Contain a user-defined method named volume to compute the sphere volume Contain a user-defined method named surfarea to compute the sphere surface area You will need the math module to perform these calculations. import math class Sphere: def __init__(self, r): # place your code here

import math class Sphere: def __init__(self, r): self.radius=r def volume(self): return (4/3)*math.pi*pow(self.radius,3) def surfarea(self): return 4*math.pi*pow(self.radius,2)

Complete the function named circarea that, given an input radius, will compute the area of a circle. You must import the math module and use the value of pi in that module import math def circarea(r): #insert your code here

import math def circarea(r): return math.pi*r**2

The goal of the function shown below is to use the search method from the re module to determine if the input string contains an arbitrary number of (including possibly 0) consecutive occurrences of abcs followed by a single d (for example, gggabcabcabcdeeee). You should complete this function by filling in a regular expression to recognize this pattern. If the pattern is found, your function should return True; otherwise, it should return False. import re def findpattern(intext_str): #insert your code here regex = re.compile(pattern) if regex.search(intext_str)!=None: return True return False

import re def findpattern(intext_str): pattern = '(abc)*d' regex = re.compile(pattern) if regex.search(intext_str)!=None: return True return False

The goal of this function is to use the search method from the re module to determine if an input string contains an a followed by an arbitrary non-zero (that is, greater than or equal to 1) number of consecutive occurrences of bs (for example, ccddabbdd). You should complete this function by filling in a regular expression to recognize this pattern. If the pattern is found, your function should return True; otherwise, it should return False. import re def findpattern(intext_str): #fill in your code here regex = re.compile(pattern) if regex.search(intext_str)!=None: return True return False

import re def findpattern(intext_str): pattern = 'ab+' regex = re.compile(pattern) if regex.search(intext_str)!=None: return True return False

membership

in Ask whether an item is in a sequence

A programmer-initialized variable

initialized within a program; hence, its value is known simply by looking at the code, oppisite of input variable

Given a numerical list as an input, you will complete the function named 'listsum' that will return the sum of the values contained in the list. Your function must use a for loop in order to solve this problem. listsum(indata): #insert your code here ...

listsum(indata): sum=0 for dval in indata: sum+=dval return sum

Mapping, dictionary, key-value pair, item, key, value, implementation, hash table, hashable, lookup, hash fuction, declaration, flag, call graph, singleton, global statement, global variable, call graph

mapping: A relationship in which each element of one set corresponds to an element of another set. dictionary: A mapping from keys to their corresponding values. key-value pair: The representation of the mapping from a key to a value. item: In a dictionary, another name for a key-value pair. key: An object that appears in a dictionary as the first part of a key-value pair. value: An object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word "value". implementation: A way of performing a computation. hashtable: The algorithm used to implement Python dictionaries. hash function: A function used by a hashtable to compute the location for a key. hashable: A type that has a hash function. Immutable types like integers, floats and strings are hashable; mutable types like lists and dictionaries are not. lookup: A dictionary operation that takes a key and finds the corresponding value. reverse lookup: A dictionary operation that takes a value and finds one or more keys that map to it. raise statement: A statement that (deliberately) raises an exception. singleton: A list (or other sequence) with a single element. call graph: A diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee. memo: A computed value stored to avoid unnecessary future computation. global variable: A variable defined outside a function. Global variables can be accessed from any function. global statement: A statement that declares a variable name global. flag: A boolean variable used to indicate whether a condition is true. declaration: A statement like global that tells the interpreter something about a variable

match() and search()

match() is a method that matches a pattern located at the beginning of a string search() is a method that will match a pattern anywhere in a string

A [blank] is a function that is associated with a particular class.

method

The process of creating a new [blank] from a class is called instantiation.

object

Assume that, before running this code, temp.dat does not exist. What error will be raised after this code runs? f = open('temp.dat','w') f.readfile()

open('temp.dat','w') creates the file. While 'temp.data' now exists, it simply contains no data.The file is empty, but there is no issue with file creation. On the other hand, the f.readfile() method does not exist (instructions such as f.read() or f.readline() would be valid method calls). Under these circumstances, since readfile() does not exist, Python will raise an attribute error.

In this code snippet, what instruction is missing that is necessary for releasing the file after the file write process has been completed? n = 5 fname = 'data' output = open(fname + ".txt",'w') output.write(str(n)+' ') print("Done! Look for the file", fname+'.txt')

output.close()

Consider this variable assignment: x=[2, 3, 4, 5, 'a', 'bee', 'c', 'dee'] What would the resulting screen output be if each of these executes directly after the assignment? Do not assume these instructions execute sequentially. Assume each singular instruction executes directly after the initial assignment. print(x[:]) Answer 1 print(x[1:3]) Answer 2 print(x[1:8:2]) Answer 3 print(x[3:1:-1]) Answer 4 print(x[2:len(x)]) Answer 5 print(x[2:]) Answer 6 print(x[:3]) Answer 7 print(x[-4:-1]) Answer 8 print(x[-1]) Answer 9 print(x[::2]) Answer 10

print(x[:]) → [2, 3, 4, 5, 'a', 'bee', 'c', 'dee'], print(x[1:3]) → [3, 4], print(x[1:8:2]) → [3, 5, 'bee', 'dee'], print(x[3:1:-1]) → [5, 4], print(x[2:len(x)]) → [4, 5, 'a', 'bee', 'c', 'dee'], print(x[2:]) → [4, 5, 'a', 'bee', 'c', 'dee'], print(x[:3]) → [2, 3, 4], print(x[-4:-1]) → ['a', 'bee', 'c'], print(x[-1]) → dee, print(x[::2]) → [2, 4, 'a', 'c']

Given this code snippet, what should be the approximate values contained in the variable n0 and n1? import random x=[ ] n=1000 n0=0 n1=0 for i in range(n): if random.random()>=0.7: x.append(1) n1+=1 else: x.append(0) n0+=1 print('Number of zeros = ',n0) print('Number of ones = ',n1)

random.random() returns a random floating point value between 0 and 1. The for loop in this code snippet will generate n=1000 random numbers. If a generated number is greater than 0.7, the list x will be appended with a one; otherwise, it will be appended with a zero. The values returned by the random method are uniformly distributed meaning that all values between 0 and 1 are equally likely. Over a large sample size, this means that approximately 70% of the values appended to the list x will be a one and approximately 30% will be a zero. When the variable n=1000, this means that the variable n0 will be somewhere near 300 and n1 will be somewhere near 700. Statistically, as n grows larger, the values of n0 and n1 will get closer and closer to their expected values

What are the random, uniform, and randint methods contained within the random module? Assuming the import random instruction has been invoked, what is the syntax for using them? Write a paragraph to explain your answer.

random: Returns a random floating point number in the range [0.0, 1.0). Syntax: random() Example: Fill a list with 10 random numbers x=[ ] for i in range(10): x.append(random.random()) uniform: Return a random floating point number N such that a <= N <= b for a <= b (or, if b<a, return a random floating point number N such that b <= N <= a for b < a) Syntax: uniform(a,b) Example: Return a random number between 3 and 5 x=random.uniform(3,5) Randint: Return a random integer N such that a <= N <= b. Syntax: randint(a,b) Example: Return a random number between 100 and 200 x=random.randint(100,200)

s.lower(), s.upper() s.strip () s.isalpha)/s.isdigit()/s.isspace) s.startswith ('other') s.replace ('old', 'new') s.split ('delim') s.join(list)

s.lower(), s.upper() -- returns the lowercase or uppercase version of the string • s.strip () -- returns a string with whitespace removed from the start and end • s.isalpha)/s.isdigit()/s.isspace)...--testsif all the string chars are in the various character classes • s.startswith ('other'), s.endswith('other') --tests if the string starts or ends with the given other string • s.find ('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found • s.replace ('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new' • s.split ('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split('") -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split () (with no arguments) splits on all whitespace chars. • s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'join (l'aaa', 'bbb', 'ccc'1) -> aaa---bbb---ccc

Search(...) Findall(...) Finditer(...)

search (...) - In contrast to match(...), search (...) tries to find matching locations anywhere within the string not just matches starting at the beginning. That means "^John" used with search(...) corresponds to "John" used with match(...), and "*John" used with match(...) corresponds to "John" used with search (...). However, "corresponds" here only means that a match will be found in exactly the same cases but the output by the different methods of the returned matching object will still vary. • findall(...) - In contrast to match(...) and search (...), findall(...) will identify all substrings in the given string that match the regular expression and return these matches as a list. • finditer (...) - finditer (...) works like findali(...) but returns the matches found not as a list but as a so-called iterator object.

Consider these two snippets of code: Snippet 1: fname = 'temp1' output = open(fname + ".txt",'w') output.write(str(5)+' ') output.write(str(7)+' ') output.close() Snippet 2: fname = 'temp2' output = open(fname + ".txt",'w') output.write(str(5)+' ') output.close() output = open(fname + ".txt",'w') output.write(str(7)+' ') output.close() What data will be contained in the files temp1.txt and temp2.txt

temp1.txt will contain: 5 7 temp2.txt will contain: 7


Ensembles d'études connexes

Medical surgical (cardiovascular and hematologic)

View Set

CSM204 - Exam 1 (Knowledge Checks)

View Set

Chapter 16 listening quiz answers

View Set