Quiz 2

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

[LC8 - Files,Exception] test_file = open("test.txt",'r') line = test_file.readline() line line.strip() test_file.seek(0)

# "r" means "open for reading" # The readline method reads a single line, including the \n at the end. # readline returns an empty string if there are no more lines in the file. 'Hello World\n' 'Hello World' 0

test_file2 = open("test2.txt",'w')

# "w" means "open for writing"

example) u = np.array([1,2,3]) v = np.array([4,5,6]) np.dot(u,v)

# This is NOT a vector product. u * v array([ 4, 10, 18]) np.sum(u * v) 32 np.dot(u,v) 32

[1,2,3] < [1,2,4] [1,2,3] < [1,2,3,-1] [1,2,3] < [1,2,3,'a'] [1,2,3] < [1,'a',3]

# comparison, element by element (same as for strings) True True True Error: # The entries being compared must be of the same type

some_dictionary = {} some_dictionary = dict()

# create an empty dictionary # alternative way to create an empty dictionary

<Sets> A set is a collection of objects of an arbitrary type (the elements of the set). A set does not contain any duplicate elements. Only one copy of an objects is allowed in the set. The items in the set are stored in no particular order. Sets are not sequences (so you cannot index a set). The keys of a dictionary form a set. More precisely, sets in Python are implemented as dictionaries without values.

# elements are in no particular oder

my_dict = {'a':1, 'answer':42, 3:['x','y']} len(my_dict)

# number of key:value pairs 3

"this,is,a,test".split(",")

# split method for strings returns a list ['this', 'is', 'a', 'test']

u = array([1, 2, 3]) u.shape

# u is a 3x1 array (3,)

import string string.punctuation // import string s = 'A man, a plan, a canal: Panama!' [x for x in s if not x in string.punctuation] // "".join([x for x in s if not x in string.punctuation and not x in string.whitespace])

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' // ['A', ' ', 'm', 'a', 'n', ' ', 'a', ' ', 'p', 'l', 'a', 'n', ' ', 'a', ' ', 'c', 'a', 'n', 'a', 'l', ' ', 'P', 'a', 'n', 'a', 'm', 'a'] // 'AmanaplanacanalPanama'

Unpacking Tuples and Lists person = ('Jane','Doe', 21) first, last, age = person first last age

'Jane' 'Doe' 21

li = ["a","b","c"] ",".join(li)

'a,b,c'

l1 = [3,1,2] min(l1) max(l1) max("some test string") min("some test string")

1 3 t blank space (' ')

[LC7 - List and Tuples] : Never modify a list while you iterate through it a_list = [1,2,'a',3.14159] for e in a_list: print(e) a_list.remove(e)

1 a

Square array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) 1. print(square[1:-1]) 2. square[1,0] 3. square[:, 0] 4. square[1:-1, 1:] 5. square[[1,3]] --> 괄호가 2개임, row를 2개 고르면 됨 6. square[:,[1,3]]

1. [[ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] 2. 5 3. array([ 0, 5, 10, 15, 20]) 4. array([[ 6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19]]) 5. array([[ 5, 6, 7, 8, 9], [15, 16, 17, 18, 19]]) 6. array([[ 1, 3], [ 6, 8], [11, 13], [16, 18], [21, 23]])

1. square % 2 2. m = square % 2 == 0

1. array([[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]) 2. array([[ True, False, True, False, True], [False, True, False, True, False], [ True, False, True, False, True], [False, True, False, True, False], [ True, False, True, False, True]],dtype=bool)

a=np.array(range(25)) # create 1D array and reshape. 1. print(a) 2. print(a.shape) square = a.reshape(5,5) 3. print(square.shape) 4. square

1. [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24] 2. (25,) 3. (5, 5) 4. array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])

data = [3.5, 2.5, 3.55, 4.0, 4.0] sum(data)

17.55

Computing the median data = [3.5, 2.5, 3.55, 4.0, 4.0] sorted(data)[len(data)//2] or def median(l): sorted_l = sorted(l) if len(l) % 2 == 1: return sorted_l[len(l)//2] else: first = sorted_l[len(l)//2-1] second = sorted_l[len(l)//2] return (first + second) / 2

3.55

l = [1,0,0,1,1,1,0,1,0,2] l.count(0)

4

[LC14 - Recursion] Recursion def fun(n): ... subresult = fun(n-1) return ...

A recursive function is simply a function that calls itself

Class and Instance ex) my_book = LibraryBook() LibraryBook() is Class my_book is Instance of LibraryBook Class isinstance(my_book, LibraryBook) -> True

Classes are blueprints for instances. The relationship between a class and an instance is similar to the one between a cookie cutter and a cookie. A single cookie cutter can make any number of cookies. The cutter defines the shape of the cookie. The cookies are edible, but the cookie cutter is not. To create an instance from a class, simply "call" the name of the class. This looks like a function call, but instead it creates a new instance.

def average(li): return sum(li) / len(li) float("{:.2f}".format(average(data))) round(average(data), 2)

Computing the average 3.51 3.51

<Instance Attributes> 1. Data fields. 2. Methods * Method definitions look like function definitions, but they happen inside a class definition. They always have a special self parameter that is automatically bound to the instance when the method is called.

Each instance owns its own data (the class can define what names the data fields have). // containing the functionality of the object. These are defined in the class.

l1 = [1,2,3] l2 = [1,2,3] l1 is l2

False

Fibonacci Arithmetic(+) Sequence with normal loop def fib(n): if n == 0 or n == 1: return 1 fiba = 1 fibb = 1 for i in range(2,n+1): nextfib = fiba + fibb fiba = fibb fibb = nextfib return nextfib

Fibonacci Arithmetic(+) Sequence with recursion def fib(n): if n == 0 or n == 1: return 1 return fib(n-1) + fib(n-2)

test_file = open("test.txt",'r') line = test_file.readline() while line!='': print(line.strip()) line = test_file.readline()

Hello World line 2 line 3

[LC10 - List comprehension] A comprehension is a compact way to construct a new collection by performing an operation on all elements of an iterator.

The basic syntax for a list comprehension is [expression for-name-in-...]

As for lists, you can use a boolean expression with in to check for membership. This is a lot more efficient with a dictionary. 'a' in my_dict 'c' in my_dict

True False

[LC 9 : Dictionaries and Sets] Dictionaries are collections of items, but unlike lists or tuples, they are not sequences. Instead, think of a dictionary as a collection of (key:value) pairs. The keys in the dictionary are unique (there is a set of keys), but the values may not be.(values can be overwritten)

You can write a dictionary literal as a list of key:value pairs surrounded by {}. Keys and values are separated by :. contacts = {'bill':'353-1234', 'rich':'269-1234', 'jane':'352-1234'} contacts['bill'] --> '353-1234'

list("hello")

['h', 'e', 'l', 'l', 'o']

for row in square: print(row, type(row), row.shape)

[0 1 2 3 4] <class 'numpy.ndarray'> (5,) [5 6 7 8 9] <class 'numpy.ndarray'> (5,) [10 11 12 13 14] <class 'numpy.ndarray'> (5,) [15 16 17 18 19] <class 'numpy.ndarray'> (5,) [20 21 22 23 24] <class 'numpy.ndarray'> (5,)

l3 = [4,2,1,6,1,2,3,0,1,9] l3.sort() #Method

[0, 1, 1, 1, 2, 2, 3, 4, 6, 9]

result = [] for i in range(20): result.append(i) result // result = [i for i in range(20)]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Lists are mutable. l1 = [1,2,3] l2 = [4,5,6] l3 = l1 + l2

[1, 2, 3, 4, 5, 6]

data = [4.0, 3.5, 4.0, 2.5, 3.55] data[:len(li)//3+1]

[4.0, 3.5]

[[i,i**2,i**3] for i in range(10) if i%2 == 0]

[[0, 0, 0], [2, 4, 8], [4, 16, 64], [6, 36, 216], [8, 64, 512]]

You can use a for loop to iterate through the keys of the dictionary. Note that you cannot expect these to be in any particular order! for k in my_dict: print(k)

a answer 3

Each item is a tuple, so we can use unpacking! for k,v in my_dict.items(): print(k,'->',v)

a -> 1 answer -> 42 3 -> ['x', 'y']

np.zeros((5,5))

array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]])

np.ones((3,3,3)) np.sum(np.ones((3,3,3))) sum(np.ones((3,3,3)))

array([[[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]]) // 27.0 // array([[ 3., 3., 3.], [ 3., 3., 3.], [ 3., 3., 3.]])

np.ones((3,3,3,3))

array([[[[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]], [[[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]], [[[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]], [[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]]])

Union / Intersection / Difference a = {1,2,3} b = {2,3,4} c = a.intersection(b) c = a.union(b) c = a.difference(b)

c = {2, 3} (c = a & b 이 기호를 써도 됨) {1, 2, 3, 4} (c = a | b 이 기호를 써도 됨) {1}

b_list = a_list[:] #this creates a COPY of a_list

copy를 만들면 a의 값이 바뀌어도 b에 변화가 없다. 근대 그냥 '=' 로 해놓으면 a의 값이 변하면 b의 값도 따라 변한다

One thing to remember is that view objects do not contain a copy of the dictionary, so if the dictionary changes, so does the view. my_dict dict_items = my_dict.items() print(dict_items) my_dict['greeting'] = 'hello' for x in my_dict: print(x) for (k,v) in dict_items: print(k,v)

dict_items([('a', 1), ('answer', 42), (3, ['x', 'y'])]) a answer 3 greeting a 1 answer 42 3 ['x', 'y'] greeting hello

How would you iterate through the values of the dictionary? for k in my_dict: print(my_dict[k]) for k in my_dict: print(k,'->',my_dict[k]) Another option is to use a 'view' object obtained using the keys(), values(), or items() method. my_dict.keys() for k in my_dict.keys(): print(k) for v in my_dict.values(): print(v) for item in my_dict.items(): print(item)

for item in my_dict.items(): print(item) --> ('a', 1) ('answer', 42) (3, ['x', 'y'])

[LC 11 - Object Oriented Programming] 'dir'

function that lists all of the attributes of the class/object (methods and names of the value)

[(x,y) for x in [1,2,3] for y in 'abcd'] // for x in [1,2,3]: for y in 'abcd': result.append((x,y))

same result

import random random.shuffle(data)

shuffle a data in the list

<Python Special Methods> __init__(self, ...) method, ex) def __init__(self, title, author, pub_year, call_no): self.title = title self.author = author self.year = pub_year self.call_number = call_no self.checked_out = False def title_and_author(self): return "{} {}: {}".format(self.author[1], self.author[0], self.title)

that is automatically called by Python when a new instance is created. This method is called the class' constructor Instead of setting data fields from outside once the instance has been created (like we did above; this is considered bad style), we usually want to pass some initial data to the instance when it is created.

okay = False while not okay: try: x = input("please type an integer number:") x_int = int(x) f = open("weljhwer.txt",'r') okay = True except ValueError: print("{} is not an integer. Try again.".format(x)) except FileNotFoundError: print("File not found.")

try-except construct example

try-except construct try: f = open("somefile.txt",'r') print("Opened file correctly.") except FileNotFoundError: print("Sorry, file did not exist.")

try-except construct example

Another useful method is __str__

which is used to convert the instance into a string, for example when it is printed, or when the str() built-in function is applied to the instance.

The empty list evaluates to False in a boolean context x = [] if x: print("x is not empty") else: print("x is empty") // [] or 3

x is empty // 3

fruit_to_color = {'banana':'yellow','lemon':'yellow','blueberry':'blue','cherry':'red'} fruit_to_color // {fruit_to_color[k]:[fruit for fruit in fruit_to_color if fruit_to_color[fruit]==fruit_to_color[k]] for k in fruit_to_color}

{'banana': 'yellow', 'blueberry': 'blue', 'cherry': 'red', 'lemon': 'yellow'} // {'blue': ['blueberry'], 'red': ['cherry'], 'yellow': ['banana', 'lemon']}

[Dictionary Comprehension] s = "abcde" list_of_tuples = [(i,s[i]) for i in range(len(s))] list_of_tuples dict(list_of_tuples)

{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

[LC17 - numpy] Numpy is a package for numeric computing in python. import numpy as np # common convention u = np.array([1,2,3]) v = np.array([4,5,6]) np.dot(u,v)

행렬 계산할 때 쓰는 package print(u) [1 2 3] list랑 다름, list는 [1,2,3] 콤마가 있다 Numpy arrays are very similar to Python lists. Indexing and slicing works the same way (including assingments). Unlike a Python list, all cells in the same array must contain the same data type. Operators don't work the same for lists and arrays and there are many additional methods defined on them.


Ensembles d'études connexes

FINAL A&P Chapters 12 & 13 MAYBE

View Set

Chapter 18: The Impacts of Government Borrowing

View Set

Individual Life Insurance Contract - Provisions and Options

View Set

Geo 101 ch.2 video quiz: plate tectonics explained

View Set

Anatomy Mid Term Open Ended Study Guide

View Set