diff --git a/Students/salim/notes/class_notes.py b/Students/salim/notes/class_notes.py index d134a7dc..9ad3fb39 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,109 @@ 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 +""" + + +############################## 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__ +""" + + +############################## 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/notes/vim_demo.py b/Students/salim/notes/vim_demo.py new file mode 100644 index 00000000..e69de29b 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/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 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!') diff --git a/Students/salim/session08/generator_lab.py b/Students/salim/session08/generator_lab.py new file mode 100644 index 00000000..4e605fc5 --- /dev/null +++ b/Students/salim/session08/generator_lab.py @@ -0,0 +1,42 @@ +#!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, 0] + while True: + if sum(l) == 0: + yield 1 + l.append(1) + else: + 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 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..66d6ff48 --- /dev/null +++ b/Students/salim/session08/sparse_array.py @@ -0,0 +1,76 @@ +#!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) + self.current = -1 + + 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)) + 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 + + 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/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] 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 new file mode 100644 index 00000000..6754e6c4 --- /dev/null +++ b/Students/salim/session09/decorator_lab.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python + + +def p_wrapper(func): + 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(string): + return string + +return_a_string('this is my string')