Course 4: Python for Data Science for AI

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

# Iterate through the lines of a file code

with open(example1,"r") as file1: i = 0; for line in file1: print("Iteration", str(i), ": ", line) i = i + 1;

Consider the tuple tuple1=("A","B","C" ), what is the result of the following operation tuple1[-1]?

"C" the index -1 corresponds to the last element of the tuple

What is the result of the following: Name[0] Name= "Michael Jackson"

"M" The index 0 corresponds to the first index

what is the result of the following say_what[-1] say_what=('say',' what', 'you', 'will')

"Will"

Consider the following list B=[1,2,[3,'a'],[4,'b']], what is the result of the following:B[3][1]

"b"

What is the result of the following: Name[-1] Name= "Michael Jackson"

"n" the index -1 corresponds to the last index

code to sort the tuple Ratings = (0, 9, 6, 5, 10, 8, 9, 6, 2)

# Sort the tuple Ratings = (0, 9, 6, 5, 10, 8, 9, 6, 2) RatingsSorted = sorted(Ratings) RatingsSorted

If we cast a Boolean False to an integer or float, we get

0

If we cast a Boolean False to an integer or float, we get a

0

What is the result of the following code segment:1//2

0 // corresponds to integer division

output of Dict = {"key1": 1, "key2": "2", "key3": [3, 3, 3], "key4": (4, 4, 4), ('key5'): 5, (0, 1): 6} Dict["key1"]

1

# Check the type of the values stored in numpy array code a = ["0", 1, "two", "3", 4]

a.dtype

# Get the size of numpy array a = np.array([0, 1, 2, 3, 4]) a

a.size

ndim

attribute that descrives the array dimension

# Create a numpy array code

b = np.array([3.1, 11.02, 6.2, 213.2, 5.2])

type (True)

bool (short for boolean)

#code to set the fourth element and fifth element to 300 and 400 c = np.array([20, 1, 2, 3, 4])

c[3:5] = 300, 400 c

dataframce

corresponds to rows and columns of data, we can use dictionary to build it

# Slicing the numpy array code c = np.array([20, 1, 2, 3, 4])

d = c[1:4] d

the dir command

dir(RedCircle) used to get a list of the object's methods. Many of them are default Python methods.

How to get a file's name

example1 = "/resources/data/Example1.txt" file1 = open(example1, "r") file1.name

how to get the mode of the file

file1.mode

In Python 3, what is the type of the variable x after the following: x=1/1

float in Python 3, regular division always results in a float

Find the first index of "disco": genres_tuple = ("pop", "rock", "soul", "hard rock", "soft rock", \ "R&B", "progressive rock", "disco")

genres_tuple.index("disco")

Hadamard product

is a binary operation that takes two matrices of the same dimensions and produces another matrix of the same dimension as the operands where each element i, j is the product of elements i, j of the original two matrices.

A Tuple

is a sequence of immutable Python objects. Tuples are sequences, just like lists.

loc

is primarily label based; when two arguments are used, you use column headers and row indexes to select the data you want. loc can also take an integer as a row or column number.

with statement in opening files

it automatically closes the file even if the code encounters an exception. The code will run everything in the indent block then close the file object.

# Get the mean of numpy array a = np.array([1, -1, 1, -1])

mean = a.mean() mean

how would you perform the dot product between the numpy arrays u and v

np.dot(u,v)

# See the content of file code

print(FileContent)

file modes (3)

r Read mode for reading files w Write mode for writing files a for appending

We can use the double slash for integer division, where the result is

rounded

What is the result of the following: type(set([1,2,3]))

set

code to get keys inside soundtrack_dic = {"The Bodyguard":"1992", "Saturday Night Fever":"1977"}

soundtrack_dic.keys()

code to get values inside the dictionary soundtrack_dic = {"The Bodyguard":"1992", "Saturday Night Fever":"1977"}

soundtrack_dic.values()

Difference between typle and list

the tuples cannot be changed unlike lists, and tuples use parentheses, whereas lists use square brackets.

if we cast a Boolean True to an integer or float, we will get

1

what is the radius attribute after the following code block is run: RedCircle=Circle(10,'red') RedCircle.radius=1

1

# Convert list to Numpy Array a = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]

A = np.array(a) A

Aliasing

A circumstance where two or more variables refer to the same object.

# Access the element on the first and second rows and third column

A[0:2, 2]

# Access the element on the first row and first and second columns (slicing) a = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]

A[0][0:2]

REST API

Any API that uses Representational State Transfer (REST), which means that the two programs, on separate computers, use HTTP messages to request and transfer data.

code to change the first value in an array c = np.array([20, 1, 2, 3, 4]) c

c[0] = 100 c

# Verify if the file is closed code

file1.closed

# Write multiple lines to file code

with open('/resources/data/Example2.txt', 'w') as writefile: writefile.write("This is line A\n") writefile.write("This is line B\n")

# Makeup a numpy array within [0, 2π] and 100 elements

x = np.linspace(0, 2*np.pi, num=100)

what is the syntax to clone the list A and assign the result to list B

B=A[:]

# Get the transposed of C C = np.array([[1,1],[2,2],[3,3]])

C.T

how to read the file and assign it to a variable :

FileContent = file1.read() FileContent

Code to create the object RedCircle of type Circle

RedCircle = Circle(10, 'red')

what is the result of the following: 1=2

SyntaxError:can't assign to literal

The method append does the following:

adds one element to a list (method)

linespace function

returns evenly spaced numbers over a specified interval. We specify the starting point of the sequence and the ending point of the sequence. The parameter "num" indicates the Number of samples to generate

head()

reads first 5 rows of data

# Open file using with code

with open(example1, "r") as file1: FileContent = file1.read() print(FileContent)

# Numpy Array Multiplication by 2 y = np.array([1, 2])

z = 2 * y

# Write the strings in a list to text file code

Lines = ["This is line A\n", "This is line B\n", "This is line C\n"] Lines with open('Example2.txt', 'w') as writefile: for line in Lines: print(line) writefile.write(line)

Nest tuple example

NestedT =(1, 2, ("pop", "rock") ,(3,4),("disco",(1,2)))

# Multiply X with Y (2 dim arrays) Y = np.array([[2, 1], [1, 2]]) X = np.array([[1, 0], [0, 1]])

Z = X * Y Z

# Add X and Y 2 dimentional arrays Y = np.array([[2, 1], [1, 2]]) X = np.array([[1, 0], [0, 1]])

Z = X + Y Z

# Calculate the dot product of A and B (two dimentional arrays)

Z = np.dot(A,B) Z

Typecasting

a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function.

# Acces the value of pie

np.pi

what is the type of the following array: a=np.array([0,1,7,3, 7])

numpy.ndarray

what are the keys of the following dictionary: {"a":1,"b":2}

"a","b"

iloc

is integer-based. You use column numbers and row numbers to get rows or columns at particular positions in the data frame.

# Calculate the dot product

np.dot(u, v)

# Makeup a numpy array within [-2, 2] and 5 elements

np.linspace(-2, 2, num=5)

What is the length of the list A = [1] after the following operation: A.append([2,3,4,5])

2 Append only adds one element to the list .

consider the numpy array u how would you multiply each element in the numpy array by 2

2*u

What is the result of the following: int(3.99)

3 In Python, if you cast a float to an integer, the conversion truncates towards zero, i.e.you just get rid of the numbers after the decimal place. So for 3.99 you just get rid of the ".99" leaving 3.

What is the output of the following: print("AB\nC\nDE")

AB C DE when the print function encounters a \n it displays a new line

how to close a file

file1.close()

# Create a constant to numpy array u = np.array([1, 2, 3, -1])

u + 14

Consider the following tuple A=(1,2,3,4,5), what is the result of the following:A[1:4]:

(2, 3, 4)

Consider the following Python Dictionary: Dict={"A":1,"B":"2","C":[3,3,3],"D":(4,4,4),'E':5,'F':6} What is the result of the following operation: Dict["D"]

(4, 4, 4)

# Plot numpy arrays

Plotvec1(u, z, v)

# Write line to file code

with open('/resources/data/Example2.txt', 'w') as writefile: writefile.write("This is line A")

#copy the file Example2.txt to the file Example3.txt code

with open('Example2.txt','r') as readfile: with open('Example3.txt','w') as writefile: for line in readfile: writefile.write(line)

# Read all lines and save as a list code

with open(example1, "r") as file1: FileasList = file1.readlines()

# Read one line code

with open(example1, "r") as file1: print("first line: " + file1.readline())

# Read first four characters of a file code

with open(example1, "r") as file1: print(file1.read(4))

What is the result of the following operation: '1,2,3,4'.split(',')

['1','2','3','4']

What is the result of the following operation: 11//2

5 the symbol // means integer value. Therefore you must round the result down.

Consider the following tuple A=(1,2,3,4,5), what is the result of the following: len(A)

5 The function len returns the number of items of a tuple.

What is the result of the following operation 3+2*2?

7 Python follows the standard mathematical conventions

In Python, if you executed name = 'Lizz', what would be the output of print(name[0:2])?

Li

sorted vs sort

The primary difference between the list sort() function and the sorted() function is that the sort() function will modify the list it is called on. The sorted() function will create a new list containing a sorted version of the list it is given. ... The sort() function modifies the list in-place and has no return value.

Consider the following set: {"A","A"}, what will the result be when the set is created

{"A"} there are no duplicate values in a set

what is the result of the following operation : {'a','b'} &{'a'}

{'a'}

read_excel

function that reads excel files

What is the result of the following: "Hello Mike".split()

["Hello","Mike"] The method split separates a string into a list based on the argument. If there is no argument as in this case the string is split using spaces.

Consider the tuple A=((11,12),[21,22]), that contains a tuple and list. What is the result of the following operation A[1]:

[21,22] the index 1 corresponds to the second element in the tuple, which contains another list.

if statement syntax

if test expression: statement(s)

# Get the biggest value in the numpy array a = np.array([1, -1, 1, -1])

max_b = b.max() max_b

code to convert the list ['rap','house','electronic music', 'rap'] to a set

set(['rap','house','electronic music','rap'])

df

short for data frames

pd

short for pandas

# Write a new line to text file with append

with open('/resources/data/Example2.txt', 'a') as testwritefile: testwritefile.write("This is line C\n")

# Read file to test if the writing worked

with open('/resources/data/Example2.txt', 'r') as testwritefile: print(testwritefile.read())

# Verify if the new line is in the text file code

with open('/resources/data/Example2.txt', 'r') as testwritefile: print(testwritefile.read())

# Calculate the production of two numpy arrays u = np.array([1, 2]) v = np.array([3, 2])

z = u * v

# Numpy Array Addition u = np.array([1, 0]) v = np.array([0, 1])

z = u + v z

In Python, if you executed var = '01234567', what would be the result of print(var[::2]).

0246 a stride value of 2 selects even elements

# Get the number of dimensions of numpy array a = np.array([0, 1, 2, 3, 4]) a

a.ndim

# Get the shape/size of numpy array a = np.array([0, 1, 2, 3, 4]) a

a.shape

Code to find out if album_set1 is a subset of album_set3

album_set1.issubset(album_set3)

Create a new set album_set3 that is the union of album_set1 and album_set2

album_set3 = album_set1.union(album_set2) album_set3 or album_set3 = album_set1 & (album_set2) album_set3


Ensembles d'études connexes

AP WORLD EXAM PRACTICE QUESTIONS BOOK

View Set

Biceps Brachii, Triceps, and Coracobrachialis

View Set

Chapter 6 Project Manager: Time Management

View Set

Cell and Transportation Mechanisms

View Set