Don't wanna be here? Send us removal request.
Text
Testing and Debugging
--Document assumptions behind code design.(Kodu yazarken neden yazdigini, bu kodu yazarken hangi sonuclari bekledigini yazmayi aliskanlik haline getirmelisin.)
--Write your program as a modules and start testing unit by unit.
--Backup your code and after change and test the new version of it
DEBUGGING steep learning curve goal is to have a bug-free program tools • built in to IDLE and Anaconda • Python Tutor • print statement • use your brain, be systematic in your hunt
ERROR MESSAGES - EASY trying to access beyond the limits of a list test = [1,2,3] then test[4] IndexError trying to convert an inappropriate type int(test) TypeError referencing a non-existent variable a NameError mixing data types without appropriate coercion '3'/4 TypeError forgetting to close parenthesis, quotation, etc. a = len([1,2,3] print a SyntaxError
Exceptions
have separate except clauses to deal with a particular type of exception try: a = int(input("Tell me one number: ")) b = int(input("Tell me another number: ")) print("a/b = ", a/b) print("a+b = ", a+b) except ValueError: print("Could not convert to a number.”) except ZeroDivisionError: print("Can't divide by zero”) except: print("Something went very wrong.”)
OTHER EXCEPTIONS else: • body of this is executed when execution of associated try body completes with no exceptions finally: • body of this is always executed after try, else and except clauses, even if they raised another error or executed a break, continue or return • useful for clean-up code that should be run no matter what else happened (e.g. close a file)
EXCEPTIONS AS CONTROL FLOW
don’t return special values when an error occurred and then check whether ‘error value’ was returned instead, raise an exception when unable to produce a result consistent with function’s specification raise () raise ValueError("something is wrong")
6.00.1X LECTURE 2
0 notes
Text
DICTIONARIES
(6.00.1X)
Dictionaries store pairs of data:
--keys:
• must be unique
• immutable type (int, float, string, tuple,bool)
• actually need an object that is hashable, but think of as immutable as all immutable types are hashable
• careful with float type as a key
no order to keys or values! d = {4:{1:0}, (1,3):"twelve", 'const':[3.14,2.7,8.44]}
--values:
• any type (immutable and mutable)
• can be duplicates
• dictionary values can be lists, even other dictionaries!
We can create dictionaries:
-- my_dict = {} -- this is an empty dictionary'
-- grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'} --ex of a dict...
**add an entry: grades['Sylvan'] = 'A'
**test if key in dictionary: 'John' in grades returns True
'Daniel' in grades returns False
**delete entry: del(grades['Ana'])
**get an iterable that acts like a tuple of all keys(no guaranteed order) :
grades.keys() returns ['Denise','Katy','John','Ana']
grades.values() returns ['A', 'A', 'A+', 'B']
CREATING A DICTIONARY
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
USING THE DICTIONARY
def most_common_words(freqs):
values = freqs.values()
best = max(values)
words = [ ]
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
LEVERAGING DICTIONARY PROPERTIES
def words_often(freqs, minTimes):
result = []
done = False
while not done:
temp = most_common_words(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w])
else:
done = True
return result
print(words_often(beatles, 5))
FIBONACCI WITH A DICTIONARY
def fib_efficient(n, d):
if n in d:
return d[n]
else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)
d[n] = ans
return ans
d = {1:1, 2:2}
print(fib_efficient(6, d))
GLOBAL VARIABLES
can be dangerous to use
◦ breaks the scoping of variables by function call
◦ allows for side effects of changing variable values in ways that affect other computation
but can be convenient when want to keep track of information inside a function
example – measuring how often fib and fib_efficient are called
0 notes
Text
The Derivative
(MITx 18.01.1x)
Derivatives are all about rates of change.
--average rate of change of f(x) with respect to x, from x=a to x=b --Δf/Δx = (f(b)-f(a)) / (b-a)
--instantaneous rate of change = The Derivative of f(x) at x=a = the limit as b approaches a. and that's the derivative. = the limit as b approaches (f(b)-f(a)) / (b-a) = f ´ (a)
0 notes
Text
TUPLES
(MITx - 6.00.1x)
-Can mix element types.
-immutable
-represented with parentheses
te = () #creates empty tuple
t = (2, “one”, 3) #creates 3 mixed type elements tuple
(2, “one”, 3) + (5, 6) # we can concenate tuples like strings
t[1:2] #slice tuple (”one”,) comme in the parentheses shows us its a tuple.
-can swap values # (x, y) = (y, x)
example:
def quotient_and_remainder(x,y):
q = x // y
r = x % y
return (q, r)
(quot , rem) = quotient_and_remainder(4, 5)
-can iterate over tuples
example:
aTuple is a tuple of tuples ((int,str) , (int,str) , (int,str) , (int,str) , (int,str) )
def get_data(aTuple):
nums = ()
words = ()
for t in aTuple:
nums = nums + (t[0],)
if t[1] not in words:
words = words + (t[1],)
min_nums = min(nums)
max_nums = max(nums)
unique_words = len(words)
return (min_nums, max_nums, unique_words)
(small, large, words) = get_data(((1, ‘mine’), (3, ‘yours’), (5, ‘ours’), (7, ‘mine’)))
0 notes
Text
Lists
(MITx-6.00.1x)
-- Lists are Python objects.
-- Lists are created using square brackets: L = [ 1, 15, 7]
-- List items can be of any data type but usually homogeneous.
-- The big difference between tuple and list is, list is mutable.
-- To make a list using list() :
lst = list() or lst = [ ] #Making an empty list.
lst = list( (“a”, “b”, “z”)) # Making a list, with double round-brackets.
or we can create lists using square-brackets:
lst = [”a”, “b”, “z”]
-- add elements to end of list -- L.append(element)
-- to combine lists together use concenation, + operator -- L1 + L2
-- mutate list with -- L.extend(some_list)
-- delete element at a specific index -- del(L[index])
-- remove the last element of list -- L.pop()
-- remove a specific element -- L.remove(element)
-- * string to list -- list(string) #returns a list with every character from a string
--to split a string on a character parameter -- s.split(’char’)
--to turn a list of characters into a string -- ‘ ‘.join(L)
-- create a new list clonning an other list -- Lclone = L[ : ]
ex.:
L = [’a’, ‘b’, ‘c’] -- ‘ ‘.join(L) -- returns “abc” or ‘_’.join(L) -- returns “a_b_c”
-- sort a list(mutated) -- L.sort()
--sort a list(not mutated) -- sorted(L)
-to reverse a list -- L.reverse() -- mutates L
** we can make list of lists. -- listoflists = [L , L1 , L2,] or lol = [[1,2],[’a’,’b’,’c’],[1.2.3.4.5.0]] or append a list -- lol.append([4, 5])
--to insert an element to desired index -- list.insert(i, element)
EX 1:
--avoid mutating a list as you are iterating over it , before iteration, clone it:
def remove_dups_new(L1, L2): L1_copy = L1[:] for e in L1_copy: if e in L2: L1.remove(e) L1 = [1, 2, 3, 4] L2 = [1, 2, 5, 6]
remove_dups_new(L1, L2) print(L1)
EX 2:
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
L = [1, -2, 3.4]
applyToEach(L, abs) #[1, 2, 3.4] Apply absolute to each element of the list.
applyToEach(L, int) #[1, 2, 3] Apply int to each element of the list.
applyToEach(L, fact) #[1, 2, 6] Apply factoriel to each element of the list.
applyToEach(L, fib) #[1, 2, 13] Apply fibonacci to each element of the list.
EX 3:
def applyFuns(L, x):
for f in L:
print(f(x))
applyFuns([abs, int, fact, fib], 4)
4, 4, 24, 5
#We have a list of functions and we are applying this list to an integer.
HOP, map
** simple form – a unary function and a collection of suitable arguments
◦ map(abs, [1, -2, 3, -4])
** produces an ‘iterable’, so need to walk down it
for elt in map(abs, [1, -2, 3, -4]):
print(elt)
1, 2, 3, 4
** general form – an n-ary function and n collections of arguments
◦ L1 = [1, 28, 36]
◦ L2 = [2, 57, 9]
for elt in map(min, L1, L2):
print(elt)
1, 28, 9
1 note
·
View note