Python Flashcards

(280 cards)

1
Q

In Python, data = [6, 8, 10, 12];

put data into an np array?

A

import np

MyArray = np.array(data)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

In Python add dict1 to dict 2?

A

dict2.update(dict1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

In Python, create a dict that pairs keys and values? (keys and values are variables)

A

dict(zip(keys, values))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

In Python and numpy:
arr_slice = arr[5:8]
arr_slice[1] = 12345

What is the result?

A

arr[6] equals 12345 (in the original object)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a python list comprehension to find all words in TEXT that are longer than 5 characters and appear at least 5 times?

A

[w for w in set(TEXT) if len(w) > 5 and FreqDist(TEXT)[w] >=5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

With NLTK, when tagging, what is a way to address the trade-off between accuracy and coverage?

A

Start with a tagger that is more accurate and back-off to a tagger that has greater coverage

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

In python, how can you reverse a dictionary and why do it?

A

How:
nltk.Index((value, key) for (key, value) in oldDict.items())

Why:

  • Reverse lookup is faster
  • dict() won’t deal with multiple values
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Using NLTK and the brown corpus, how do you create a conditional frequency distribution based on genre?

A

ConditionalFreqDist((genre, word)
for genre in brown.categories()
for word in brown.words(categories = genre))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

arr = np.array([1, 2, 3], [4, 5, 6])

What does arr[0,2] return?

A

The same as arr[0][2], which is 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

arr = np.array([1, 2, 3], [4, 5, 6])

What does arr[0][2] return?

A

The same as arr[0,2], which is 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

In iPython, 2 quick ways to time a function?

A

1) %timeit

2) %time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In Python, return an object’s True or False?

A

bool(object)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

In Python, return the value of ‘a’ from myDict while deleting the key, value pair?

A

myDict.pop(‘a’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

In Python, load numpy?

A

import numpy as np

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

In iPython, look up magic words?

A

%.[TAB]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

In Python’s interpreter, return list of attributes & methods of myObject?

A

myObject.[TAB]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

In, iPython, what does this return?

‘numpy.load?’

A

All numpy functions that have load as part of the name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

In Python, s = ‘hello’

s[::-1]?

A

olleh

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

In Python, what does the following return if x = 30?

‘Yes’ if x > 10 else ‘No’

A

‘Yes’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

In Python, s = ‘hello’

What does the following return?

For i, value in enumerate(s):
print(value)

A
h
e
l
l
o
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

In Python, return and remove the 3rd item in list T?

A

T.pop(2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

In Python, s = ‘hello’

What does the following return?

s[2:4]

A

ll

s[start:up to, but not including]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

In Python and np, how do you flip an array Dat with rows and columns?

A

Dat.T()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

In Python and np:

names = array of 7 names
data = 7 by 4 d.array

What does the following return?

data[names == “Bob”|names == ‘Will’]

A

The rows of data at the index of names that equal ‘Bob’ or ‘Will’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
In lexical resources, what is the word itself called?
the headword or lemma
26
In lexical resources, what is the classification as a noun, verb, etc., called?
The part-of-speech or lexical category
27
In lexical resources, what is the meaning referred to as?
Sense definition or gloss
28
In Python, tup = (4, 5, (6, 7)) Unpack tup?
a, b, (c, d) = tup
29
In Python, test if string S has a title capitilization?
S.istitle()
30
In Python, what module is useful to add items into a sorted list?
bisect
31
Assuming data is an np nd.array, how many rows & columns?
data.shape
32
In Python and np, how do you copy an array?
array.copy()
33
In Python, rewrite the following as a list comprehension? flattened = [] for tup in some_tuples: for x in tup: flattened.append(x)
flattened = [x for tup in some_tuples for x in tup]
34
In Python, how do you create a list of 1 - 10?
range(1, 11)
35
In Python, how do you create a list of 10 - 20?
range(10, 21)
36
In Python, how do you create a list of 10, 12, 14, 16, 18, 20?
range(10, 21, 2)
37
In nltk, view a graph of Conditional Frequency Distribution called cfd?
cfd.plot()
38
With pd, dat has columns year and state. Create a column called myNum that equals 16 for all records?
dat['myNum'] = 16
39
With pd, dat is a list object of multiple dictionaries. Create a data frame?
DataFrame(dat)
40
In Python, define a feature extractor for documents that searches a document for a list of words and returns a feature set?
def myFunc(list_of_words, a_document): - >doc_words = set(a_document) - >to_return = {} - >for words in list_of_words: - >->to_return['contains(%s)' % words] = words in doc_words - >to_return
41
With pd, what are 2 ways to return a column from a DataFrame?
Attr: dat.name Dict: dat['name']
42
With pd, assign -5 to Series object dat at index 't'?
dat['t'] = -5
43
With pd, create a series from 4, 7, 2, 1?
Series([4, 7, 2, 1])
44
Load pandas?
import pandas as pd | from pandas import Series, DataFrame
45
Assuming this_dat is an np nd-array, what is the type?
this_dat.dtype
46
With pd, return just Series obj's values?
obj.values
47
In pd, 2 ways to use .isnull and .notnull?
Either as a method of an object or a pd function applied to an object.
48
With pd, return Series object--obj--index?
obj.index
49
In Python and np, return set difference of x vs. y?
np.setdiff1d(x, y)
50
In Python, view the conditions associated with a Conditional Frequency Distribution called CFD?
CFD.conditions()
51
With pd, assign column order of 'state' then 'year' to dat DataFrame?
DataFrame(dat, columns = ['state', 'year'])
52
In Python and np, return the intersection of x and y?
np.intersect1d(x, y)
53
With pd, what happens when you build a DataFrame out of a nested dictionary with 2 levels?
Outer dict keys become the columns and the inner keys are the rows.
54
In Python and np, dat is an array, return another array of 2s and -2s depending on whether dat's value is positive?
np.where(dat > 0, 2, -2)
55
In NLTK, return words that commonly appear around "car" and "bus" in T?
T.common_contexts(['car', 'bus'])
56
In NLTK, create a plot showing where "car", "bus", and "stew" appear in T?
T.dispersion_plot(['car', 'bus', 'stew'])
57
In Python and np, return unique items in x?
np.unique(x)
58
With pd, dat is a dictionary. What does Series(dat) do?
Creates a Series object with dat's keys as an index and in sorted order.
59
In NLTK, after creating 2 lists of words, TEXT1 and TEXT2, how do you find the unique words in TEXT1?
TEXT1.difference(TEXT2) or TEXT1 - TEXT2
60
With NLTK, create a concordance with text object T?
T.concordance('myword')
61
In Python, what is for loop to return the number and existence of each letter in the string variable STRING?
a_dict = {} for L in 'abcdefghijklmnopqrstuv': -> a_dict[L] = STRING.lower().count(L)
62
What are ways to get a list of keys from a Python dictionary, dict?
Treat it like a list and the keys will be the list.
63
In Python, iterate over unique items in S?
for item in set(S)
64
In Python, iterate over a unique set of items in S that are not in T?
for item in set(S).difference(T)
65
In Python, iterate over a random set of items in S?
for item in random.shuffle(S)
66
With pd, delete column State from dat?
del dat['State']
67
In Python, how do you write to a file?
``` with open("file.txt", "w") as f: -> f.write("here is some text") ```
68
With NLTK, how do I create a stop-words object that contains a list of english stop-words?
nltk.corpus.stopwords.words('english')
69
In Python and np, return union of x and y?
np.union1d(x, y)
70
In NLTK, return words that have a similar concordance with "apple" in T?
T.similar("apple")
71
In Python, add [4, 'foo', 3, 'red'] to list T?
T.extend([4, 'foo', 3, 'red'])
72
In NLTK, generally describe in code how to create a conditional frequency distribution?
nltk.ConditionalFreqDist(tuple of words like (condition, word))
73
In Python, use code to confirm x is an integer, returning True or False?
isinstance(x, int)
74
In Python, add 'word' at index 3 to list T, sliding all other values to the right?
T.insert(3, 'word')
75
With NLTK, tag all words in TEXT with 'n'?
my_tagger = nltk.DefaultTagger('n') | my_tagger.tag(TEXT)
76
With NLTK, tag all words with tuples of the form (regex, "tag") stored in PATTERNS?
nltk.RegexpTagger(PATTERNS)
77
With NLTK, tag all words based on a lookup list stored in TAGS, while backing off to a tagger that tag "Unk" for any word not in the lookup?
``` nltk.UnigramTagger(model = TAGS, backoff = nltk.DefaultTagger("Unk")) ```
78
In Python, add 'word' to the end of list T?
T.append('word')
79
In Python and np, return boolean for items from x that are in y?
np.in1d(x, y)
80
Create a Python function for creating a measure for the lexical diversity of TEXT?
``` def lexDef(TEXT): -> return (len(TEXT) / len(set(TEXT)) ```
81
In Python, how do you continue onto the next line outside parenthesis?
"\"
82
In Python, return the intersection of S1 and S2?
S1.intersection(S2) or S1 & S2
83
In Python, create a table of a conditional frequency distribution call CFD?
CFD.tabulate()
84
In Python, why are some functions names prefixed by "___"?
They are hidden objects meant to only be used within a module and, as a result, will not be imported when the rest of a library is imported.
85
In NLTK, how do you create an NLTK corpus from a set of text files?
from nltk import PlaintextCorpusReader | corpus = PlaintextCorpusReader(file_path, REGEX_FOR_FILENAMES)
86
WordNet: What is a hypernym?
Words that are up the hierarchy (corvette -> car)
87
WordNet: What is a hyponym?
Words that are down the hierarchy (car -> corvette)
88
WordNet: What is a meronym?
Components of a word (tree is made up of branch, root, and leaves)
89
WordNet: What is a holonym?
What a word is contained in (forest includes trees, a forest is a holonym of tree)
90
WordNet: What does entail mean?
Specific steps in a verb (walking -> stepping)
91
In Python, after importing os, how do you see your working dir?
os.getcwd()
92
In NLTK, n-gram functions?
nltk. util.bigram(TEXT) nltk. util.trigram(TEXT) nltk. util.ngram(TEXT, n)
93
In Python: def search1(subst, words): - > for word in words: - >-> if subst in word: - >->-> yield word What and why?
This is a generator and is usually more efficient than building a list to store.
94
In regex, search for any letter from a to m?
[a-m]
95
In regex, search for any letter in the word chasm?
[chasm]
96
In regex search for the word chasm or bank?
'chasm|bank'
97
In Python, how do I slice a portion of a STRING that is after the word "START" and up to the word "END"?
STRING[STRING.find('START'):STRING.find('END')]
98
In Python, return the union of SET1 and SET2?
SET1 | SET2 or SET1.union(SET2)
99
In Python, test if string S is all numbers?
S.isdigits()
100
In Python and np, create an array with 0-14?
np.arange(15)
101
In NLTK, assuming I have a RAW string file, how do I tokenize it?
nltk.word_tokenize(RAW)
102
With a frequency distribution (fdist), get a word's percent frequency?
fdist.freq('word')
103
With a freq. dist. (fdist), get n?
fdist.N()
104
With a freq. dist. (fdist), get a plot?
fdist.plot()
105
With a freq. dist. (fdist), get a cumulative plot?
fdist.plot(cumulative = True)
106
In Python, test if string S's last letter is "L"?
S.endswith("L")
107
In Python, test if string S is all non-capitalized letters?
S.islower()
108
In Python, test if string S is composed of letters and numbers?
S.isalnum()
109
In Python, test if string S is all letters?
S.isalpha()
110
In Python, test if string S is all capital letters?
S.isupper()
111
In Python and np, return items in x or y, but not both?
np.setxor1d(x, y)
112
In regex, what is 'a*'?
0 or more of 'a'
113
In regex, what is 'a+'?
1 or more of 'a'
114
In regex, what is 'a?'?
0 or 1 of 'a'
115
In Python, given STRING return the location of "a" going from left to right, but return -1 if not found?
STRING.find("a")
116
In Python, given STRING return the location of "a" going from right to left, but return -1 if not found?
STRING.rfind("a")
117
In Python, given STRING return the location of "a" going from left to right, but return ValueError if not found?
STRING.index("a")
118
In Python, given STRING return the location of "a" going from right to left, but return ValueError if not found?
STRING.rindex("a")
119
In Python, given STRING, return it as all lower case?
STRING.lower()
120
In Python, given STRING, return it as all upper case?
STRING.upper()
121
In Python, given STRING, return it as title casing?
STRING.title()
122
In Python, merge the elements of STRING or LIST with "-"?
"-".join(STRING) | "-".join(LIST)
123
In Python, split A_SENTENCE by the spaces?
A_SENTENCE.split(" ")
124
In Python, split A_DOCUMENT_STRING by new lines?
A_DOCUMENT_STRING.splitlines()
125
In Python, remove leading and trailing whitespace from STRING?
STRING.strip()
126
In Python, replace all occurrences of the letter 'e' with '-' in STRING?
STRING.replace("e", "-")
127
What is an NLTK Text object?
A python list of each individual word and punctuation mark from a STRING or DOCUMENT.
128
___ i in ITERABLE: - >__ ITERABLE[i] == 10: - > -> 1 - >__ ITERABLE[i] == 15: - > -> 0 - >__ - > -> "Neither"
for i in ITERABLE: - >if ITERABLE[i] == 10: - > -> 1 - >elif ITERABLE[i] == 15: - > -> 0 - >else: - > -> "Neither"
129
As list comprehension: for obj in objects: - > if obj == 10: - > -> myFunc(obj)
[myFunc(obj) for obj in objects if obj == 10]
130
In Python's Regex: add word boundary to end of pattern "the"?
r"the\b"
131
In Python's Regex: pattern to find 2 or 3 digits?
r"\d{2,3}"
132
In Python's Regex: pattern to find 5 non-digits?
r"\D{5}"
133
In Python's Regex: pattern to find 0 or 1 spaces?
r"\s?"
134
In Python's Regex: pattern to find a non-space?
r"\S"
135
In Python's Regex: pattern to find a alphanumerics?
r"\w"
136
In Python's Regex: pattern to find anything but alphanumerics?
r"\W"
137
In Python's Regex: pattern to find a tab?
r"\t"
138
In Python's Regex: pattern to find a new line?
r"\n"
139
Python's "not equal"?
!=
140
Python's "equal to"
==
141
Python's "less than or equal"?
<=
142
Python: test for x is greater than 10 but less than or equal to 15?
10 < x <= 15
143
Sort myDict by its value?
from operator import itemgetter | newDict = sorted(myDict.items(), key = itemgetter(1))
144
In Python, open and read the content of a TEXT.txt into STRING?
``` with open("TEXT.txt", "r") as f: -> STRING = f.read() ```
145
With NLTK, create a list of English words from UNIX dictionary?
english_vocab = set(w.lower() for w in nltk.corpus.words.words())
146
Create an NLTK Text object from tokenized text?
nltk.Text(tokens)
147
What NLTK function is a version of defaultdict with sorting and plotting methods?
nltk.Index()
148
What is Brill tagging?
Transformation based learning where a model guess the tag of each word, but then fixes mistakes based on context. Rules are of the form "retag x to y if z comes before it"
149
In Python, return myDict's keys?
myDict.keys()
150
In Python, return myDict's items as a list of tuples?
myDicts.items()
151
In Python, return myDict's values?
myDict.values()
152
With nltk, remove HTML tags from this_object?
nltk.clean_html(this_object)
153
In Python, test if STRING's first letter is "A"?
STRING.startswith("A")
154
With pd, add or change DATAFRAME's name for its columns or index?
``` DATAFRAME.column.name = "NEW_NAME" DATAFRAME.index.name = "NEW_NAME" ```
155
With nltk, count all words in TEXT? (I believe this must be a nltk.Text object)
nltk.FreqDist(TEXT)
156
In Python's Regex: pattern to find "a" followed by any character but a new line?
r"a."
157
In Python's Regex: pattern to find the word "the", but not as part of any other word?
r"^the$"
158
In Python's Regex: pattern to anything but vowels?
r"[^aeiou]"
159
In Python, finish this code to create NewText, wihch only includes the top 1000 most frequent words and replaces all others with "Unk"? from collections import defaultdict vocab = nltk.FreqDist(OldText) v1000 = list(vocab)[:1000] now what?
map = defaultdict(lamda: "Unk") for v in v1000: -> map[v] = v NewText = [map[v] for v in OldText]
160
Using Python's list comprehension, count the number of times words ending in 'ed', 'ing', or 'es' show up in My_Text?
sum([1 for w in My_Text if re.search(r"ed$|ing$|es$", w)])
161
In Python, import and start debugger on myFunc?
import pdb | pdb.run("myFunc()")
162
In Python, while in debugger, execute the current line?
step
163
In Python, while in debugger, execute through the next line?
next
164
In Python, while in debugger, execute up to the next break point?
continue
165
In Python, while in debugger, how do you view the value of Obj?
Obj
166
In Python, while in debugger, how do you see the value of a function's parameter??
argument name
167
In Python's debugger, how do you view or list break points?
break on command line or in code
168
With nltk's Text, find every instance of "a * man", but return only *?
Text.findall(r" (.*) ")
169
In Python, derive the vocab from Text?
set([w.lower() for w in Text if w.isalpha()])
170
In Python, test if STRING contains SUBSTRING?
SUBSTRING in STRING
171
In Python, how do I check what kind of object MY_OBJECT is?
type(MY_OBJECT)
172
In Python, return the actual result of 5 divided by 2?
5 / 2
173
In Python, return the integer result of 5 divided by 2?
5 // 2
174
In Python, return the remainder from 5 divided by 2?
5 % 2
175
In Python, what is another way to do the following: a = a + 3?
a += 3
176
In Python, return the remainder and integer result of 5 divided by 2?
divmod(5, 2)
177
In Python, what does int(98.7) return?
98 because it just lops off everything after the decimal
178
In Python: ``` bottles = 99 base = 'current inventory: ' ``` Add bottles to base?
base += str(bottles)
179
In Python: ``` a = Duck. b = a c = Grey Duck! ``` Result of a + b + c vs. print(a, b, c)?
a + b + c = Duck.Duck.Grey Duck! | print(a, b, c) = Duck. Duck. Grey Duck!
180
In Python, what happens and what are solutions? ``` name = 'Henry' name[0] = 'P' ```
TypeError because strings are immutable. Must use name.replace("H", "P") or "P" + name[1:]
181
In Python, how many times does WORD appear in LONG_STRING?
LONG_STRING.count(WORD)
182
In Python, return MY_LIST in reverse?
MY_LIST[::-1]
183
In Python, another way to do: MY_LIST.extend(YOUR_LIST)
MY_LIST += YOUR_LIST
184
In Python, another way to do: MY_LIST += YOUR_LIST
MY_LIST.extend(YOUR_LIST)
185
In Python, what is the difference between MY_LIST.extend(YOUR_LIST) and MY_LIST.append(YOUR_LIST)?
MY_LIST.extend(YOUR_LIST) returns a single list | MY_LIST.append(YOUR_LIST) makes MY_LIST[:-1] = YOUR_LIST (a list within a list)
186
In Python, get rid of 'item_a' in MY_LIST?
MY_LIST.remove('item_a')
187
In Python, return and then get rid of 'item_a' in MY_LIST?
MY_LIST.pop('item_a')
188
In Python, return the index of 'item_a' in MY_LIST?
MY_LIST.index('item_a')
189
In Python, how many times does 'item_a' appear in MY_LIST?
MY_LIST.count('item_a')
190
In Python, what is the difference between: MY_LIST.sort() sorted(MY_LIST)
MY_LIST.sort() changes MY_LIST (and does not return the result) sorted(MY_LIST) returns a sorted copy of MY_LIST
191
In Python: ``` a = [1, 2, 3] b = a a[0] = 5 ``` What does b return?
[5, 2, 3]
192
In Python, create a new version of MY_LIST in NEW_LIST? (3 ways)
``` NEW_LIST = MY_LIST.copy() or NEW_LIST = list(MY_LIST) or NEW_LIST = MY_LIST[:] ```
193
In Python, delete all keys and values from a MY_DICTIONARY? (2 ways)
MY_DICTIONARY.clear() or MY_DICTIONARY = {}
194
In Python, MY_DICTIONARY does not have THIS_KEY. What is the difference? MY_DICTIONARY.get("THIS_KEY", "Nope") MY_DICTIONARY["THIS_KEY"]
MY_DICTIONARY.get("THIS_KEY", "Nope") returns "Nope" MY_DICTIONARY["THIS_KEY"] Returns an error
195
In Python 3, what is the difference? MY_DICT.keys() list(MY_DICT.keys())
MY_DICT.keys() returns MY_DICT.dict_keys(), which is an iterable view of the keys list(MY_DICT.keys()) returns a converted version of the iterable view, which is a list
196
In Python, create a new version of MY_DICT that keeps the dictionary's values and keys?
MY_DICT.copy()
197
In python, what does this return? bool( { 'a', 'b', 'c' } & { 'd', 'e', 'f' } )
False because the two sets have nothing in common
198
In python, what does this return? bool( [ 'a', 'b', 'c' ] & { 'd', 'e', 'f' } )
An error because the first component is a list
199
In Python, what does this return? {'a', 'b', 'c'} ^ {'d', 'e', 'a'}
{'b', 'c', 'd', 'e'}
200
In Python, what is another version of this? SET1.issubset(SET2)
SET1 <= SET2
201
In Python, what is another version of this? SET1.issuperset(SET2)
SET1 >= SET2
202
In Python, make a tuple of lists out of LIST1, LIST2, LIST3?
tup_of_lists = LIST1, LIST2, LIST3
203
In Python, count = 1, create a while loop that adds to count until it is equal to 50?
while count < 50: | -> count += 1
204
In Python, create an infinite loop that capitalizes the users input and stops only when the user enters 'q'?
while True: - > user_input = input('Enter Here: ") - > if user_input == 'a': - > -> break - > print(user_input.upper())
205
In Python, how do you make a loop start the next iteration without completed the remaining code within the current loop?
continue
206
In Python, when will this end? for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts): -> print(day, fruit, drink, dessert)
When the shortest sequence is done
207
Describe Python's list comprehension?
[ expression for item in iterable if condition ]
208
Describe Python's dictionary comprehension?
{ key_expression : value_expression for item in iterable if condition }
209
Describe Python's set comprehension?
{ expression for item in iterable }
210
In Python, what is this? | expression for item in iterable if condition
It is a generator comprehension
211
In Python, create a function that repeats an argument with a space between it?
``` def echo(arg): -> return arg + " " + arg ```
212
Change this Python function so that it can take any number of arguments: ``` def print_this(VARIABLE): -> print(VARIABLE) ```
``` def print_this(*args): -> print( args ) ```
213
When defining a function in Python, how do you gather all keyword arguments into a dictionary?
**kwargs kwargs is the name of the dictionary to use in the function, but technically ' ** ' is what tells Python to gather the keyword arguments into a dictionary, which--by convention--is called kwargs
214
In Python, where do you put a function's documentation?
As a docstring at the start of the function's body as a comment
215
In Python, print print's docstring?
print(print.__doc__)
216
In Python, add an error handler that simply prints MSG: ``` def add_this(first, second): -> return first + second ```
def add_this(first, second): - > try: - > -> return first + second - > except: - > -> print(MSG)
217
In Python, test.py prints out "Program arguments: [file_name, and other arguments]". What does test.py say?
import sys | print("Program arguments: ", sys.argv)
218
In Python, return a random item from THIS_LIST
random.choice(THIS_LIST)
219
Where does Python look for modules?
Based on the items listed in sys.path
220
What function is helpful for printing an index value along with each item in LIST?
enumerate()
221
How do you make Python treat MY_DIR as a Python package?
Make sure there is a file called __init__.py, which can be empty.
222
In Python, return my_dict['key'] by assigning 12 if 'key' does not already exist and otherwise just returns its current value?
my_dict.setdefault( 'key', 12 )
223
In Python, MY_LIST is a list of objects, which sometimes repeat. How many of each item are in MY_LIST?
from collections import Counter | Counter(MY_LIST)
224
In Python, what is the most popular item or items? from collections import Counter item_counter = Counter(item)
item_counter.most_common(1)--most popular item item_counter.most_common()--all items, in sorted order
225
In Python, what does this check? word == word[::-1]
Is word a palindrome?
226
In Python, given a list, what object and methods are useful to pull items from either side?
from collections import deque - pop - popleft
227
In Python, given 4 lists, what function is useful to go through items, 1 at a time, across all 4 lists?
from itertools import chain
228
In Python, what function is useful for continuously iterating through LIST?
from itertools import cycle
229
In Python, what function is useful for cumulative functions, such as sum?
from itertools import accumulate
230
In Python, how do you create an easier to read print out?
from pprint import pprint
231
In Python, create a class for Person that stores a name?
class Person(): - > def __init__(self, name): - > -> self.name = name
232
In OOP, what are names for an original class?
superclass, parent class, base class
233
In OOP, what names for classes that inherit something from a an original class?
subclass, child class, derived class
234
In Python, create a Child class that inherits everything from a Parent class and does nothing additional?
``` class Child(Parent): -> pass ```
235
In Python, create a class for Doctor that stores a name and has method to greet a patient by name?
class Doctor(): - > def __init__(self, name): - > -> self.name = name - > def greeting(self, patient): - > -> self.greeting = print("Hello", patient, "I'm Doctor", self.name)
236
In Python, why use super()?
If you are creating a subclass with a new __init__ definition, but still want to inherit items from the parent class
237
In Python, class Circle(): - > def __init__(self, radius): - > -> self.radius = radius - > @property - > def diameter(self): - > -> return 2 * self.radius test = Circle(30) What happens when you run: test.diameter = 15
An exception because diameter is a attribute that can't be set directly. This is identified by the @property tag, which would otherwise make diameter a method rather than an attribute.
238
What is a class method and how is it distinguished?
It is a method that affects the class as a whole, as opposed to an instance method, which affects only a particular instance of the class. It is distinguished with the @classmethod decorator tag.
239
In Python, how do you identify how to print a class?
Use the __str__ magic method to define how you print a class when print(class) is called.
240
In Python, create a named tuple called 'document' that has attr1, attr2, and attr3 as its composition? Then use it for item1, item2, item3.
from collections import namedtuple the_tuple = namedtuple('document', 'attr1 attr2 attr3') the_tuple(item1, item2, item3)
241
Using old style strings in Python, create a string that says the following, but "Hunter" and "1984" are variables: "My name is Hunter and I was born in 1984"
"My name is %s and I was born in %s" % (name, year)
242
Using new style strings in Python, create a string that says the following, but "Hunter" and "1984" are variables: "My name is Hunter and I was born in 1984"
"My name is {} and I was born in {}".format(name, year)
243
In Python regular expressions, what is the difference between the methods and functions?
The methods require calling re.compile(pattern) first, but then the search will be sped up. If not necessary, re.functionname(pattern, object) is a reasonable alternate.
244
In Python, return the first match of a regular expression PATTERN within STRING?
CP = re.compile(PATTERN) CP.search(STRING) OR re.search(PATTERN, STRING)
245
In Python, return of all non-overlapping matches to regular expression PATTERN within STRING?
CP = re.compile(PATTERN) CP.findall(STRING) OR re.findall(PATTERN, STRING)
246
In Python, return a list made from a STRING that was split at a regular expression PATTERN.
CP = re.compile(PATTERN) CP.split(STRING) OR re.split(PATTERN, STRING)
247
In Python, replace all matches to a regular expression PATTERN contained within STRING using REPLACEMENT?
re.sub(PATTERN, REPLACEMENT, STRING)
248
In Python, check to see if the STRING starts with the regular expression PATTERN?
CP = re.compile(PATTERN) CP.match(STRING) OR re.match(PATTERN, STRING)
249
Create a regex that finds pat1 if is not followed by pat2?
pat1(!=pat2)
250
Create a regex that finds pat1 if it is preceded by pat2?
(?<=pat2)pat1
251
Create a regex that finds pat1 if it is not preceded by pat2?
(?<1pat2)pat1
252
Describe the pattern for use in re.search or re.match that allows you to name groups?
(?P< name > pattern)
253
Create a regex that finds pat1 if is followed by pat2?
pat1(?=pat2)
254
Read file.txt in one line at a time, but create a single string called the_text?
the_text = "" with open("file.txt", "r") as f: -> for line in f: -> -> the_text += line
255
Read in file.csv as a list (columns) of lists (rows)?
``` import csv with open("file", "r") as f: -> cin = csv.reader(f) -> stuff = [row for row in cin] ```
256
What does this do? import csv with open("villians', 'r') as fin: - > cin = csv.DictReader(fin, fieldnames = ['first', 'last']) - > villains = [row for row in cin] print(villains ]
It prints villains, which is a list of dictionaries each have a key for 'first' and for 'last'
257
What is the simplest way to parse XML in Python?
Using xml.etree.ElementTree
258
Given a string JSON--in JSON format--read it into a Python dictionary?
import json | str_dict= json.loads(JSON)
259
Verify a directory or a file exist?
import os | os.path.exists(directory or file)
260
Verify myfile is an existing file in your working dir?
import os | os.path.isfile(myfile)
261
Verify mydir is an existing directory?
os.path.isdir(mydir)
262
Is myfilename an absolute path?
os.path.isabs(myfilename)
263
Copy myfile.txt and call it newtext.txt?
import shutil | shutil.copy('myfile.txt', 'newtext.txt')
264
Rename myfile.txt newtext.txt?
import os | os.rename('myfile.txt', 'newtext.txt')
265
Get the full path name for myfile.txt, which is in your current working directory?
os.path.abspath('myfile.txt')
266
Delete myfile.txt?
os.remove('myfile.txt')
267
Create the directory, mynewdir?
os.mkdir('mynewdir')
268
Remove the directory, mynewdir?
os.rmdir('mynewdir')
269
List the items in mynewdir, which is within the current working directory?
os.listdir('mynewdir')
270
Switch to mynewdir, which is within the current working directory?
os.chdir('mynewdir')
271
Find all the files within the current working directory that start with 'm'?
import glob | glob.glob("m*")
272
What module and object deals with years, months, and days?
datetime.date
273
What module and object deals with hours, minutes, seconds, and fractions of a second?
datetime.time
274
What module and object deals with years, months, days, hours, minutes, seconds, and fractions of a second
datetime.datetime
275
What module and object deals with date or time intervals?
datetime.timedelta
276
How does the time module deal with time?
As seconds from January 1, 1970.
277
Convert the time object, mytime, to a string?
time.ctime(mytime)
278
What method of datetime, date, or time objects, or function from the time module is useful for converting dates and times to strings?
strftime()
279
What method is useful for converting a string to a time object?
time.strptime()
280
Create a switch to return VALUE based on POSSIBILITIES?
choices = dict(zip(POSSIBILITES, VALUE)) | choices.get(a_possibility, "Default for key error")