From 359562785b242410cfb3072a2cc743125a66e3ef Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Sun, 16 Nov 2014 17:11:06 -0800 Subject: [PATCH 1/7] Session 6 Homework. --- Students/salim/notes/class_notes.py | 22 +++++++++++++++++-- Students/salim/session06/html_render.py | 10 +++++++++ .../salim/session06/lambda_keyword_lab.py | 5 +++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 Students/salim/session06/html_render.py create mode 100644 Students/salim/session06/lambda_keyword_lab.py diff --git a/Students/salim/notes/class_notes.py b/Students/salim/notes/class_notes.py index d134a7dc..ce619f7b 100644 --- a/Students/salim/notes/class_notes.py +++ b/Students/salim/notes/class_notes.py @@ -649,7 +649,7 @@ def func(c, list=[]): # this is wrong because it dones't create a function le return list.append(c) -############################## SESSION03 ############################## +############################## SESSION04 ############################## """ you almost never have to loop through sequences using range() - zip() will zip lists together @@ -742,7 +742,7 @@ def sort_key(item): -############################## SESSION04 ############################## +############################## SESSION05 ############################## """ dealing with "ordered" / "sorted" dicts """ @@ -794,3 +794,21 @@ def func(*args, **kwargs): # you can recieve an undefined number of args """testing in python""" + + + +############################## SESSION06 ############################## + +"""Singletons should be tested using 'is'""" + +"""Anonymous functions""" + +lambda x, y: x + y + +"""Functional Programming""" + +""" +'self' means the new instance of the class that you just created +""" + + diff --git a/Students/salim/session06/html_render.py b/Students/salim/session06/html_render.py new file mode 100644 index 00000000..d8c44398 --- /dev/null +++ b/Students/salim/session06/html_render.py @@ -0,0 +1,10 @@ +#!/usr/local/bin/python + +class Element(object): + + def __init__(self, content=None): + self.content = content + def append(self, new_content): + self.content += new_content + def render(self, file_out, ind=""): + pass diff --git a/Students/salim/session06/lambda_keyword_lab.py b/Students/salim/session06/lambda_keyword_lab.py new file mode 100644 index 00000000..c33ac5d5 --- /dev/null +++ b/Students/salim/session06/lambda_keyword_lab.py @@ -0,0 +1,5 @@ +def incremental(n): + l = [] + for i in range(n): + l.append(lambda x, e=i: x + e) + return l From e8b24cc8c2c0021e50b0aab9da30a8a6a27d538a Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Tue, 18 Nov 2014 19:39:06 -0800 Subject: [PATCH 2/7] Added vim_demo file. --- Students/salim/notes/vim_demo.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Students/salim/notes/vim_demo.py diff --git a/Students/salim/notes/vim_demo.py b/Students/salim/notes/vim_demo.py new file mode 100644 index 00000000..e69de29b From 0f873524bf7a5cde4b87165cb9517ac6c34e7dfc Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Sun, 23 Nov 2014 21:07:05 -0800 Subject: [PATCH 3/7] finished session 07 homework --- Students/salim/notes/class_notes.py | 57 ++++++++++ Students/salim/session07/circle.py | 45 ++++++++ Students/salim/session07/circle_test.py | 102 ++++++++++++++++++ Students/salim/session07/subclassing_notes.py | 14 +++ 4 files changed, 218 insertions(+) create mode 100644 Students/salim/session07/circle.py create mode 100644 Students/salim/session07/circle_test.py create mode 100644 Students/salim/session07/subclassing_notes.py diff --git a/Students/salim/notes/class_notes.py b/Students/salim/notes/class_notes.py index ce619f7b..01d7eb9e 100644 --- a/Students/salim/notes/class_notes.py +++ b/Students/salim/notes/class_notes.py @@ -812,3 +812,60 @@ def func(*args, **kwargs): # you can recieve an undefined number of args """ +############################## SESSION07 ############################## +""" +Personal Project: + - Make sure to use Pep 8 + - Make sure to have unit tests + - Make sure to user version control + - Due the Friday after the last class (Due on December 12th) + - Send proposal by next week +""" + +""" +What are subclasses for? + - Subclassing is not for specialization + - Subclassing is for reusing code + - Bear in mind that the subclass is in charge. This means keep in mind + that the subclass can change +""" + +""" +Multiple Inheritance: + - You can create subclasses from multiple +""" + +""" +New-Style Classes: + - when you subclass a class from "object", this is a new style class + - you should always inherit from object +""" + +""" +super() + - allows you to call super classes when you are inheriting +""" + +""" +properties: + - property + - setters + - deleters +""" + +""" +Static Methods: + - a method that doesn't need self to be passed + - however, these are not very useful +""" + +""" +Class Methods: + - a method that gets the class object, rather than an instance object, as + the first argument +""" + +""" +Special Methods: + - all of the special methods are in the format __methodname__ +""" diff --git a/Students/salim/session07/circle.py b/Students/salim/session07/circle.py new file mode 100644 index 00000000..7bca4715 --- /dev/null +++ b/Students/salim/session07/circle.py @@ -0,0 +1,45 @@ +#!usr/local/bin/python + +from math import pi + + +class Circle(object): + """Generic Circle class.""" + + def __init__(self, radius): + self.radius = radius + + @property + def diameter(self): + return self.radius * 2.0 + + @diameter.setter + def diameter(self, value): + self.radius = value / 2.0 + + @property + def area(self): + return pi * self.radius ** 2 + + @classmethod + def from_diameter(cls, diameter): + return cls(diameter / 2.0) + + def __str__(self): + return 'Circle with radius: {:.2f}'.format(self.radius) + + def __repr__(self): + return 'Circle({})'.format(self.radius) + + def __add__(self, other): + return Circle(self.radius + other.radius) + + def __mul__(self, other): + return Circle(self.radius * other) + + def __rmul__(self, other): + return Circle(self.radius * other) + + def __cmp__(self, other): + result = float(self.radius) - float(other.radius) + return -1 if result < 0 else 1 if result > 0 else 0 diff --git a/Students/salim/session07/circle_test.py b/Students/salim/session07/circle_test.py new file mode 100644 index 00000000..b0a0468c --- /dev/null +++ b/Students/salim/session07/circle_test.py @@ -0,0 +1,102 @@ +#!usr/local/bin/python +from circle import Circle +from math import pi + + +def test_circle_class(): + c = Circle(2) + assert isinstance(c, Circle) + + +def test_radius(): + c = Circle(2.0) + assert c.radius == 2.0 + + +def test_get_diameter(): + c = Circle(2.5) + assert c.diameter == 5.0 + + +def test_set_diameter(): + c = Circle(4.3) + c.diameter = 3.0 + assert c.radius == 1.5 + assert c.diameter == 3.0 + + +def test_area(): + c = Circle(10) + assert c.area == pi * 10 ** 2 + + +def test_set_area(): + c = Circle(4) + try: + c.area = 10 + except AttributeError as error: + assert error.message == "can't set attribute" + else: + assert False + + +def test_from_diameter(): + c = Circle.from_diameter(10) + assert isinstance(c, Circle) + assert c.radius == 5.0 + + +def test_print_circle(): + c_int = Circle(3) + c_float = Circle(3.50) + assert str(c_int) == 'Circle with radius: 3.00' + assert str(c_float) == 'Circle with radius: 3.50' + + +def test_repr(): + c = Circle(3) + assert repr(c) == 'Circle(3)' + + +def test_add(): + a = Circle(10) + b = Circle(15) + assert isinstance(a + b, Circle) + assert (a + b).radius == Circle(25).radius + + +def test_multiply(): + a = Circle(10) + c_mult = a * 3 + assert isinstance(c_mult, Circle) + assert c_mult.radius == 30 + + c2_mult = 4 * a + assert isinstance(c2_mult, Circle) + assert c2_mult.radius == 40 + + +def test_compare_circle(): + a3 = Circle(3) + b3 = Circle(3) + c5 = Circle(5) + d10 = Circle(10) + e3f = Circle(3.0) + assert not a3 > b3 + assert c5 > b3 + assert not c5 < b3 + assert a3 < d10 + assert a3 == b3 + assert not d10 == c5 + + +def test_sort(): + c_list = [Circle(6), Circle(7), Circle(15), Circle(1), Circle(6.5)] + c_list.sort() + + sorted_list = [Circle(1), Circle(6), Circle(6.5), Circle(7), Circle(15)] + assert c_list[0].radius == sorted_list[0].radius + assert c_list[1].radius == sorted_list[1].radius + assert c_list[2].radius == sorted_list[2].radius + assert c_list[3].radius == sorted_list[3].radius + assert c_list[4].radius == sorted_list[4].radius diff --git a/Students/salim/session07/subclassing_notes.py b/Students/salim/session07/subclassing_notes.py new file mode 100644 index 00000000..c608c046 --- /dev/null +++ b/Students/salim/session07/subclassing_notes.py @@ -0,0 +1,14 @@ +class Animal(object): + """Generic animal class""" + + def __init__(self, name): + self.name = name + + def walk(self): + print ('{} is Walking'.format(self.name)) + +class Dog(Animal): + """Man's best friend""" + + def bark(self): + print('Woof!') From eac206765c0582dd725667542a116f888e498bfc Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Fri, 28 Nov 2014 15:01:21 -0800 Subject: [PATCH 4/7] Added sparse_array object with unit tests. --- Students/salim/notes/class_notes.py | 31 +++++ Students/salim/session04/kata_14.py | 2 +- Students/salim/session05/email/Salim Sr.txt | 9 ++ Students/salim/session05/email/Zeina.txt | 9 ++ .../salim/session05/email/joanna hamed.txt | 9 ++ Students/salim/session08/.iterator.py.swp | Bin 0 -> 12288 bytes Students/salim/session08/.quadratic.py.swp | Bin 0 -> 12288 bytes Students/salim/session08/.sparse_array.py.swp | Bin 0 -> 12288 bytes .../salim/session08/.test_sparse_array.py.swp | Bin 0 -> 12288 bytes Students/salim/session08/iterator.py | 42 +++++++ Students/salim/session08/quadratic.py | 17 +++ Students/salim/session08/sparse_array.py | 68 ++++++++++ Students/salim/session08/test_sparse_array.py | 119 ++++++++++++++++++ 13 files changed, 305 insertions(+), 1 deletion(-) create mode 100644 Students/salim/session05/email/Salim Sr.txt create mode 100644 Students/salim/session05/email/Zeina.txt create mode 100644 Students/salim/session05/email/joanna hamed.txt create mode 100644 Students/salim/session08/.iterator.py.swp create mode 100644 Students/salim/session08/.quadratic.py.swp create mode 100644 Students/salim/session08/.sparse_array.py.swp create mode 100644 Students/salim/session08/.test_sparse_array.py.swp create mode 100644 Students/salim/session08/iterator.py create mode 100644 Students/salim/session08/quadratic.py create mode 100644 Students/salim/session08/sparse_array.py create mode 100644 Students/salim/session08/test_sparse_array.py diff --git a/Students/salim/notes/class_notes.py b/Students/salim/notes/class_notes.py index 01d7eb9e..9ad3fb39 100644 --- a/Students/salim/notes/class_notes.py +++ b/Students/salim/notes/class_notes.py @@ -869,3 +869,34 @@ def func(*args, **kwargs): # you can recieve an undefined number of args Special Methods: - all of the special methods are in the format __methodname__ """ + + +############################## SESSION08 ############################## + +""" +Callable classes: + - a "callable" is anything that you can call like a function (i.e., a class + is a "callable") + - __call__ is the special method that you use to make your call callable + +Writing your own sequence type: + - __len__ + - __getitem__ + - __setitem__ + - __delitem__ + - __contains__ +""" + +""" +Iterators: + - every iterator has an __iter__ method (e.g., list.__iter__()) + - in order to make your Class an interator (i.e., so you can use it in a + loop), you need the following methods + - __iter__() + - next() +""" + +""" +Generators: + - generators give you the iterator immediately +""" diff --git a/Students/salim/session04/kata_14.py b/Students/salim/session04/kata_14.py index 626d58c0..80099e43 100644 --- a/Students/salim/session04/kata_14.py +++ b/Students/salim/session04/kata_14.py @@ -114,7 +114,7 @@ def clean_string(s, lowercase = False, punctuation = False): end_line = 0 # ending line of the file num_of_words_to_print = 200 - start_words = 'I did' + start_words = 'But we' # read file to list f = open(path_book) diff --git a/Students/salim/session05/email/Salim Sr.txt b/Students/salim/session05/email/Salim Sr.txt new file mode 100644 index 00000000..02d6b444 --- /dev/null +++ b/Students/salim/session05/email/Salim Sr.txt @@ -0,0 +1,9 @@ + +Dear Salim Sr, + +Thank you very much for your generous donation of $101.00. We +appreciate your thoughtfullness and we will make sure your donation +goes to the right cause. + +Kind Regards, +Donation Team diff --git a/Students/salim/session05/email/Zeina.txt b/Students/salim/session05/email/Zeina.txt new file mode 100644 index 00000000..4c451a20 --- /dev/null +++ b/Students/salim/session05/email/Zeina.txt @@ -0,0 +1,9 @@ + +Dear Zeina, + +Thank you very much for your generous donation of $500.00. We +appreciate your thoughtfullness and we will make sure your donation +goes to the right cause. + +Kind Regards, +Donation Team diff --git a/Students/salim/session05/email/joanna hamed.txt b/Students/salim/session05/email/joanna hamed.txt new file mode 100644 index 00000000..d7d040ba --- /dev/null +++ b/Students/salim/session05/email/joanna hamed.txt @@ -0,0 +1,9 @@ + +Dear Joanna Hamed, + +Thank you very much for your generous donation of $100.00. We +appreciate your thoughtfullness and we will make sure your donation +goes to the right cause. + +Kind Regards, +Donation Team diff --git a/Students/salim/session08/.iterator.py.swp b/Students/salim/session08/.iterator.py.swp new file mode 100644 index 0000000000000000000000000000000000000000..99238dcfd440188394b8398595e1bc48f06ca388 GIT binary patch literal 12288 zcmeI2Pixdb6u_tAt^Py5z-xNRw%yHcEhxnziXc4{3R}I1glsyy8=IYpGZWc*P*70( z0OCPG!J`K+UIhhF4<5Xz7d?8=uONbNl595H>Rs^-{K#hJ&6_vB%^sFar+I#L4URRI z7`8)<-TgG&xbff-YrkSl2XQp$2Lrxo2mjpKHcr>qg7CDITlIA%8?g+7c;}33S6rudT#H+}kO4A42FL&zAOmE843GgbKnBPF86X4ypn(A2?LVEycm4aYczpjq z`v3p^AY`_3}{A*nPKM4Cg}$Ru9^j}4dOJk~s4YcxS|lPUq4$K6JlDuri`%V=D& z+7Bo4TaBs5NhTuZS4JT`$c4ay)QcQ17PXApo zt#X0g-$fCh<+HVyp_Rq*oz=%_utp(GR{prU>c;ZW!k&msVQ(SRvjB71?((UQ<78{P z5Jy`ahAI#}?k?4!mUZXfna&by)FAxN2XYv z1|1EOm_s1SXWI5|%M?QF>v1zKA&dj9Cw?HZbBTw>K0nOX*v@l}ejLDuflaQnK{h+% SrCNENNO)Xafh0R+&wc?O@>tCP literal 0 HcmV?d00001 diff --git a/Students/salim/session08/.quadratic.py.swp b/Students/salim/session08/.quadratic.py.swp new file mode 100644 index 0000000000000000000000000000000000000000..ae8715b2058159a16983a480ac9d5d63e3506042 GIT binary patch literal 12288 zcmeI2y>1gh5XU$4e2aeUG>LKU91{sdNCPw}A{iWLt-bYHK3LzH+r21m;4vsDpyoMH zN-7?J1_5uu?0p3+(IQ3sNBV1b=VoW-e%;J+$`a&M3E$u}Yft8?Vn3#*eKk7CQ6px7}FHtu^sz<>xk| zt>IvIZ#zEBd~T0z<&4L^n3lK7RI$^}r8XPfi(eITnoFOmXt`Rii!%s-Kp=2g+!^i; z!fvzMp_@0Jg)IyOKmY_l00ck)1V8`;K;S&DtzAF+S{2!H?x zfB*=900@8p2!H?xfB*h2kSfQGwY1?p7oY>!cwde z>wxuu)nVOYedRn~ntT_K2U-RJ5C8!X009sH0T2KI5C8!X_~!(uwp{xn=Xr3a%`B4C zqf_ejXt+(cYhMz4;aEl}(Om3yyY2pImBi0At>{FWLX(|QIJT4HG_(1lFfwW{H3_DA zMw1Cow42GKY@^Th?u$0As!IoSUb}Q9>`MNOlI)VDt4f+?sc)0YJ|%rpoSN90>W_?c zE;QG)n^%+Wq`7s^`!(0w}<$ Aa{vGU literal 0 HcmV?d00001 diff --git a/Students/salim/session08/.sparse_array.py.swp b/Students/salim/session08/.sparse_array.py.swp new file mode 100644 index 0000000000000000000000000000000000000000..e1da450fb9cad819925a7fff6afaa85ea5c84e54 GIT binary patch literal 12288 zcmeI2Ka3ki6vpRhfQ0Zb5={!`oFYDCuYKX9L?M?56p8~y3i5^KI5}hQINo?YvzeK_ z*hGK?4NymPNFYQ_r7^E z*2&XpzP)jto(R?mu4f66_eY!WeES7y-6lk{I2!iZkcYN&@2h3)bp1T*z9!|MenH6~ zmR%Old%Qm#uyIay(;*i|mp-++eJSI{g|X>NL954`t7|Kb4Plhrlv!h=Wzx`jxuF`G zYaL0^JlW6*Q<}G#QfwR~RYOE5y;tGClnK#r>^`&)zHG z74Qmp1-t@Y0k42pz$>uN6fnsW`2aaTmgjvgzc0<*^GAR43U~#)0$u^HfLFjP;1%!+ zcm=!yUIDLwSKtv;fZ@0OFCQo5rza3Re*Z82|G)bTA$P!U;74#9Tmv<51RMsxKTXIt z;1lpMxB|ApE1&|Fz@0;c`~q%)o8WWs5%>^vz*$fOe>_FV&)_@o75Eff0&Cz!@Eo{z zkdV9Jd+;^50j`2ga2C7-4uW3~U@UM8+ypnkHLwNV0LQ=q@aL1T1wVk#zz%o|oB%I? zzo5xI;Iw%J=hlbp74Qmp1-t@YfrnoKTD}yEG^ZOPl8O|aJl6cwpt%o$`a3we*W+jxylu-&fO0czG3sZP8pu75et z)@7og3*62pi&IW)SNTG0u7fVG)8?!M|C5scpqA!lUM$((q(Si&ZuhD zC4~Zu)vPk7cw$nR#sNzbE2TK8R&iuYc%+!P%&XckWolF#namY%q9S3? zp`vhhUWyKx%tTQ%W4vA3QFU2pAv0_?q*4er5c@vV1B3`75k_6EtA+DiE-}ourbTaO zMn?j}i7vN7Vze0kd0tsHLz(&cDNjtU?{ulSR5DjYkuQR>2Q+opo@>DNE>5Iv&0p3e z_My1;tS@Wuw|hc4cB}I2mN3~4Y%_*}1~I#+D2@x}0j&aOd(H Mok%nicgmhT03?)I^8f$< literal 0 HcmV?d00001 diff --git a/Students/salim/session08/.test_sparse_array.py.swp b/Students/salim/session08/.test_sparse_array.py.swp new file mode 100644 index 0000000000000000000000000000000000000000..0c36b8289cff450d712bdddbb860f40684cbcd79 GIT binary patch literal 12288 zcmeI2Ply{;9LHZptyZ^{iZ_L+m73`8X7Z=oO<>hZEiSrH%-YMc#A$YPgUL*ondoj0 zdMR2_t6shMuPW$81us2#sJ)0DL*yRB6V2U=Qn#D*Nei;yLxlk_uGX7tI@LWS-Fy3tmF%`UKIHA zzG^Jgqu!G2C0!LlHw;_8XHOR*H;fu#*9k(m;RJ!RI@w*-$2ZqTfsL)em?)QucC5k9 zn|D~(Z+~!O%VB136fg=H1&jhl0i%FXz$jo8*kB4o-A&?2=6qQ)@5htZP1Te58!1u0&O@5cfp-7 z1-HN$oV|(|;S78Or{QBb3Qt1>4%`n_*achR5Aydr{085{+wc}V2R_WfE|7V?1nbm< zY!omG7zHk}0+xC>Vdw^t6*>#G%Az$hV=dU@R&m^lpKW_l#8#hiqX-uSp%ZXn_`ro32kAGXx#xOS`Q z=JGWp%*@C0Bdc1qS{}34+l%&a`x>U@VJlQyqj9*YZzV^*&qnwrIyy$vh7jqg@>r6wg`T^-##nSdd zOPNeIT9MoNuS$7z8BeXLzRHQNzRHQNzACM0EmNZwg6^STSc#l+X<5o4!N;B~)rG6L zG}EiNr=`}8-CrX_U7Grkq_4nLWK<)g!wzDfK;KAgZj6u}Aso-s*Jy_}fh8G&~1> Vcl5%bAkXC&4z;{OSDvyLe*@Z7>`DLt literal 0 HcmV?d00001 diff --git a/Students/salim/session08/iterator.py b/Students/salim/session08/iterator.py new file mode 100644 index 00000000..fdc2750e --- /dev/null +++ b/Students/salim/session08/iterator.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +""" +Simple iterator examples +""" + + +class IterateMe_1(object): + """ + About as simple an iterator as you can get: + + returns the sequence of numbers from zero to 4 + ( like xrange(4) ) + """ + def __init__(self, stop, *args): + self.step = 1 + if not args: + self.start = -1 + self.stop = stop + else: + self.start = stop - 1 + self.stop = args[0] + if len(args) == 2: + self.step = args[1] + self.start = stop - self.step + + def __iter__(self): + self.current = self.start + return self + + def next(self): + self.current += self.step + if self.current < self.stop: + return self.current + else: + raise StopIteration + +if __name__ == "__main__": + + print "Testing the iterator" + for i in IterateMe_1(): + print i diff --git a/Students/salim/session08/quadratic.py b/Students/salim/session08/quadratic.py new file mode 100644 index 00000000..9ff0e542 --- /dev/null +++ b/Students/salim/session08/quadratic.py @@ -0,0 +1,17 @@ +#!usr/local/bin/python + + +class Quadratic(object): + """ + Class for the quardratic equation. + """ + def __init__(self, a, b, c): + self.a = a + self.b = b + self.c = c + + def __call__(self, x): + """ + Return the y value of the quadratic formula. + """ + return (self.a * x ** 2) + (self.b * x) + self.c diff --git a/Students/salim/session08/sparse_array.py b/Students/salim/session08/sparse_array.py new file mode 100644 index 00000000..59c8c634 --- /dev/null +++ b/Students/salim/session08/sparse_array.py @@ -0,0 +1,68 @@ +#!usr/local/bin/python + + +class SparseArray(object): + """ + Use a dictionary to store the location of the values. Then, if the user + asks for a key that isn't in the dictionary, but it should exist, then + return zero. + """ + def __init__(self, sequence): + self.data = {k: v for k, v in enumerate(sequence) if v != 0} + self.mylen = len(sequence) + + def get_value(self, idx): + try: + return self.data[idx] + except KeyError: + if idx < self.mylen: + return 0 + else: + raise IndexError + + def __len__(self): + return self.mylen + + def __getitem__(self, idx): + if isinstance(idx, slice): + l = [] + start, stop, stride = idx.indices(len(self)) + print len(self.data) + print start + print stop + print stride + for i in xrange(start, stop): + l.append(self.get_value(i)) + return l + else: + return self.get_value(idx) + + def __setitem__(self, idx, value): + if idx < self.mylen: + try: + del self.data[idx] + except KeyError: + pass + finally: + if value != 0: + self.data[idx] = value + else: + raise IndexError + + def __delitem__(self, idx): + if idx < self.mylen: + self.mylen -= 1 + try: + del self.data[idx] + except KeyError: + pass + finally: + d = {} + for k, v in self.data.iteritems(): + if k > idx: + d[k - 1] = v + else: + d[k] = v + self.data = d + else: + raise IndexError diff --git a/Students/salim/session08/test_sparse_array.py b/Students/salim/session08/test_sparse_array.py new file mode 100644 index 00000000..593a6c65 --- /dev/null +++ b/Students/salim/session08/test_sparse_array.py @@ -0,0 +1,119 @@ +#!usr/local/bin/python + +import sparse_array + + +def test_len(): + sa = sparse_array.SparseArray([0, 1, 0, 3, 4, 0, 9, 0]) + assert len(sa) == 8 + + sa2 = sparse_array.SparseArray([]) + assert len(sa2) == 0 + + sa3 = sparse_array.SparseArray((3, 4, 0, 9, 0)) + assert len(sa3) == 5 + + sa4 = sparse_array.SparseArray((0, 0, 0, 0, 0)) + assert len(sa4) == 5 + + +def test_get_item(): + sa = sparse_array.SparseArray([0, 1, 0, 3, 4, 0, 9, 0]) + assert sa[0] == 0 + assert sa[1] == 1 + assert sa[2] == 0 + assert sa[3] == 3 + assert sa[4] == 4 + assert sa[5] == 0 + assert sa[6] == 9 + assert sa[7] == 0 + + try: + sa[8] + except IndexError: + assert True + else: + assert False + + +def test_set_item(): + sa = sparse_array.SparseArray([0, 0, 4, 100, 0, 3, 9]) + sa[0] = 1 + sa[1] = 0 + sa[2] = 0 + sa[3] = 8 + + assert sa[0] == 1 + assert sa[1] == 0 + assert sa[2] == 0 + assert sa[3] == 8 + assert sa[4] == 0 + assert sa[5] == 3 + assert sa[6] == 9 + + try: + sa[8] + except IndexError: + assert True + else: + assert False + + +def test_del_item(): + sa = sparse_array.SparseArray([0, 1, 0, 100, 0, 3, 9]) + + del sa[0] + # ([1, 0, 100, 0, 3, 9]) + assert len(sa) == 6 + assert sa[0] == 1 + assert sa[1] == 0 + assert sa[2] == 100 + assert sa[3] == 0 + assert sa[4] == 3 + assert sa[5] == 9 + + del sa[4] + # ([1, 0, 100, 0, 9]) + assert len(sa) == 5 + assert sa[0] == 1 + assert sa[1] == 0 + assert sa[2] == 100 + assert sa[3] == 0 + assert sa[4] == 9 + + del sa[1] + # ([1, 100, 0, 9]) + assert len(sa) == 4 + assert sa[0] == 1 + assert sa[1] == 100 + assert sa[2] == 0 + assert sa[3] == 9 + + try: + del sa[8] + except IndexError: + assert True + else: + assert False + + +def test_contains(): + sa = sparse_array.SparseArray([0, 1, 0, 100, 0, 3, 9]) + + assert 0 in sa + assert 1 in sa + assert 100 in sa + assert 3 in sa + assert 9 in sa + assert not 10 in sa + assert not 99 in sa + + +def test_slice(): + sa = sparse_array.SparseArray([0, 1, 0, 100, 0, 3, 9]) + + assert sa[0:1] == [0] + assert sa[1:3] == [1, 0] + assert sa[1:4] == [1, 0, 100] + assert sa[2:] == [0, 100, 0, 3, 9] + assert sa[:4] == [0, 1, 0, 100] From 51c97fd15b8cb366f47430a230cb4a3dfb3a979d Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Sat, 6 Dec 2014 13:05:34 -0800 Subject: [PATCH 5/7] Generate lab, modified sparse array, decoratory lab. --- Students/salim/session08/.iterator.py.swp | Bin 12288 -> 0 bytes Students/salim/session08/.quadratic.py.swp | Bin 12288 -> 0 bytes Students/salim/session08/.sparse_array.py.swp | Bin 12288 -> 0 bytes .../salim/session08/.test_sparse_array.py.swp | Bin 12288 -> 0 bytes Students/salim/session08/generator_lab.py | 27 +++++++++ Students/salim/session08/sparse_array.py | 16 +++-- .../salim/session08/test_generator_lab.py | 57 ++++++++++++++++++ Students/salim/session09/decorator_lab.py | 31 ++++++++++ 8 files changed, 127 insertions(+), 4 deletions(-) delete mode 100644 Students/salim/session08/.iterator.py.swp delete mode 100644 Students/salim/session08/.quadratic.py.swp delete mode 100644 Students/salim/session08/.sparse_array.py.swp delete mode 100644 Students/salim/session08/.test_sparse_array.py.swp create mode 100644 Students/salim/session08/generator_lab.py create mode 100644 Students/salim/session08/test_generator_lab.py create mode 100644 Students/salim/session09/decorator_lab.py diff --git a/Students/salim/session08/.iterator.py.swp b/Students/salim/session08/.iterator.py.swp deleted file mode 100644 index 99238dcfd440188394b8398595e1bc48f06ca388..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI2Pixdb6u_tAt^Py5z-xNRw%yHcEhxnziXc4{3R}I1glsyy8=IYpGZWc*P*70( z0OCPG!J`K+UIhhF4<5Xz7d?8=uONbNl595H>Rs^-{K#hJ&6_vB%^sFar+I#L4URRI z7`8)<-TgG&xbff-YrkSl2XQp$2Lrxo2mjpKHcr>qg7CDITlIA%8?g+7c;}33S6rudT#H+}kO4A42FL&zAOmE843GgbKnBPF86X4ypn(A2?LVEycm4aYczpjq z`v3p^AY`_3}{A*nPKM4Cg}$Ru9^j}4dOJk~s4YcxS|lPUq4$K6JlDuri`%V=D& z+7Bo4TaBs5NhTuZS4JT`$c4ay)QcQ17PXApo zt#X0g-$fCh<+HVyp_Rq*oz=%_utp(GR{prU>c;ZW!k&msVQ(SRvjB71?((UQ<78{P z5Jy`ahAI#}?k?4!mUZXfna&by)FAxN2XYv z1|1EOm_s1SXWI5|%M?QF>v1zKA&dj9Cw?HZbBTw>K0nOX*v@l}ejLDuflaQnK{h+% SrCNENNO)Xafh0R+&wc?O@>tCP diff --git a/Students/salim/session08/.quadratic.py.swp b/Students/salim/session08/.quadratic.py.swp deleted file mode 100644 index ae8715b2058159a16983a480ac9d5d63e3506042..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI2y>1gh5XU$4e2aeUG>LKU91{sdNCPw}A{iWLt-bYHK3LzH+r21m;4vsDpyoMH zN-7?J1_5uu?0p3+(IQ3sNBV1b=VoW-e%;J+$`a&M3E$u}Yft8?Vn3#*eKk7CQ6px7}FHtu^sz<>xk| zt>IvIZ#zEBd~T0z<&4L^n3lK7RI$^}r8XPfi(eITnoFOmXt`Rii!%s-Kp=2g+!^i; z!fvzMp_@0Jg)IyOKmY_l00ck)1V8`;K;S&DtzAF+S{2!H?x zfB*=900@8p2!H?xfB*h2kSfQGwY1?p7oY>!cwde z>wxuu)nVOYedRn~ntT_K2U-RJ5C8!X009sH0T2KI5C8!X_~!(uwp{xn=Xr3a%`B4C zqf_ejXt+(cYhMz4;aEl}(Om3yyY2pImBi0At>{FWLX(|QIJT4HG_(1lFfwW{H3_DA zMw1Cow42GKY@^Th?u$0As!IoSUb}Q9>`MNOlI)VDt4f+?sc)0YJ|%rpoSN90>W_?c zE;QG)n^%+Wq`7s^`!(0w}<$ Aa{vGU diff --git a/Students/salim/session08/.sparse_array.py.swp b/Students/salim/session08/.sparse_array.py.swp deleted file mode 100644 index e1da450fb9cad819925a7fff6afaa85ea5c84e54..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI2Ka3ki6vpRhfQ0Zb5={!`oFYDCuYKX9L?M?56p8~y3i5^KI5}hQINo?YvzeK_ z*hGK?4NymPNFYQ_r7^E z*2&XpzP)jto(R?mu4f66_eY!WeES7y-6lk{I2!iZkcYN&@2h3)bp1T*z9!|MenH6~ zmR%Old%Qm#uyIay(;*i|mp-++eJSI{g|X>NL954`t7|Kb4Plhrlv!h=Wzx`jxuF`G zYaL0^JlW6*Q<}G#QfwR~RYOE5y;tGClnK#r>^`&)zHG z74Qmp1-t@Y0k42pz$>uN6fnsW`2aaTmgjvgzc0<*^GAR43U~#)0$u^HfLFjP;1%!+ zcm=!yUIDLwSKtv;fZ@0OFCQo5rza3Re*Z82|G)bTA$P!U;74#9Tmv<51RMsxKTXIt z;1lpMxB|ApE1&|Fz@0;c`~q%)o8WWs5%>^vz*$fOe>_FV&)_@o75Eff0&Cz!@Eo{z zkdV9Jd+;^50j`2ga2C7-4uW3~U@UM8+ypnkHLwNV0LQ=q@aL1T1wVk#zz%o|oB%I? zzo5xI;Iw%J=hlbp74Qmp1-t@YfrnoKTD}yEG^ZOPl8O|aJl6cwpt%o$`a3we*W+jxylu-&fO0czG3sZP8pu75et z)@7og3*62pi&IW)SNTG0u7fVG)8?!M|C5scpqA!lUM$((q(Si&ZuhD zC4~Zu)vPk7cw$nR#sNzbE2TK8R&iuYc%+!P%&XckWolF#namY%q9S3? zp`vhhUWyKx%tTQ%W4vA3QFU2pAv0_?q*4er5c@vV1B3`75k_6EtA+DiE-}ourbTaO zMn?j}i7vN7Vze0kd0tsHLz(&cDNjtU?{ulSR5DjYkuQR>2Q+opo@>DNE>5Iv&0p3e z_My1;tS@Wuw|hc4cB}I2mN3~4Y%_*}1~I#+D2@x}0j&aOd(H Mok%nicgmhT03?)I^8f$< diff --git a/Students/salim/session08/.test_sparse_array.py.swp b/Students/salim/session08/.test_sparse_array.py.swp deleted file mode 100644 index 0c36b8289cff450d712bdddbb860f40684cbcd79..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI2Ply{;9LHZptyZ^{iZ_L+m73`8X7Z=oO<>hZEiSrH%-YMc#A$YPgUL*ondoj0 zdMR2_t6shMuPW$81us2#sJ)0DL*yRB6V2U=Qn#D*Nei;yLxlk_uGX7tI@LWS-Fy3tmF%`UKIHA zzG^Jgqu!G2C0!LlHw;_8XHOR*H;fu#*9k(m;RJ!RI@w*-$2ZqTfsL)em?)QucC5k9 zn|D~(Z+~!O%VB136fg=H1&jhl0i%FXz$jo8*kB4o-A&?2=6qQ)@5htZP1Te58!1u0&O@5cfp-7 z1-HN$oV|(|;S78Or{QBb3Qt1>4%`n_*achR5Aydr{085{+wc}V2R_WfE|7V?1nbm< zY!omG7zHk}0+xC>Vdw^t6*>#G%Az$hV=dU@R&m^lpKW_l#8#hiqX-uSp%ZXn_`ro32kAGXx#xOS`Q z=JGWp%*@C0Bdc1qS{}34+l%&a`x>U@VJlQyqj9*YZzV^*&qnwrIyy$vh7jqg@>r6wg`T^-##nSdd zOPNeIT9MoNuS$7z8BeXLzRHQNzRHQNzACM0EmNZwg6^STSc#l+X<5o4!N;B~)rG6L zG}EiNr=`}8-CrX_U7Grkq_4nLWK<)g!wzDfK;KAgZj6u}Aso-s*Jy_}fh8G&~1> Vcl5%bAkXC&4z;{OSDvyLe*@Z7>`DLt diff --git a/Students/salim/session08/generator_lab.py b/Students/salim/session08/generator_lab.py new file mode 100644 index 00000000..7416eb54 --- /dev/null +++ b/Students/salim/session08/generator_lab.py @@ -0,0 +1,27 @@ +#!usr/local/bin/python + + +def intsum(): + args = [0, 1, 2, 3, 4, 5, 6, 7] + x = 0 + for i in args: + yield x + i + x = x + i + + +def doubler(): + args = range(1, 100) + x = 0 + for i in args: + yield max([x * 2, 1]) + x = max([x * 2, 1]) + + +def fib(): + l = [0, 1] + for i in range(1, 100): + if i == 0: + yield 1 + else: + l.append(l[-1] + l[-2]) + yield l[-1] diff --git a/Students/salim/session08/sparse_array.py b/Students/salim/session08/sparse_array.py index 59c8c634..66d6ff48 100644 --- a/Students/salim/session08/sparse_array.py +++ b/Students/salim/session08/sparse_array.py @@ -10,6 +10,7 @@ class SparseArray(object): def __init__(self, sequence): self.data = {k: v for k, v in enumerate(sequence) if v != 0} self.mylen = len(sequence) + self.current = -1 def get_value(self, idx): try: @@ -27,10 +28,6 @@ def __getitem__(self, idx): if isinstance(idx, slice): l = [] start, stop, stride = idx.indices(len(self)) - print len(self.data) - print start - print stop - print stride for i in xrange(start, stop): l.append(self.get_value(i)) return l @@ -66,3 +63,14 @@ def __delitem__(self, idx): self.data = d else: raise IndexError + + def __iter__(self): + self.current = -1 + return self + + def next(self): + if self.current + 1 < self.mylen: + self.current += 1 + return self.get_value(self.current) + else: + raise StopIteration diff --git a/Students/salim/session08/test_generator_lab.py b/Students/salim/session08/test_generator_lab.py new file mode 100644 index 00000000..517f8a35 --- /dev/null +++ b/Students/salim/session08/test_generator_lab.py @@ -0,0 +1,57 @@ +#!usr/local/bin/python + +import generator_lab as gen + + +def test_intsum(): + g = gen.intsum() + + assert g.next() == 0 + assert g.next() == 1 + assert g.next() == 3 + assert g.next() == 6 + assert g.next() == 10 + assert g.next() == 15 + + +def test_doubler(): + g = gen.doubler() + + assert g.next() == 1 + assert g.next() == 2 + assert g.next() == 4 + assert g.next() == 8 + assert g.next() == 16 + assert g.next() == 32 + + for i in range(10): + j = g.next() + + assert j == 2**15 + + +def test_fib(): + g = gen.fib() + + assert g.next() == 1 + assert g.next() == 1 + assert g.next() == 2 + assert g.next() == 3 + assert g.next() == 5 + assert g.next() == 8 + assert g.next() == 13 + assert g.next() == 21 + + +def test_prime(): + g = gen.prime() + + assert g.next() == 2 + assert g.next() == 3 + assert g.next() == 5 + assert g.next() == 7 + assert g.next() == 11 + assert g.next() == 13 + assert g.next() == 17 + assert g.next() == 19 + assert g.next() == 23 diff --git a/Students/salim/session09/decorator_lab.py b/Students/salim/session09/decorator_lab.py new file mode 100644 index 00000000..2932d26e --- /dev/null +++ b/Students/salim/session09/decorator_lab.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + + +def p_wrapper(func): + def wrap(string, tag): + return '<{}>{}'.format(tag, string.strip(), tag) + return wrap + +@p_wrapper +def return_a_string(): + return + +return_a_string('this is my string', 'p') + + +# class example +def logged_func(func): + def logged(*args, **kwargs): + print "Function %r called" % func.__name__ + if args: + print "\twith args: %r" % args + if kwargs: + print "\twith kwargs: %r" % kwargs + result = func(*args, **kwargs) + print "\t Result --> %r" % result + return result + return logged + +@logged_func +def add(a, b): + return a + b From f70019da5db02038d33f4bb1d5a3b5c530dee271 Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Sat, 6 Dec 2014 14:56:37 -0800 Subject: [PATCH 6/7] finished generator lab. --- Students/salim/session08/generator_lab.py | 25 ++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/Students/salim/session08/generator_lab.py b/Students/salim/session08/generator_lab.py index 7416eb54..4e605fc5 100644 --- a/Students/salim/session08/generator_lab.py +++ b/Students/salim/session08/generator_lab.py @@ -18,10 +18,25 @@ def doubler(): def fib(): - l = [0, 1] - for i in range(1, 100): - if i == 0: + l = [0, 0] + while True: + if sum(l) == 0: yield 1 + l.append(1) else: - l.append(l[-1] + l[-2]) - yield l[-1] + yield sum(l) + l.append(sum(l)) + del l[0] + + +def prime(): + num = 1 + while True: + num += 1 + prime = True + for i in xrange(2, num + 1): + if num % i == 0 and i != num: + prime = False + break + if prime: + yield num From b36a2e240aabe466367547fae67241cb1f74e510 Mon Sep 17 00:00:00 2001 From: Salim Hamed Date: Tue, 9 Dec 2014 17:50:54 -0800 Subject: [PATCH 7/7] Finished Session 09 Homework. --- .../salim/session09/context_manager_lab.py | 23 +++++++++++++++ Students/salim/session09/decorator_lab.py | 29 ++++--------------- 2 files changed, 29 insertions(+), 23 deletions(-) create mode 100644 Students/salim/session09/context_manager_lab.py diff --git a/Students/salim/session09/context_manager_lab.py b/Students/salim/session09/context_manager_lab.py new file mode 100644 index 00000000..780cb4a8 --- /dev/null +++ b/Students/salim/session09/context_manager_lab.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +from datetime import datetime +import sys + + +class Timer(object): + + def __init__(self, file_object=sys.stdout): + self.file_object = file_object + + def __enter__(self): + self.start = datetime.now() + return self + + def __exit__(self, e_type, e_value, e_tb): + elasped = datetime.now() - self.start + output = "This took {:f} seconds.".format(elasped.total_seconds()) + try: + self.file_object.write(output) + except AttributeError as e: + raise e + + return False diff --git a/Students/salim/session09/decorator_lab.py b/Students/salim/session09/decorator_lab.py index 2932d26e..6754e6c4 100644 --- a/Students/salim/session09/decorator_lab.py +++ b/Students/salim/session09/decorator_lab.py @@ -2,30 +2,13 @@ def p_wrapper(func): - def wrap(string, tag): - return '<{}>{}'.format(tag, string.strip(), tag) + def wrap(*args, **kwargs): + tag = kwargs.get('tag', 'p') # default tag value is

+ return '<{}>{}'.format(tag, args[0].strip(), tag) return wrap @p_wrapper -def return_a_string(): - return +def return_a_string(string): + return string -return_a_string('this is my string', 'p') - - -# class example -def logged_func(func): - def logged(*args, **kwargs): - print "Function %r called" % func.__name__ - if args: - print "\twith args: %r" % args - if kwargs: - print "\twith kwargs: %r" % kwargs - result = func(*args, **kwargs) - print "\t Result --> %r" % result - return result - return logged - -@logged_func -def add(a, b): - return a + b +return_a_string('this is my string')