14. Advanced Python Modules Flashcards

1
Q

How do you import counter()

A

from collections import Counter

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

What does Counter() do?

A

Counter is a dict subclass which helps count hashable objects. Inside of it elements are stored as dictionary keys and the counts of the objects are stored as the value.

lst = [1,2,2,2,2,3,3,3,1,2,1,12,3,2,32,1,21,1,223,1]

  • *Counter(lst)**
  • *Counter({1: 6, 2: 6, 3: 4, 12: 1, 21: 1, 32: 1, 223: 1})**
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you import defaultdict()?

A

from collections import defaultdict

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

What does defaultdict() do?

A

defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory) as a default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.

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

Does Defaultdict() ever create an error?

A

no

A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

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

What does defaultdict() look like?

A

d is empty but no error is created

d = defaultdict(object)

d[‘one’]

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

How do you import a namedtuple?

A

from collections import namedtuple

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

What does a namedtuple look like?

A

Dog = namedtuple(‘Dog’, [‘age’,’breed’,’name’])

sam = Dog(age=2,breed=’Lab’,name=’Sammy’)

frank = Dog(age=2,breed=’Shepard’,name=”Frankie”)

so:

sam
Dog(age=2, breed=’Lab’, name=’Sammy’)
sam.age
2

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

How do you create a file?

A

f = open(‘practice.txt’, ‘w+’)

f. write(‘test’)
f. close()

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

How do you get the current directory?

A
  • *import os
    os. getcwd()**

So, for example:
‘C:\Users\Marcial\Pierian-Data-Courses\Complete-Python-3-Bootcamp\12-Advanced Python Modules’

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

How do you list files in a directory?

A

import os

In your current directory
os.listdir()

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

How do you list files in a specific directory?

A

os.listdir(“C:\Users”)

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

How do you move a file?

A

import shutil

shutil.move(‘practice.txt’,’C:\Users\Marcial’)

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

How do you list files in a directory?

A

In your current directory

os.listdir()

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

How do you list files in a specific directory

A

os.listdir(“C:\Users”)

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

How do you delete a file?

A

import send2trash

send2trash.send2trash(‘practice.txt’)

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

How do you walk through a directory?

A

for folder , sub_folders , files in os.walk(“Example_Top_Level”):

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

For regular expressions, what does \d represent?

A

A digit

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

For regular expressions, what does \w represent?

A

Alphanumeric

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

For regular expressions, what does \s represent?

A

White space

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

For regular expressions, what does \D represent?

A

a non digit

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

For regular expressions, what does \W represent?

A

Non-alphanumeric

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

For regular expressions, what does \S represent?

A

non-whitespace

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

For regular expressions, what is a quantifier?

A

+ {n} * ?

where n is some number.

Now that we know the special character designations, we can use them along with quantifiers to define how many we expect.

Character Description Example Pattern Code Exammple Match
+ Occurs one or more times Version \w-\w+ Version A-b1_1

{3} Occurs exactly 3 times \D{3} abc

{2,4} Occurs 2 to 4 times \d{2,4} 123

{3,} Occurs 3 or more \w{3,} anycharacters

* Occurs zero or more times A*B*C* AAACC

? Once or none

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
For regular expressions, what does + represent?
**Occurs one or more times**
26
For regular expressions, what does \* represent?
**Occurs zero or more times.**
27
For regular expressions, what does ? represent?
**Once or none.**
28
For regular expressions, what does {3} represent?
**Occurs exactly 3 times.**
29
For regular expressions, what does {2,4} represent?
**Ocucurs 2 to 4 times.**
30
For regular expressions, what does {3,} represent?
**Occurs 3 or more times.**
31
For regular expressions, what does | represent?
**Or** re. search(r"man|woman","This man was here.") re. search(r"man|woman","This woman was here.")
32
For regular expressions, what does a **.** represent?
**A wildcard**
33
What module is used to time your code?
**timeit**
34
How do you import timeit?
**import timeit**
35
What are the three pieces needed to use timeit()
**\* the setup of the function to be timed.** It needs to be in a string format: setup = ''' def func\_one(n): return [str(num) for num in range(n)] ''' **\* The statement name.** Also needs to be in a string format: stmt = 'func\_one(100)' **\* The number of times to test the function** number=100000 The end product: timeit.timeit(stmt, setup, number=100000)
36
What is the Jupyter 'magic' method to time your code.
**%%timeit** func\_one(100)
37
What module needs to be imported to zip files?
**import zipfile**
38
What is the first step to zip a file?
**Create a zip file.** comp\_file = zipfile.ZipFile('comp\_file.zip', 'w')
39
What is the second step to zip a file?
**Move the file into the already created zip file, and zip the file while doing this.** comp\_file.write("new\_file.txt",compress\_type=zipfile.ZIP\_DEFLATED)
40
What is the final step when zipping a file?
**close the zip file** comp\_file.close()
41
What module would you use to archive a folder?
**shutil**
42
How do you zip an entire folder?
**import shutil** **Save to a variable the file path of directory to be zip** directory\_to\_zip='C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Bootcamp\\12-Advanced Python Modules' **Save name of archieve to a variable** output\_filename = 'example' **#use the function: shutil.make\_archive()** Note this won't run as is because the variable are undefined shutil.make\_archive(output filename, 'zip', directory\_to\_zip)
43
How do you un-zip a zip archive?
**shutil.*unpack\_archive*(output\_filename, dir\_for\_extract\_result, 'zip')**
44
How do you import the datetime module?
**import datetime**
45
How do I use the datetime module?
import datetime **t = datetime.time(4, 20, 1)** Let's show the different components print(t) print('hour :', t.hour) print('minute:', t.minute) print('second:', t.second) print('microsecond:', t.microsecond) print('tzinfo:', t.tzinfo) So: 04:20:01 hour : 4 minute: 20 second: 1 microsecond: 0 tzinfo: None Note: A time instance only holds values of time, and not a date associated with the time.
46
How do you check the minimum, maximum, and resolution of the time?
*print('Earliest :', **datetime.time.min**)* *print('Latest :', **datetime.time.max**) print('Resolution:', **datetime.time.resolution**)* So: Earliest : 00:00:00 Latest : 23:59:59.999999 Resolution: 0:00:00.000001 The min and max class attributes reflect the valid range of times in a single day.
47
How do you use datetime to find the current day?
**today = datetime.date.today()** print(today) print('ctime:', today.ctime()) print('tuple:', today.timetuple()) print('ordinal:', today.toordinal()) print('Year :', today.year) print('Month:', today.month) print('Day :', today.day) So: 2020-06-10 ctime: Wed Jun 10 00:00:00 2020 tuple: time.struct\_time(tm\_year=2020, tm\_mon=6, tm\_mday=10, tm\_hour=0, tm\_min=0, tm\_sec=0, tm\_wday=2, tm\_yday=162, tm\_isdst=-1) ordinal: 737586 Year : 2020 Month: 6 Day : 10
48
How do you use replace() to create a date instance?
d1 = datetime.date(2015, 3, 11) print('d1:', d1) *d2 = d1.**replace(year=1990)*** print('d2:', d2) So: d1: 2015-03-11 d2: 1990-03-11
49
A simple use of arithmetic with datetime?
``` d1 = datetime.date(2015, 3, 11) d2 = datetime.date(1990, 3, 11) ``` **d1 - d2** So: datetime.timedelta(9131) This gives us the difference in days between the two dates. You can use the timedelta method to specify various units of times (days, minutes, hours, etc.)
50
How do you import the math module?
**import math**
51
How do you find help with the math module?
**help(math)**
52
What are the three ways to round a number?
value = 4.35 * *math**.**floor**(value) #4 * *math**.**ceil**(value) #5 * *round**(value) #4
53
Is round() part of the math module?
**No**
54
What are the math constants in the math module?
math. pi #3.141592653589793 math. e #2.718281828459045 math. tau #6.283185307179586 math. inf #inf math. nan #nan
55
What does the log() function look like?
Log Base e **math.log(math.e) # 1**
56
What is the default base of log()?
e math. log(10) # 2.302585092994046 math. e \*\* 2.302585092994046 # 10.000000000000002
57
How do you use a custom base with log()?
math. log(x,base) * math.log(100,**10**) # 2.0*
58
How do you find the sine of a number using the math module?
Radians **math.sin(10)**
59
By default does the math module use degrees or radians?
**radians**
60
How do you convert to degrees using the math module?
**math.degrees(pi/2)** # 90.0
61
How do you convert to radians using the math module?
**math.radians(180)** # 3.141592653589793
62
With the Random module, what does the seed do?
**We can even set a seed to produce the _same_ random set every time.**
63
How do you set the seed of the random function?
The value 101 is completely arbitrary, you can pass in any number you want **random.seed(101)**
64
Using the random module, how do you "sample with replacement"?
Take a sample size, allowing picking elements more than once. Imagine a bag of numbered lottery balls, you reach in to grab a random lotto ball, then after marking down the number, you place it back in the bag, then continue picking another one. **random._choices_(population=mylist,k=10)** [15, 14, 17, 8, 17, 2, 19, 17, 6, 1]
65
Using the random module, how do you "sample without replacement"?
Once an item has been randomly picked, it can't be picked again. Imagine a bag of numbered lottery balls, you reach in to grab a random lotto ball, then after marking down the number, you leave it out of the bag, then continue picking another one. **random._sample_(population=mylist,k=10)** #[17, 19, 11, 14, 1, 3, 4, 10, 5, 15]
66
Using the random module, how do you shuffle a list?
Don't assign this to anything! **random._shuffle_(mylist)**
67
Using the random module, how do you create a random distribution?
Continuous, random picks a value between a and b, each value has equal change of being picked. **random._uniform_(a=0,b=100)**
68
How do you import the Python debugger?
**import pdb**
69
What is the most important Python debugger function?
Set a trace using Python Debugger pdb.set\_trace()
70
How do you import regular expressions into Python?
**import re**
71
Using regular expressions how do you find the word 'phone' in a sentence?
text = "The person's phone number is 408-555-1234. Call soon!" import re pattern = 'phone' **re.search(pattern, text)**
72
Using regular expressions, how do you display just the span of what you are searching for?
**match.span()** # (13, 18)
73
Using regular expressions, how do you display just the start of what you are searching for?
**match.start**() # 13
74
Using regular expressions, how do you display just the end of what you are searching for?
**match.end()** # 18
75
Using regular expressions, if there is more than one result for what is being searched for, how do you return all of the results?
**matches = re._findall_("phone", text)** returns a list of found items.
76
Using regular expressions, how do iterate all the results?
**for match in re._finditer_("phone",text):** print(match.span()) ``` (3, 8) # (18, 23) ```