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
Q

For regular expressions, what does + represent?

A

Occurs one or more times

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

For regular expressions, what does * represent?

A

Occurs zero or more times.

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

For regular expressions, what does ? represent?

A

Once or none.

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

For regular expressions, what does {3} represent?

A

Occurs exactly 3 times.

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

For regular expressions, what does {2,4} represent?

A

Ocucurs 2 to 4 times.

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

For regular expressions, what does {3,} represent?

A

Occurs 3 or more times.

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

For regular expressions, what does | represent?

A

Or

re. search(r”man|woman”,”This man was here.”)
re. search(r”man|woman”,”This woman was here.”)

32
Q

For regular expressions, what does a . represent?

A

A wildcard

33
Q

What module is used to time your code?

A

timeit

34
Q

How do you import timeit?

A

import timeit

35
Q

What are the three pieces needed to use timeit()

A

* 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
Q

What is the Jupyter ‘magic’ method to time your code.

A

%%timeit
func_one(100)

37
Q

What module needs to be imported to zip files?

A

import zipfile

38
Q

What is the first step to zip a file?

A

Create a zip file.

comp_file = zipfile.ZipFile(‘comp_file.zip’, ‘w’)

39
Q

What is the second step to zip a file?

A

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
Q

What is the final step when zipping a file?

A

close the zip file

comp_file.close()

41
Q

What module would you use to archive a folder?

A

shutil

42
Q

How do you zip an entire folder?

A

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
Q

How do you un-zip a zip archive?

A

shutil.unpack_archive(output_filename, dir_for_extract_result, ‘zip’)

44
Q

How do you import the datetime module?

A

import datetime

45
Q

How do I use the datetime module?

A

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
Q

How do you check the minimum, maximum, and resolution of the time?

A

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
Q

How do you use datetime to find the current day?

A

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
Q

How do you use replace() to create a date instance?

A

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
Q

A simple use of arithmetic with datetime?

A
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
Q

How do you import the math module?

A

import math

51
Q

How do you find help with the math module?

A

help(math)

52
Q

What are the three ways to round a number?

A

value = 4.35

  • *math.floor**(value) #4
  • *math.ceil**(value) #5
  • *round**(value) #4
53
Q

Is round() part of the math module?

A

No

54
Q

What are the math constants in the math module?

A

math. pi #3.141592653589793
math. e #2.718281828459045
math. tau #6.283185307179586
math. inf #inf
math. nan #nan

55
Q

What does the log() function look like?

A

Log Base e
math.log(math.e) # 1

56
Q

What is the default base of log()?

A

e

math. log(10) # 2.302585092994046
math. e ** 2.302585092994046 # 10.000000000000002

57
Q

How do you use a custom base with log()?

A

math. log(x,base)
* math.log(100,10) # 2.0*

58
Q

How do you find the sine of a number using the math module?

A

Radians

math.sin(10)

59
Q

By default does the math module use degrees or radians?

A

radians

60
Q

How do you convert to degrees using the math module?

A

math.degrees(pi/2) # 90.0

61
Q

How do you convert to radians using the math module?

A

math.radians(180) # 3.141592653589793

62
Q

With the Random module, what does the seed do?

A

We can even set a seed to produce the same random set every time.

63
Q

How do you set the seed of the random function?

A

The value 101 is completely arbitrary, you can pass in any number you want

random.seed(101)

64
Q

Using the random module, how do you “sample with replacement”?

A

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
Q

Using the random module, how do you “sample without replacement”?

A

[17, 19, 11, 14, 1, 3, 4, 10, 5, 15]

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)

66
Q

Using the random module, how do you shuffle a list?

A

Don’t assign this to anything!

random.shuffle(mylist)

67
Q

Using the random module, how do you create a random distribution?

A

Continuous, random picks a value between a and b, each value has equal change of being picked.

random.uniform(a=0,b=100)

68
Q

How do you import the Python debugger?

A

import pdb

69
Q

What is the most important Python debugger function?

A

Set a trace using Python Debugger
pdb.set_trace()

70
Q

How do you import regular expressions into Python?

A

import re

71
Q

Using regular expressions how do you find the word ‘phone’ in a sentence?

A

text = “The person’s phone number is 408-555-1234. Call soon!”

import re

pattern = ‘phone’

re.search(pattern, text)

72
Q

Using regular expressions, how do you display just the span of what you are searching for?

A

match.span() # (13, 18)

73
Q

Using regular expressions, how do you display just the start of what you are searching for?

A

match.start() # 13

74
Q

Using regular expressions, how do you display just the end of what you are searching for?

A

match.end() # 18

75
Q

Using regular expressions, if there is more than one result for what is being searched for, how do you return all of the results?

A

matches = re.findall(“phone”, text)

returns a list of found items.

76
Q

Using regular expressions, how do iterate all the results?

A

for match in re.finditer(“phone”,text):
print(match.span())

(3, 8)
# (18, 23)