Python Flashcards
In Python, data = [6, 8, 10, 12];
put data into an np array?
import np
MyArray = np.array(data)
In Python add dict1 to dict 2?
dict2.update(dict1)
In Python, create a dict that pairs keys and values? (keys and values are variables)
dict(zip(keys, values))
In Python and numpy:
arr_slice = arr[5:8]
arr_slice[1] = 12345
What is the result?
arr[6] equals 12345 (in the original object)
What is a python list comprehension to find all words in TEXT that are longer than 5 characters and appear at least 5 times?
[w for w in set(TEXT) if len(w) > 5 and FreqDist(TEXT)[w] >=5]
With NLTK, when tagging, what is a way to address the trade-off between accuracy and coverage?
Start with a tagger that is more accurate and back-off to a tagger that has greater coverage
In python, how can you reverse a dictionary and why do it?
How:
nltk.Index((value, key) for (key, value) in oldDict.items())
Why:
- Reverse lookup is faster
- dict() won’t deal with multiple values
Using NLTK and the brown corpus, how do you create a conditional frequency distribution based on genre?
ConditionalFreqDist((genre, word)
for genre in brown.categories()
for word in brown.words(categories = genre))
arr = np.array([1, 2, 3], [4, 5, 6])
What does arr[0,2] return?
The same as arr[0][2], which is 3.
arr = np.array([1, 2, 3], [4, 5, 6])
What does arr[0][2] return?
The same as arr[0,2], which is 3.
In iPython, 2 quick ways to time a function?
1) %timeit
2) %time
In Python, return an object’s True or False?
bool(object)
In Python, return the value of ‘a’ from myDict while deleting the key, value pair?
myDict.pop(‘a’)
In Python, load numpy?
import numpy as np
In iPython, look up magic words?
%.[TAB]
In Python’s interpreter, return list of attributes & methods of myObject?
myObject.[TAB]
In, iPython, what does this return?
‘numpy.load?’
All numpy functions that have load as part of the name.
In Python, s = ‘hello’
s[::-1]?
olleh
In Python, what does the following return if x = 30?
‘Yes’ if x > 10 else ‘No’
‘Yes’
In Python, s = ‘hello’
What does the following return?
For i, value in enumerate(s):
print(value)
h e l l o
In Python, return and remove the 3rd item in list T?
T.pop(2)
In Python, s = ‘hello’
What does the following return?
s[2:4]
ll
s[start:up to, but not including]
In Python and np, how do you flip an array Dat with rows and columns?
Dat.T()
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’]
The rows of data at the index of names that equal ‘Bob’ or ‘Will’
In lexical resources, what is the word itself called?
the headword or lemma
In lexical resources, what is the classification as a noun, verb, etc., called?
The part-of-speech or lexical category
In lexical resources, what is the meaning referred to as?
Sense definition or gloss
In Python, tup = (4, 5, (6, 7))
Unpack tup?
a, b, (c, d) = tup
In Python, test if string S has a title capitilization?
S.istitle()
In Python, what module is useful to add items into a sorted list?
bisect
Assuming data is an np nd.array, how many rows & columns?
data.shape
In Python and np, how do you copy an array?
array.copy()
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]
In Python, how do you create a list of 1 - 10?
range(1, 11)
In Python, how do you create a list of 10 - 20?
range(10, 21)
In Python, how do you create a list of 10, 12, 14, 16, 18, 20?
range(10, 21, 2)
In nltk, view a graph of Conditional Frequency Distribution called cfd?
cfd.plot()
With pd, dat has columns year and state.
Create a column called myNum that equals 16 for all records?
dat[‘myNum’] = 16
With pd, dat is a list object of multiple dictionaries.
Create a data frame?
DataFrame(dat)
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
With pd, what are 2 ways to return a column from a DataFrame?
Attr: dat.name
Dict: dat[‘name’]
With pd, assign -5 to Series object dat at index ‘t’?
dat[‘t’] = -5
With pd, create a series from 4, 7, 2, 1?
Series([4, 7, 2, 1])
Load pandas?
import pandas as pd
from pandas import Series, DataFrame
Assuming this_dat is an np nd-array, what is the type?
this_dat.dtype
With pd, return just Series obj’s values?
obj.values
In pd, 2 ways to use .isnull and .notnull?
Either as a method of an object or a pd function applied to an object.
With pd, return Series object–obj–index?
obj.index
In Python and np, return set difference of x vs. y?
np.setdiff1d(x, y)
In Python, view the conditions associated with a Conditional Frequency Distribution called CFD?
CFD.conditions()
With pd, assign column order of ‘state’ then ‘year’ to dat DataFrame?
DataFrame(dat, columns = [‘state’, ‘year’])
In Python and np, return the intersection of x and y?
np.intersect1d(x, y)
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.
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)
In NLTK, return words that commonly appear around “car” and “bus” in T?
T.common_contexts([‘car’, ‘bus’])
In NLTK, create a plot showing where “car”, “bus”, and “stew” appear in T?
T.dispersion_plot([‘car’, ‘bus’, ‘stew’])
In Python and np, return unique items in x?
np.unique(x)
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.
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
With NLTK, create a concordance with text object T?
T.concordance(‘myword’)
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)
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.
In Python, iterate over unique items in S?
for item in set(S)
In Python, iterate over a unique set of items in S that are not in T?
for item in set(S).difference(T)
In Python, iterate over a random set of items in S?
for item in random.shuffle(S)
With pd, delete column State from dat?
del dat[‘State’]
In Python, how do you write to a file?
with open("file.txt", "w") as f: -> f.write("here is some text")
With NLTK, how do I create a stop-words object that contains a list of english stop-words?
nltk.corpus.stopwords.words(‘english’)
In Python and np, return union of x and y?
np.union1d(x, y)
In NLTK, return words that have a similar concordance with “apple” in T?
T.similar(“apple”)
In Python, add [4, ‘foo’, 3, ‘red’] to list T?
T.extend([4, ‘foo’, 3, ‘red’])
In NLTK, generally describe in code how to create a conditional frequency distribution?
nltk.ConditionalFreqDist(tuple of words like (condition, word))
In Python, use code to confirm x is an integer, returning True or False?
isinstance(x, int)
In Python, add ‘word’ at index 3 to list T, sliding all other values to the right?
T.insert(3, ‘word’)
With NLTK, tag all words in TEXT with ‘n’?
my_tagger = nltk.DefaultTagger(‘n’)
my_tagger.tag(TEXT)
With NLTK, tag all words with tuples of the form (regex, “tag”) stored in PATTERNS?
nltk.RegexpTagger(PATTERNS)
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"))
In Python, add ‘word’ to the end of list T?
T.append(‘word’)
In Python and np, return boolean for items from x that are in y?
np.in1d(x, y)
Create a Python function for creating a measure for the lexical diversity of TEXT?
def lexDef(TEXT): -> return (len(TEXT) / len(set(TEXT))
In Python, how do you continue onto the next line outside parenthesis?
”"
In Python, return the intersection of S1 and S2?
S1.intersection(S2)
or
S1 & S2
In Python, create a table of a conditional frequency distribution call CFD?
CFD.tabulate()
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.
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)
WordNet: What is a hypernym?
Words that are up the hierarchy (corvette -> car)
WordNet: What is a hyponym?
Words that are down the hierarchy (car -> corvette)
WordNet: What is a meronym?
Components of a word (tree is made up of branch, root, and leaves)
WordNet: What is a holonym?
What a word is contained in (forest includes trees, a forest is a holonym of tree)
WordNet: What does entail mean?
Specific steps in a verb (walking -> stepping)
In Python, after importing os, how do you see your working dir?
os.getcwd()
In NLTK, n-gram functions?
nltk. util.bigram(TEXT)
nltk. util.trigram(TEXT)
nltk. util.ngram(TEXT, n)
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.
In regex, search for any letter from a to m?
[a-m]
In regex, search for any letter in the word chasm?
[chasm]
In regex search for the word chasm or bank?
‘chasm|bank’
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’)]
In Python, return the union of SET1 and SET2?
SET1 | SET2
or
SET1.union(SET2)
In Python, test if string S is all numbers?
S.isdigits()
In Python and np, create an array with 0-14?
np.arange(15)
In NLTK, assuming I have a RAW string file, how do I tokenize it?
nltk.word_tokenize(RAW)
With a frequency distribution (fdist), get a word’s percent frequency?
fdist.freq(‘word’)
With a freq. dist. (fdist), get n?
fdist.N()
With a freq. dist. (fdist), get a plot?
fdist.plot()
With a freq. dist. (fdist), get a cumulative plot?
fdist.plot(cumulative = True)
In Python, test if string S’s last letter is “L”?
S.endswith(“L”)
In Python, test if string S is all non-capitalized letters?
S.islower()
In Python, test if string S is composed of letters and numbers?
S.isalnum()
In Python, test if string S is all letters?
S.isalpha()
In Python, test if string S is all capital letters?
S.isupper()
In Python and np, return items in x or y, but not both?
np.setxor1d(x, y)
In regex, what is ‘a*’?
0 or more of ‘a’
In regex, what is ‘a+’?
1 or more of ‘a’
In regex, what is ‘a?’?
0 or 1 of ‘a’
In Python, given STRING return the location of “a” going from left to right, but return -1 if not found?
STRING.find(“a”)
In Python, given STRING return the location of “a” going from right to left, but return -1 if not found?
STRING.rfind(“a”)
In Python, given STRING return the location of “a” going from left to right, but return ValueError if not found?
STRING.index(“a”)
In Python, given STRING return the location of “a” going from right to left, but return ValueError if not found?
STRING.rindex(“a”)
In Python, given STRING, return it as all lower case?
STRING.lower()
In Python, given STRING, return it as all upper case?
STRING.upper()
In Python, given STRING, return it as title casing?
STRING.title()
In Python, merge the elements of STRING or LIST with “-“?
”-“.join(STRING)
“-“.join(LIST)
In Python, split A_SENTENCE by the spaces?
A_SENTENCE.split(“ “)
In Python, split A_DOCUMENT_STRING by new lines?
A_DOCUMENT_STRING.splitlines()
In Python, remove leading and trailing whitespace from STRING?
STRING.strip()
In Python, replace all occurrences of the letter ‘e’ with ‘-‘ in STRING?
STRING.replace(“e”, “-“)
What is an NLTK Text object?
A python list of each individual word and punctuation mark from a STRING or DOCUMENT.
___ 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”
As list comprehension:
for obj in objects:
- > if obj == 10:
- > -> myFunc(obj)
[myFunc(obj) for obj in objects if obj == 10]
In Python’s Regex: add word boundary to end of pattern “the”?
r”the\b”
In Python’s Regex: pattern to find 2 or 3 digits?
r”\d{2,3}”
In Python’s Regex: pattern to find 5 non-digits?
r”\D{5}”
In Python’s Regex: pattern to find 0 or 1 spaces?
r”\s?”
In Python’s Regex: pattern to find a non-space?
r”\S”
In Python’s Regex: pattern to find a alphanumerics?
r”\w”
In Python’s Regex: pattern to find anything but alphanumerics?
r”\W”
In Python’s Regex: pattern to find a tab?
r”\t”
In Python’s Regex: pattern to find a new line?
r”\n”
Python’s “not equal”?
!=
Python’s “equal to”
==
Python’s “less than or equal”?
<=
Python: test for x is greater than 10 but less than or equal to 15?
10 < x <= 15
Sort myDict by its value?
from operator import itemgetter
newDict = sorted(myDict.items(), key = itemgetter(1))
In Python, open and read the content of a TEXT.txt into STRING?
with open("TEXT.txt", "r") as f: -> STRING = f.read()
With NLTK, create a list of English words from UNIX dictionary?
english_vocab = set(w.lower() for w in nltk.corpus.words.words())
Create an NLTK Text object from tokenized text?
nltk.Text(tokens)
What NLTK function is a version of defaultdict with sorting and plotting methods?
nltk.Index()
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”
In Python, return myDict’s keys?
myDict.keys()
In Python, return myDict’s items as a list of tuples?
myDicts.items()
In Python, return myDict’s values?
myDict.values()
With nltk, remove HTML tags from this_object?
nltk.clean_html(this_object)
In Python, test if STRING’s first letter is “A”?
STRING.startswith(“A”)
With pd, add or change DATAFRAME’s name for its columns or index?
DATAFRAME.column.name = "NEW_NAME" DATAFRAME.index.name = "NEW_NAME"
With nltk, count all words in TEXT? (I believe this must be a nltk.Text object)
nltk.FreqDist(TEXT)
In Python’s Regex: pattern to find “a” followed by any character but a new line?
r”a.”
In Python’s Regex: pattern to find the word “the”, but not as part of any other word?
r”^the$”
In Python’s Regex: pattern to anything but vowels?
r”[^aeiou]”
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]
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)])
In Python, import and start debugger on myFunc?
import pdb
pdb.run(“myFunc()”)
In Python, while in debugger, execute the current line?
step
In Python, while in debugger, execute through the next line?
next
In Python, while in debugger, execute up to the next break point?
continue
In Python, while in debugger, how do you view the value of Obj?
Obj
In Python, while in debugger, how do you see the value of a function’s parameter??
argument name
In Python’s debugger, how do you view or list break points?
break on command line or in code
With nltk’s Text, find every instance of “a * man”, but return only *?
Text.findall(r”<a> (.*) “)</a>
In Python, derive the vocab from Text?
set([w.lower() for w in Text if w.isalpha()])
In Python, test if STRING contains SUBSTRING?
SUBSTRING in STRING
In Python, how do I check what kind of object MY_OBJECT is?
type(MY_OBJECT)
In Python, return the actual result of 5 divided by 2?
5 / 2
In Python, return the integer result of 5 divided by 2?
5 // 2
In Python, return the remainder from 5 divided by 2?
5 % 2
In Python, what is another way to do the following:
a = a + 3?
a += 3
In Python, return the remainder and integer result of 5 divided by 2?
divmod(5, 2)
In Python, what does int(98.7) return?
98 because it just lops off everything after the decimal
In Python:
bottles = 99 base = 'current inventory: '
Add bottles to base?
base += str(bottles)
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!
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:]
In Python, how many times does WORD appear in LONG_STRING?
LONG_STRING.count(WORD)
In Python, return MY_LIST in reverse?
MY_LIST[::-1]
In Python, another way to do:
MY_LIST.extend(YOUR_LIST)
MY_LIST += YOUR_LIST
In Python, another way to do:
MY_LIST += YOUR_LIST
MY_LIST.extend(YOUR_LIST)
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)
In Python, get rid of ‘item_a’ in MY_LIST?
MY_LIST.remove(‘item_a’)
In Python, return and then get rid of ‘item_a’ in MY_LIST?
MY_LIST.pop(‘item_a’)
In Python, return the index of ‘item_a’ in MY_LIST?
MY_LIST.index(‘item_a’)
In Python, how many times does ‘item_a’ appear in MY_LIST?
MY_LIST.count(‘item_a’)
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
In Python:
a = [1, 2, 3] b = a a[0] = 5
What does b return?
[5, 2, 3]
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[:]
In Python, delete all keys and values from a MY_DICTIONARY? (2 ways)
MY_DICTIONARY.clear()
or
MY_DICTIONARY = {}
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
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
In Python, create a new version of MY_DICT that keeps the dictionary’s values and keys?
MY_DICT.copy()
In python, what does this return?
bool( { ‘a’, ‘b’, ‘c’ } & { ‘d’, ‘e’, ‘f’ } )
False because the two sets have nothing in common
In python, what does this return?
bool( [ ‘a’, ‘b’, ‘c’ ] & { ‘d’, ‘e’, ‘f’ } )
An error because the first component is a list
In Python, what does this return?
{‘a’, ‘b’, ‘c’} ^ {‘d’, ‘e’, ‘a’}
{‘b’, ‘c’, ‘d’, ‘e’}
In Python, what is another version of this?
SET1.issubset(SET2)
SET1 <= SET2
In Python, what is another version of this?
SET1.issuperset(SET2)
SET1 >= SET2
In Python, make a tuple of lists out of LIST1, LIST2, LIST3?
tup_of_lists = LIST1, LIST2, LIST3
In Python, count = 1, create a while loop that adds to count until it is equal to 50?
while count < 50:
-> count += 1
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())
In Python, how do you make a loop start the next iteration without completed the remaining code within the current loop?
continue
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
Describe Python’s list comprehension?
[ expression for item in iterable if condition ]
Describe Python’s dictionary comprehension?
{ key_expression : value_expression for item in iterable if condition }
Describe Python’s set comprehension?
{ expression for item in iterable }
In Python, what is this?
expression for item in iterable if condition
It is a generator comprehension
In Python, create a function that repeats an argument with a space between it?
def echo(arg): -> return arg + " " + arg
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 )
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
In Python, where do you put a function’s documentation?
As a docstring at the start of the function’s body as a comment
In Python, print print’s docstring?
print(print.__doc__)
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)
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)
In Python, return a random item from THIS_LIST
random.choice(THIS_LIST)
Where does Python look for modules?
Based on the items listed in sys.path
What function is helpful for printing an index value along with each item in LIST?
enumerate()
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.
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 )
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)
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
In Python, what does this check?
word == word[::-1]
Is word a palindrome?
In Python, given a list, what object and methods are useful to pull items from either side?
from collections import deque
- pop
- popleft
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
In Python, what function is useful for continuously iterating through LIST?
from itertools import cycle
In Python, what function is useful for cumulative functions, such as sum?
from itertools import accumulate
In Python, how do you create an easier to read print out?
from pprint import pprint
In Python, create a class for Person that stores a name?
class Person():
- > def __init__(self, name):
- > -> self.name = name
In OOP, what are names for an original class?
superclass, parent class, base class
In OOP, what names for classes that inherit something from a an original class?
subclass, child class, derived class
In Python, create a Child class that inherits everything from a Parent class and does nothing additional?
class Child(Parent): -> pass
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)
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
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.
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.
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.
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)
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)
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)
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.
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)
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)
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)
In Python, replace all matches to a regular expression PATTERN contained within STRING using REPLACEMENT?
re.sub(PATTERN, REPLACEMENT, STRING)
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)
Create a regex that finds pat1 if is not followed by pat2?
pat1(!=pat2)
Create a regex that finds pat1 if it is preceded by pat2?
(?<=pat2)pat1
Create a regex that finds pat1 if it is not preceded by pat2?
(?<1pat2)pat1
Describe the pattern for use in re.search or re.match that allows you to name groups?
(?P< name > pattern)
Create a regex that finds pat1 if is followed by pat2?
pat1(?=pat2)
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
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]
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’
What is the simplest way to parse XML in Python?
Using xml.etree.ElementTree
Given a string JSON–in JSON format–read it into a Python dictionary?
import json
str_dict= json.loads(JSON)
Verify a directory or a file exist?
import os
os.path.exists(directory or file)
Verify myfile is an existing file in your working dir?
import os
os.path.isfile(myfile)
Verify mydir is an existing directory?
os.path.isdir(mydir)
Is myfilename an absolute path?
os.path.isabs(myfilename)
Copy myfile.txt and call it newtext.txt?
import shutil
shutil.copy(‘myfile.txt’, ‘newtext.txt’)
Rename myfile.txt newtext.txt?
import os
os.rename(‘myfile.txt’, ‘newtext.txt’)
Get the full path name for myfile.txt, which is in your current working directory?
os.path.abspath(‘myfile.txt’)
Delete myfile.txt?
os.remove(‘myfile.txt’)
Create the directory, mynewdir?
os.mkdir(‘mynewdir’)
Remove the directory, mynewdir?
os.rmdir(‘mynewdir’)
List the items in mynewdir, which is within the current working directory?
os.listdir(‘mynewdir’)
Switch to mynewdir, which is within the current working directory?
os.chdir(‘mynewdir’)
Find all the files within the current working directory that start with ‘m’?
import glob
glob.glob(“m*”)
What module and object deals with years, months, and days?
datetime.date
What module and object deals with hours, minutes, seconds, and fractions of a second?
datetime.time
What module and object deals with years, months, days, hours, minutes, seconds, and fractions of a second
datetime.datetime
What module and object deals with date or time intervals?
datetime.timedelta
How does the time module deal with time?
As seconds from January 1, 1970.
Convert the time object, mytime, to a string?
time.ctime(mytime)
What method of datetime, date, or time objects, or function from the time module is useful for converting dates and times to strings?
strftime()
What method is useful for converting a string to a time object?
time.strptime()
Create a switch to return VALUE based on POSSIBILITIES?
choices = dict(zip(POSSIBILITES, VALUE))
choices.get(a_possibility, “Default for key error”)