Last active
October 13, 2015 17:18
-
-
Save marioplumbarius/4229672 to your computer and use it in GitHub Desktop.
Pieces of code I've written since I started the MOOC's Python course. It includes strings, lists, tuples, dictionaries, loops, conditionals, functions, methods, classes, objects, files, exceptions, queues, trees, nodes and some exercices I've done through the course.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### abstract data type - ADT | |
| ### specifies a set of methods and what they do, but not its implementation | |
| ## | |
| ### -> the stack ADT = a collection/data structure with mutiple elements | |
| ##""" a ADT is defined by its interface: the operations/methods that | |
| ## can be performed on it """ | |
| ## | |
| ### interface of a stack: | |
| ##__init__ = initialize a new empty stack | |
| ##push = add a new item to the stack | |
| ##pop = remove and return the last added item from the stack | |
| ##isEmpty = check whether the stack is empty | |
| # -> implementing stacks with Python lists | |
| # implementation = set of methods that satisfy the syntatic | |
| # and semantic requirements of an interface | |
| ##class Stack: | |
| ## | |
| ## """ venner = the methods consist of simple | |
| ## invocations of existing methods """ | |
| ## | |
| ## def __init__(self): | |
| ## """ creates an empty list named 'items' """ | |
| ## self.items = [] | |
| ## | |
| ## def push(self, item): | |
| ## """ add new items to the 'items' list """ | |
| ## self.items.append(item) | |
| ## | |
| ## def pop(self): | |
| ## """ removes and returns the last item from the 'items' list """ | |
| ## return self.items.pop() | |
| ## | |
| ## def isEmpty(self): | |
| ## """ checks if the 'items' list is empty """ | |
| ## return (self.items == []) | |
| ### stack = generic data structure = we can add any type of item to it | |
| ### -> pushing and popping | |
| ##s = Stack() | |
| ##s.push(54) | |
| ##s.push(4.5) | |
| ##s.push("+") | |
| ## | |
| ##while not s.isEmpty(): | |
| ## """ prints the list backward """ | |
| ## print s.pop(), | |
| ##import string | |
| ##x = "1 2 + 3" | |
| ##x = string.split(x) | |
| ##print x | |
| ### -> parsing = in this case, analysing/read a string of characters or tokens | |
| ### and analyze its grammatical operands | |
| ### -> token = set of characters that are treated as | |
| ### a unit for purposes of parsing, such as words in a natural language | |
| ### -> postfix = the operator follow the operands: "1 2 +" = "1 + 2" | |
| ##def evalPostfix(expr): | |
| ## """ takes in an string expression with postfix and retuns the result """ | |
| ## | |
| ## import re # regular expression module | |
| ## # breaks the list by empty char = "[^0-9]" | |
| ## tokenList = re.split("([^0-9])", expr) | |
| ## stack = Stack() # creates an empty stack | |
| ## for token in tokenList: # traverse the tokenList | |
| ## if token == '' or token == ' ': # ignore empty char | |
| ## continue | |
| ## if token == '+': | |
| ## # removes and sums the last 2 items from stack | |
| ## sum = stack.pop() + stack.pop() | |
| ## # add the result from sum onto the stack | |
| ## stack.push(sum) | |
| ## elif token == '*': # same behaviour as previous | |
| ## product = stack.pop() * stack.pop() | |
| ## stack.push(product) | |
| ## else: | |
| ## # if the item is a number | |
| ## stack.push(int(token)) # add it onto the stack | |
| ## return stack.pop() # removes and returns the last item from stack | |
| ## | |
| ##print evalPostfix("56 47 + 2 *") | |
| ## | |
| ### -> provider = the code that implements an ADT | |
| ### -> client = a program that uses an ADT |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### bitwise operations. a binary representation | |
| ## | |
| ##print 5>>4 # Right Shift | |
| ##print 5<<1 # Left Shift | |
| ##print 8&5 # Bitwise AND | |
| ##print 9|4 # Bitwise OR | |
| ##print 12^42 # Bitwise XOR | |
| ##print ~88 # Bitwise NOT | |
| ## | |
| ## | |
| ### printing binary numbers in base 2 | |
| ### syntax -> 0b + bit | |
| ##print 0b1, #1 | |
| ##print 0b10, #2 | |
| ##print 0b11, #3 | |
| ##print 0b100, #4 | |
| ##print 0b101, #5 | |
| ##print 0b110, #6 | |
| ##print 0b111 #7 | |
| ##print "******" | |
| ##print 0b1 + 0b11 # 4 | |
| ##print 0b11*0b11 # 9 | |
| ### functions | |
| ##bin() = base 2 | |
| ##oct() = base 8 | |
| ##hex() = base 16 | |
| ##int("number", number's bas) = convert any number as string from any base to base 10 | |
| ##print int("1111", 2) # 15 | |
| ##print int("120", 3) # 15 | |
| ##print int ("33", 4) # 15 | |
| ##print int ("17", 8) # 15 | |
| ##print int ("F", 16) # 15 | |
| ### -> bitwise operators | |
| ### left bit shift | |
| ##print 0b0001 << 2 # = 0b0010 | |
| ##print 0b0010 << 2 # = 0b1000 | |
| ## | |
| ### right bit shift | |
| ##print 0b1000 >> 2 # = 0b0010 | |
| ##print 0b0001 << 2 # = 0b0000 | |
| ### AND = & | |
| ##a = 0b00101010 # 42 | |
| ##b = 0b00001111 # 15 | |
| ## -----X-X-- # matching bits | |
| ##c = 0b00001010 # 10 | |
| ##print a & b # 10 | |
| ### OR = | | |
| ##a = 0b00101010 # 42 | |
| ##b = 0b00001111 # 15 | |
| ### ----X-XXXX # at least one bit is on | |
| ##c 0b00101111 # 47 | |
| ##print a | b # 47 | |
| ### XOR = ^ | |
| ##a = 0b00101010 # 42 | |
| ##b = 0b00001111 # 15 | |
| ### ----X--X-X # only one bit on | |
| ##print 0b00100101 # 37 | |
| ##print a ^ b # 37 | |
| ### NOT = ~ | |
| ### syntax -> ~x = (x+1)*(-1) | |
| ##print ~1 # (1+1)*-1 = -2 | |
| ##print ~2 # (2+1)*-1 = -3 | |
| ##print ~3 # (3+1)*-1 = -4 | |
| ##print ~42 # (42+1)*-1 = -43 | |
| ##print ~123 # (123+1)*-1 = -124 | |
| ##def check_bit4(x): | |
| ## """ takes an integer as input and checks the fourth bit from right """ | |
| ## mask = 0b1000 # this var will be used in comparison with user input | |
| ## desired = x & mask # will return int value for matching bits | |
| ## | |
| ## # the fourth bit from a list of fourth is = 8, so... | |
| ## if desired == 8: | |
| ## return "on" | |
| ## else: | |
| ## return "off" | |
| ### turning bits on | |
| ##a = 0b100000 | |
| ##mask = 0b100 # third bit | |
| ##desired = a | mask | |
| ##print bin(desired) | |
| ### flipping bits | |
| ##a = 0b11111111 | |
| ##mask = 0b10001 # fourth and last bit | |
| ##desired = a ^ mask | |
| ##print bin(desired) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### classes and functions | |
| ## | |
| ### -> time | |
| ##class Time(): | |
| ## pass | |
| ## | |
| ### instances | |
| ## | |
| ### t1 | |
| ##t1 = Time() | |
| ##t1.hours = 5 | |
| ##t1.minutes = 30 | |
| ##t1.seconds = 50 | |
| ## | |
| ### t1 | |
| ##t2 = Time() | |
| ##t2.hours = 2 | |
| ##t2.minutes = 15 | |
| ##t2.seconds = 0 | |
| ## | |
| ##def printTimes(x): | |
| ## """ prints attributes from passed argument """ | |
| ## print "%d:%d:%d" % (x.hours, x.minutes, x.seconds) | |
| ### -> pure functions = doesn't modify any objects passed to it as arguments | |
| ##def sumTimes(x, y): | |
| ## """ creates a new object, initializes its attributes | |
| ## and returns a reference to the new object """ | |
| ## # new object | |
| ## totalTime = Time() | |
| ## totalTime.hours = x.hours + y.hours | |
| ## totalTime.minutes = x.minutes + y.minutes | |
| ## totalTime.seconds = x.seconds + y.seconds | |
| ## | |
| ## # making sure the number of seconds or minutes are not up to more than sixty | |
| ## # if so, let's move the extra seconds into minutes or minutes into hours | |
| ## if totalTime.seconds >= 60: | |
| ## totalTime.seconds -= 60 | |
| ## totalTime.minutes += 1 | |
| ## | |
| ## if totalTime.minutes >= 60: | |
| ## totalTime.minutes -= 60 | |
| ## totalTime.hours += 1 | |
| ## | |
| ## return totalTime | |
| ### -> modifiers = modify any objects passed to it as arguments | |
| ## | |
| ##def increment(t, seconds): | |
| ## """ takes in a Time object as argument and increment its attribute by seconds """ | |
| ## | |
| ## t.seconds += seconds | |
| ## | |
| ## if t.seconds == 60: | |
| ## t.seconds -= 60 | |
| ## t.minutes += 1 | |
| ## | |
| ## elif t.seconds > 60: | |
| ## seconds_to_minutes = t.seconds/60.0 | |
| ## rest_minutes = int(seconds_to_minutes) | |
| ## rest_seconds = int((seconds_to_minutes - rest_minutes)*60) | |
| ## t.seconds = rest_seconds | |
| ## t.minutes += rest_minutes | |
| ## | |
| ## if t.minutes == 60: | |
| ## t.minutes -= 60 | |
| ## t.hours += 1 | |
| ## | |
| ## elif t.minutes > 60: | |
| ## minutes_to_hours = t.minutes/60.0 | |
| ## rest_hours = int(minutes_to_hours) | |
| ## rest_minutes = int((minutes_to_hours - rest_hours)*60) | |
| ## t.minutes = rest_minutes | |
| ## t.hours += rest_hours | |
| ## printTimes(t) | |
| ### -> rewrite past functions, so they become shorter and easier to read | |
| ##def convertToSeconds(t): | |
| ## """ converts a Time object into an integer """ | |
| ## minutes = t.hours * 60 + t.minutes | |
| ## seconds = minutes * 60 + t.seconds | |
| ## return seconds | |
| ## | |
| ##def makeTime(seconds): | |
| ## """ converts from an integer to a Time object """ | |
| ## t = Time() | |
| ## t.hours = seconds / 3600 | |
| ## t.minutes = (seconds % 3600)/60 | |
| ## t.seconds = seconds %60 | |
| ## return t | |
| ## | |
| ##def sumTimes(t1,t2): | |
| ## """ takes in two Time objects and sum its attributes values """ | |
| ## seconds = convertToSeconds(t1) + convertToSeconds(t2) | |
| ## return makeTime(seconds) | |
| ## | |
| ##def increment(t, sec): | |
| ## """ takes in an time object and seconds to increment """ | |
| ## t = convertToSeconds(t) | |
| ## t += sec | |
| ## return printTimes(makeTime(t)) | |
| ## | |
| ### increments 30 seconds from t1 seconds attribute | |
| ##increment(t1, 30) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> methods | |
| ## | |
| ### class | |
| ##class Time(): | |
| ## def printTime(time): | |
| ## """ takes in an Time object and prints its attributes """ | |
| ## print "%s:%s:%s" % (time.hours, time.minutes, time.seconds) | |
| ## | |
| ## def increment(self, seconds): | |
| ## """ takes in an Time object and seconds to increment its seconds attribute """ | |
| ## self.seconds = self.seconds + seconds | |
| ## | |
| ## while self.seconds >=60: | |
| ## self.seconds = self.seconds - 60 | |
| ## self.minutes = self.minutes + 1 | |
| ## | |
| ## | |
| ## while self.minutes >= 60: | |
| ## self.minutes = self.minutes - 60 | |
| ## self.hours = self.hours + 1 | |
| ## | |
| ## def convertToSeconds(self): | |
| ## """ converts a Time object into an integer """ | |
| ## minutes = self.hours * 60 + self.minutes | |
| ## seconds = minutes * 60 + self.seconds | |
| ## return seconds | |
| ## | |
| ## # -> operating with two Time objects | |
| ## def after(self, time2): | |
| ## """ is time2 after the currentTime """ | |
| ## if self.hours > time2.hours: | |
| ## return 1 | |
| ## elif self.hours < time2.hours: | |
| ## return 0 | |
| ## | |
| ## if self.minutes > time2.minutes: | |
| ## return 1 | |
| ## elif self.minutes < time2.minutes: | |
| ## return 0 | |
| ## | |
| ## if self.seconds > time2.seconds: | |
| ## return 1 | |
| ## return 0 | |
| ## | |
| ### new object | |
| ##currentTime = Time() | |
| ##currentTime.hours = 1 | |
| ##currentTime.minutes = 1 | |
| ##currentTime.seconds = 1 | |
| ## | |
| ### another object | |
| ##lunchTime = Time() | |
| ##lunchTime.hours = 2 | |
| ##lunchTime.minutes = 2 | |
| ##lunchTime.seconds = 2 | |
| ## | |
| ### invoking increment as a method | |
| ##currentTime.increment(50) | |
| ## | |
| ### invoking printTime as a method | |
| ##currentTime.printTime() | |
| ## | |
| ### invoking convertToSeconds as a method | |
| ##print currentTime.convertToSeconds() | |
| ### -> operating with two Time objects | |
| ### invoking a method with two Time objects | |
| ##if lunchTime.after(currentTime): | |
| ## print "The lunch time is not in time yet" | |
| ### optional arguments | |
| ## | |
| ##def find(word, ch, start=0, end=-1): | |
| ## """ prints the index of found ch in word[start:end] """ | |
| ## # stars, end = optional arguments | |
| ## | |
| ## index = start | |
| ## word = word[start:end] | |
| ## while index < len(word): | |
| ## if word[index] == ch: | |
| ## return index | |
| ## index += 1 | |
| ## return -1 | |
| ## | |
| ##print find("xaxxx", "a") | |
| ##print find("xxax", "a") | |
| ##print find("xxa", "a") | |
| ##print find("ax", "a") | |
| ### -> initialization method = special method to invoke when an object is created | |
| ## | |
| ##class Time: | |
| ## def __init__(self, hours=0, minutes=0, seconds=0): | |
| ## self.hours = hours | |
| ## self.minutes = minutes | |
| ## self.seconds = seconds | |
| ## | |
| ## def printTime(self): | |
| ## print "%s:%s:%s" % (self.hours, self.minutes, self.seconds) | |
| ##currentTime = Time(9, 14, 30) | |
| ##currentTime.printTime() | |
| ## | |
| ### because the arguments are optional, we can omit them: | |
| ##currentTime = Time() | |
| ##currentTime.printTime() | |
| ## | |
| ##currentTime = Time(9, 14) | |
| ##currentTime.printTime() | |
| ## | |
| ##currentTime = Time(9) | |
| ##currentTime.printTime() | |
| ### we can also make assignmments by naming a subset of parameters explicity: | |
| ##currentTime = Time(seconds = 30, hours = 9) | |
| ##currentTime.printTime() | |
| ##class Point: | |
| ## def __init__(self, x=0, y=0): | |
| ## """ initialization method of Point object """ | |
| ## self.x = x | |
| ## self.y = y | |
| ## | |
| ## def __str__(self): # overrides the default behavior of the str() func | |
| ## """ overrides the default behaviour of str() """ | |
| ## """ printing an Point object also invokes _str__ """ | |
| ## return "(%d, %d)" % (self.x, self.y) | |
| ## | |
| ##p = Point(3, 4) | |
| ##print p | |
| ## | |
| ### It's a good practice to start a class by sriting __init__, | |
| ### wich makes it easier to instantiate objects, and __str__, | |
| ### which is useful for debugging | |
| ### -> operator overloading = change built-in operators | |
| ## | |
| ##class Point: | |
| ## def __init__(self, x=0, y=0): | |
| ## """ initialization method of Point object """ | |
| ## self.x = x | |
| ## self.y = y | |
| ## | |
| ## def __str__(self): | |
| ## """ overrides the default behaviour of str() and print """ | |
| ## # printing an Point object also invokes _str__ | |
| ## return "(" + str(self.x) + ", " + str(self.y) + ")" | |
| ## | |
| ## def __add__(self, other): | |
| ## """ overrides the '+' operator """ | |
| ## return Point(self.x + other.x, self.y + other.y) | |
| ## | |
| ## def __sub__(self, other): | |
| ## """ overrides the '-' operator """ | |
| ## return Point(self.x - other.x, self.y - other.y) | |
| ## | |
| ## def __mul__(self, other): # used for two objects | |
| ## """ overrides the '*' operator / dot product """ | |
| ## return Point(self.x * other.x, self.y * other.y) | |
| ## | |
| ## def __rmul__(self, other): # one object and a primitive one | |
| ## """ overrides the '*' operator / scalar multiplication""" | |
| ## return Point(other * self.x, other * self.y) | |
| ## | |
| ## def reverse(self): # this method will be used in "Polymorphism" section | |
| ## """ overrides the default behaviour of reverse method """ | |
| ## self.x, self.y = self.y, self.x | |
| ### __str__ | |
| ##p1 = Point(3, 4) | |
| ##print p1 # equivalent to p1.__str__() | |
| ## | |
| ### __add__ | |
| ##p1 = Point(3, 4) | |
| ##p2 = Point(5, 7) | |
| ##total = p1 + p2 # equivalent to p1.__add__(p2) | |
| ##print total | |
| ## | |
| ### __sub__ | |
| ##p1 = Point(3, 4) | |
| ##p2 = Point(5, 7) | |
| ##total = p1 - p2 | |
| ##print total | |
| ## | |
| ### __mul__ | |
| ##p1 = Point(3, 4) | |
| ##p2 = Point(5, 7) | |
| ##total = p1 * p2 # equivalent to p1.__mul__(p2) | |
| ##print total # | |
| ### __rmul__ | |
| ##p1 = Point(3, 4) | |
| ##print 2 * p1 # equivalent to p1.__rmul__(2) | |
| ### -> Polymorphism = functions that can operate on more than one type | |
| ### If all of the operations inside the function can be applied to the type, | |
| ### the function can be applied to the type. | |
| ### example 1 | |
| ##def multadd(x, y, z): | |
| ## """ multiplies the first two pars and adds third """ | |
| ## return x * y + z | |
| ## | |
| ### this func can be aplied to any data type: | |
| ### numeric values | |
| ##print multadd(1, 2, 3) | |
| ## | |
| ### objects | |
| ##p1 = Point(3, 4) | |
| ##p2 = Point(5, 7) | |
| ##print multadd(2, p1, p2) | |
| ### example 2 | |
| ### example that applies frontAndBack to a list: | |
| ##def frontAndBack(front): | |
| ## import copy | |
| ## back = copy.copy(front) | |
| ## back.reverse() | |
| ## print str(front) + str(back) | |
| ## | |
| ##myList = [1, 2, 3, 4] | |
| ##frontAndBack(myList) | |
| ### the function applied to a Point object: | |
| ### first, we need to change default behaviour of 'reverse' inside Point class | |
| ##def reverse(self): | |
| ## self.x, self.y = self.y, self.x | |
| ## | |
| ### now, we can apply the frontAndBack function to a Point object | |
| ##p = Point(3, 4) | |
| ##frontAndBack(p) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # classes and objects | |
| ### -> defining a class | |
| ##class Person: | |
| ## pass # has no effect, but it must have something in its body | |
| ### -> instantiating a class | |
| ##xPerson = Person() | |
| ##xPerson.name = 'mario' | |
| ##xPerson.age = 39 | |
| ##xPerson.gender = 'male' | |
| ##print xPerson.name, xPerson.age, xPerson.gender | |
| ## | |
| ##yPerson = Person() | |
| ##yPerson.name = 'mario' | |
| ##yPerson.age = 39 | |
| ##yPerson.gender = 'male' | |
| ##print yPerson.name, yPerson.age, yPerson.gender | |
| ### -> instances as arguments | |
| ##def printPerson(x, y): | |
| ## print x.name, x.age, x.gender | |
| ## print y.name, y.age, y.gender | |
| ## | |
| ##printPerson(xPerson, yPerson) | |
| # -> shallow equality = comparison of objects' ids | |
| ### 'is' operator = find out if two references refer to the same object | |
| ### it compares only the references(ids) not the contents of the objects | |
| ##print xPerson is yPerson | |
| ##print id(xPerson), id(yPerson) # let's check objects ids | |
| ##xPerson = yPerson | |
| ##print xPerson is yPerson | |
| ##print id(xPerson), id(yPerson) # checking again after aliasing | |
| # -> deep equality = comparison of objects' contents | |
| ### comparing objects' contents | |
| ##def sameContent(x,y): | |
| ## return (x.name == y.name) and (x.age == y.age) and (x.gender == y.gender) | |
| ## | |
| ##print sameContent(xPerson, yPerson) | |
| ### -> retangle | |
| ##class Point: | |
| ## pass | |
| ## | |
| ##class Rectangle: | |
| ## pass | |
| ## | |
| ##box = Rectangle() | |
| ##box.width = 100.0 | |
| ##box.height = 200.0 | |
| ## | |
| ##box.corner = Point() | |
| ##box.corner.x = 0.0 | |
| ##box.corner.y = 0.0 | |
| ### the state of box object is: | |
| ###box -> width -> 100.0 | |
| ### height -> 200.0 | |
| ### corner ----------> x -> 0.0 | |
| ### y -> 0.0 | |
| ### -> instances as return values | |
| ##def findCenter(box): | |
| ## p = Point() | |
| ## p.x = box.corner.x + box.width/2.0 | |
| ## p.y = box.corner.y - box.height/2.0 | |
| ## return p # instance as return value | |
| ## | |
| ##retangleCenter = findCenter(box) | |
| ## | |
| ##def printPoint(p): | |
| ## print '(' + str(p.x) + ', ' + str(p.y) + ')' | |
| ## | |
| ##printPoint(retangleCenter) | |
| ## | |
| ### -> objects are mutable | |
| ### let's change the size of the retangle without changing its position | |
| ##box.width = box.width + 50 | |
| ##box.height = box.height + 100 | |
| ##printPoint(findCenter(box)) | |
| ## | |
| ### let's create a function to grow the retangle by any amount: | |
| ##def growRect(rect, dwidth, dheight): | |
| ## rect.width = rect.width + dwidth | |
| ## rect.height = rect.height + dheight | |
| ## printPoint(findCenter(box)) | |
| ## return "Done" | |
| ## | |
| ##print growRect(box, 40, 80) | |
| ### -> shallow copying = copy the content of an object and | |
| ### references to embeded objects | |
| ##def samePoint(p1, p2): | |
| ## return (p1.x == p2.x) and (p1.y == p2.y) | |
| ## | |
| ### example 1 | |
| ##import copy | |
| ## | |
| ##p1 = Point() | |
| ##p1.x = 3 | |
| ##p1.y = 4 | |
| ##p2 = copy.copy(p1) | |
| ## | |
| ##print p1 == p2 # False | |
| ##print samePoint(p1,p2) # True | |
| ### -> deep copy = copy the content of an object as well as any embedded objects | |
| ## | |
| ### rewriting the growRect function, so that it creates and returns | |
| ### a new rect instead of modifying the old one | |
| ##def growRect(rect, dwidth, dheight): | |
| ## import copy | |
| ## newBox = copy.deepcopy(rect) | |
| ## newBox.width = newBox.width + dwidth | |
| ## newBox.height = newBox.height + dheight | |
| ## return newBox | |
| ## | |
| ##printPoint(findCenter(growRect(box, 100, 200))) | |
| ##print 'box id=', id(box), ' and ', 'newBox id=', id(newBox) | |
| ##print samePoint(box.corner, newBox.corner) | |
| # more content from classes and objects... | |
| ### classes and objects | |
| ##class Person(object): | |
| ## def __init__(self, name, age, gender, has_tattoo): | |
| ## self.name = name # assign name value to object | |
| ## self.age = age | |
| ## self.gender = gender | |
| ## self.has_tattoo = has_tattoo | |
| ## | |
| ##mario = Person("mario", 22, "male", True) | |
| ##karine = Person("karine", 22, "female", False) | |
| ##print mario.name, mario.age, mario.gender, mario.has_tattoo | |
| ##print karine.name, karine.age, karine.gender, karine.has_tattoo | |
| # __ini__() = initialize the object it creates | |
| # self = refers to the object being created | |
| # -> class scope | |
| # global variable/function = available everywhere | |
| # member variable/function = available to members of a certain class | |
| # instance variable/function = available to particular instances of class | |
| ### e.g: | |
| ## | |
| ##class Animal(object): | |
| ## """Makes cute animals.""" | |
| ## is_alive = True # member variable | |
| ## def __init__(self, name, age): | |
| ## self.name = name # instance variable | |
| ## self.age = age | |
| ## | |
| ##zebra = Animal("Jeffrey", 2) | |
| ##giraffe = Animal("Bruce", 1) | |
| ##panda = Animal("Chad", 7) | |
| ## | |
| ##print zebra.name, zebra.age, zebra.is_alive | |
| ##print giraffe.name, giraffe.age, giraffe.is_alive | |
| ##print panda.name, panda.age, panda.is_alive | |
| ### -> methods = functions from a class | |
| ##class ShoppingCart(object): | |
| ## """Creates shopping cart objects | |
| ## for users of our fine website.""" | |
| ## items_in_cart = {} | |
| ## def __init__(self, customer_name): | |
| ## self.customer_name = customer_name | |
| ## | |
| ## def add_item(self, product, price): | |
| ## """Add product to the cart.""" | |
| ## | |
| ## if not product in self.items_in_cart: | |
| ## self.items_in_cart[product] = price | |
| ## print product + " added." | |
| ## else: | |
| ## print product + " is already in the cart." | |
| ## | |
| ## def remove_item(self, product): | |
| ## """Remove product from the cart.""" | |
| ## | |
| ## if product in self.items_in_cart: | |
| ## del self.items_in_cart[product] | |
| ## print product + " removed." | |
| ## else: | |
| ## print product + " is not in the cart." | |
| ## | |
| ##my_cart = ShoppingCart("mario") | |
| ##ShoppingCart.add_item(my_cart, "bear", 1.50) | |
| ##ShoppingCart.add_item(my_cart, "vodka", 10) | |
| ##print ShoppingCart.items_in_cart | |
| ### -> inheritance | |
| ### syntax = class DerivedClass(BaseClass) | |
| ### overrride | |
| ## | |
| ##class Employee(object): # superclass | |
| ## """Models real-life employees!""" | |
| ## def __init__(self, employee_name): | |
| ## self.employee_name = employee_name | |
| ## | |
| ## # original function | |
| ## def calculate_wage(self, hours): | |
| ## self.hours = hours | |
| ## return hours * 20.00 | |
| ## | |
| ##class PartTimeEmployee(Employee): | |
| ## | |
| ## # this functions overrides the first one | |
| ## def calculate_wage(self, hours): | |
| ## self.hours = hours | |
| ## return hours * 12.00 | |
| ##class Triangle(object): | |
| ## number_of_sides = 3 | |
| ## def __init__(self, angle1, angle2, angle3): | |
| ## self.angle1 = angle1 | |
| ## self.angle2 = angle2 | |
| ## self.angle3 = angle3 | |
| ## | |
| ## def check_angles(self): | |
| ## sum = self.angle1 + self.angle2 + self.angle3 | |
| ## if sum == 180: | |
| ## return True | |
| ## else: | |
| ## return False | |
| ## | |
| ##angles = Triangle(60,60,60) | |
| ##print Triangle.check_angles(angles) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> logical operators | |
| ##not | |
| ##or | |
| ##and | |
| ##if x % 2 == 0: | |
| ## print x, "is even" | |
| ##else: | |
| ## print x, "is odd" | |
| ### -> creating a function to check if a number is even or odd | |
| ##def isEven(number): | |
| ## if number % 2 == 0: | |
| ## print number, "is even" | |
| ## else: | |
| ## print number, "is odd" | |
| ### -> elseif statments | |
| ##choice = str(raw_input("Enter a consoant\n")) | |
| ## | |
| ##if choice == 'A': | |
| ## print "functionA()" | |
| ##elif choice == 'B': | |
| ## print "functionB()" | |
| ##else: | |
| ## print "Invalid Choice." | |
| ### -> conditional + function | |
| ### input | |
| ##x = int(raw_input("Enter x value\n")) | |
| ##y = int(raw_input("Now, enter y value\n")) | |
| ## | |
| ### function creation | |
| ##def compare(x, y): | |
| ## if (x % 2 == 0) and (y % 2 == 0): | |
| ## print x, " and ", y, "are even" | |
| ## elif (x % 2 == 0) and (y % 2 != 0): | |
| ## print "only ", x, "is even. ", y, " is odd" | |
| ## elif (y % 2 == 0) and (x % 2 != 0): | |
| ## print "only ", y, "is even. ", x, " is odd" | |
| ## else: | |
| ## print x, " and ", y, " are odd" | |
| ## | |
| ### function call | |
| ##compare(x, y) | |
| ### -> nested conditionals | |
| ## | |
| ##if 2 != 0: | |
| ## if 2 > 1: | |
| ## print "2 is positive" | |
| ## else: | |
| ## print "2 is not positive" | |
| ### -> return statements | |
| ## | |
| ##import math | |
| ## | |
| ##def printLogarithm(x): | |
| ## # validation | |
| ## if x <= 0: | |
| ## print "Positive numbers only, please." | |
| ## return # exit the function | |
| ## | |
| ## # continue the program execution... | |
| ## result = math.log(x) | |
| ## print "the log of x is", result | |
| ### -> recursion | |
| ### example 1 | |
| ##def countdown(n): | |
| ## if n == 0: | |
| ## print "Blastoff" | |
| ## else: | |
| ## print n | |
| ## countdown(n-1) | |
| ### example 1 | |
| ##def newLines(n): | |
| ## if n > 0: | |
| ## newLines(n-1) | |
| ### -> infinite recursion | |
| ##def recurse(): | |
| ## recurse() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -> creating a new data type | |
| # -> euclid's algorithm = reduce the fraction to its simplest terms | |
| def gcd(m, n): | |
| if m % n == 0: | |
| return n | |
| else: | |
| return gcd(n,m%n) | |
| # -> Fraction class | |
| class Fraction: | |
| def __init__(self, numerator, denominator=1): | |
| g = gcd(numerator, denominator) | |
| self.numerator = numerator / g | |
| self.denominator = denominator / g | |
| def __str__(self): | |
| """ default behaviour of str() and print """ | |
| if self.denominator == 1: | |
| return str(self.numerator) | |
| return "%d/%d" % (self.numerator, self.denominator) | |
| def __cmp__(self, other): | |
| """ default behaviour of comparators """ | |
| diff = (self.numerator * other.denominator - | |
| other.numerator * self.denominator) | |
| return diff | |
| def __mul__(self, other): | |
| """ default behaviour of multiplication (*) operator """ | |
| if isinstance(other, int): | |
| other = Fraction(other) | |
| return Fraction(self.numerator * other.numerator, | |
| self.denominator * other.denominator) | |
| __rmul__ = __mul__ # rmul is now the same as mul | |
| def __div__(self, other): | |
| """ default behaviour of division (/) operator """ | |
| if isinstance(other, int): | |
| other = Fraction(other) | |
| return Fraction(self.numerator * other.denominator, | |
| self.denominator * other.numerator) | |
| __rdiv__ = __div__ # rvid is now the same as div | |
| def __add__(self, other): | |
| """ default behaviour of sum (+) operator """ | |
| if isinstance(other, int): | |
| other = Fraction(other) | |
| return Fraction(self.numerator * other.denominator + | |
| self.denominator * other.numerator, | |
| self.denominator * other.denominator) | |
| __radd__ = __add__ # radd is now the same as add | |
| def __sub__(self, other): | |
| """ default behaviour of subtraction (-) operator """ | |
| if isinstance(other, int): | |
| other = Fraction(other) | |
| return Fraction(self.numerator * other.denominator - | |
| self.denominator * other.numerator, | |
| self.denominator * other.denominator) | |
| __rsub__ = __sub__ # rsub is now the same as sub | |
| def __pow__(self, other): | |
| """ default behaviour or exponential (**) operator """ | |
| if isinstance(other, int): | |
| # if other object is an integer | |
| total = 1 | |
| while other > 0: | |
| total *= Fraction(self.numerator, self.denominator) | |
| other -= 1 | |
| return total | |
| else: | |
| return False | |
| __rpow__ = __pow__ # rpow is now the same as pow | |
| # invoking __pow__ and __rpow__ | |
| pow1 = 2 ** Fraction(1,2) | |
| rpow = Fraction(1,2) ** 2 | |
| print pow1, rpow | |
| # checking implementation | |
| # invoking __mul__ and __rmul__ | |
| mul1 = Fraction(1,2) * Fraction(3,4) | |
| mul2 = Fraction(1,2) * 2 | |
| rmul = 2 * Fraction(1,2) | |
| print mul1, mul2, rmul | |
| ### invoking __div__ and __rdiv__ | |
| div1 = Fraction(1,2) / Fraction(1,2) | |
| div2 = Fraction(1,2) / 2 | |
| rdiv = 2 / Fraction(1,2) | |
| print div1, div2, rdiv | |
| # invoking __add__ and __radd__ | |
| add1 = Fraction(1,2) + Fraction(3,4) | |
| add2 = Fraction(1,2) + 2 | |
| radd = 2 + Fraction(1,2) | |
| print add1, add2, radd | |
| # invoking __sub__ and __rsub__ | |
| sub1 = Fraction(1) - 5 | |
| sub2 = Fraction(10,3) - 1 | |
| rsub = 1 - Fraction(10,3) | |
| print sub1, sub2, rsub | |
| # invoking __cmp__ | |
| print (add2 == radd) | |
| print add2 < radd | |
| print mul1 > mul2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### dictionaries | |
| ### unodered list, the index is immutable, the values are mutable | |
| ### e.g: dict = {'name': 'mario', 'age': 22} | |
| ##empty = {} | |
| ##empty['first index'] = 'uno' | |
| ##empty['second index'] = 2 | |
| ## | |
| ### -> operations | |
| ## | |
| ### del | |
| ##color_to_fruits = {'red': 'apple', 'yellow': 'banana', 'orange': 'orange'} | |
| ##del color_to_fruits['red'] | |
| ##print color_to_fruits | |
| ## | |
| ### update | |
| ##color_to_fruits['orange'] = 'laranja' | |
| ##print color_to_fruits | |
| ## | |
| ### lenght | |
| ##print len(color_to_fruits) # number of indeces | |
| ### -> methods | |
| ## | |
| ### keys | |
| ### returns dict indeces | |
| ##print color_to_fruits.keys() | |
| ## | |
| ### values | |
| ### returns dict values | |
| ##print color_to_fruits.values() | |
| ## | |
| ### items | |
| ### returns both indeces and values from dict as a list with tuples | |
| ##print color_to_fruits.items() | |
| ## | |
| ### has_keys | |
| ### returns True if argument is in the dict's indeces | |
| ##print color_to_fruits.has_key('red') | |
| ### -> aliasing and copying | |
| ## | |
| ##opposites = {'up':'down', 'right':'wrong', 'true':'false'} | |
| ## | |
| ##alias = opposites # two variables refering to the same object | |
| ### if we modify one, the other is also changed | |
| ##alias['right'] = 'left' | |
| ##print opposites['right'] | |
| ## | |
| ##copy = opposites.copy() # this is a copy of opposites' dict | |
| ### if we modify copy, it will not change opposites | |
| ##copy['right'] = 'privilege' | |
| ##print opposites['right'] | |
| ### -> sparce matrices | |
| ## | |
| ### matrix using list | |
| ##matrix_list = [ [0, 0, 0, 1, 0], | |
| ## [0, 0, 0, 0, 0], | |
| ## [0, 2, 0, 0, 0], | |
| ## [0, 0, 0, 0, 0], | |
| ## [0, 0, 0, 3, 0] ] | |
| ## | |
| ### accessing elements: | |
| ##print matrix_list[0][3] | |
| ##print matrix_list[2][1] | |
| ##print matrix_list[4][3] | |
| ##print matrix_list[3][1] # it returns 0 | |
| ## | |
| ### matrix using dict, tuples as keys | |
| ##matrix_dict = {(0,3): 1, (2, 1): 2, (4, 3): 3} | |
| ### accessing elements: | |
| ##print matrix_dict[0,3] | |
| ##print matrix_dict[2,1] | |
| ##print matrix_dict[4,3] | |
| ###print matrix_dict[3,1] # there's no element with this key | |
| ### this will fix the error above | |
| ##print matrix_dict.get((1,3),0) # get(dict key, value if key doesn't exists) | |
| ### -> hints | |
| ### keep track of values that have already been computed by storing in a dict | |
| ## | |
| ### fibonacci example | |
| ##previous = {0:1, 1:1} | |
| ## | |
| ##def fibonacci(x): | |
| ## if previous.has_key(x): | |
| ## return previous[x] | |
| ## else: | |
| ## newValue = fibonacci(x-1) + fibonacci(x-2) | |
| ## previous[x] = newValue | |
| ## return newValue | |
| ## | |
| ##print fibonacci(50) | |
| ### -> couting letters | |
| ## | |
| ##letterCounts = {} | |
| ##for letter in "Mississippi": | |
| ## letterCounts[letter] = letterCounts.get(letter, 0) + 1 | |
| ## print 'letterCounts[',letter,']', letterCounts[letter] | |
| ##print letterCounts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -> syntax errors | |
| SyntaxError: invalid syntax | |
| SyntaxError: invalid token | |
| # -> runtime errors | |
| RuntimeError: maximum recursion depth exceeded | |
| NameError | |
| TypeError | |
| KeyError | |
| AttributeError | |
| IndexError |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #### files and exceptions | |
| ### creating, writing, openning and copying files | |
| ## | |
| ### -> writing | |
| ### a. if the file doesn't exists yet, it will be created | |
| ### b. elif the file already exists, it will be replaced | |
| ##f = open("name.extension", "w") # open in writing mode | |
| ##f.write("Write something over here") # write | |
| ##f.close() # close | |
| ## | |
| ### -> reading | |
| ##f = open("name.extension", "r") # open in reading mode | |
| ##print f.read() # read its entire content | |
| ##print f.read(5) # or st art to read after a limited number of characters | |
| ## -> closing | |
| # Python will not write/read the file properly if you don't close your files after doing something with them | |
| ## first method | |
| ##file_name.close() | |
| ## alternative method | |
| ##with open("test.txt", "w") as my_file: | |
| ## my_file.write("I'm writing") | |
| # it will be closed automatically | |
| ## to make sure the file has been closed properly, we can create a if statement after with/as: | |
| ##if not my_file.closed: | |
| ## my_file.close() | |
| ### mixing things up | |
| ## | |
| ##def copyFile(oldFile, newFile): | |
| ## """ copies a file, reading and writing | |
| ## up to 50 characters at a time """ | |
| ## f1 = open(oldFile, "r") # open in reading mode | |
| ## f2 = open(newFile, "w") # open in writing mode, creates a new file | |
| ## while True: | |
| ## text = f1.read(50) | |
| ## if text == "": # when read method reach the end of the file | |
| ## break | |
| ## f2.write(text) # copying content from old file to the new file | |
| ## # closing both files | |
| ## f1.close() | |
| ## f2.close() | |
| ## return | |
| ### -> methods | |
| ### readline | |
| ##def readlineFile(): | |
| ## """ reads all the characters up to and including the | |
| ## next newline (\n) character""" | |
| ## f = open("test.dat", "w") | |
| ## f.write("first\nsecond\nthird") | |
| ## f.close() | |
| ## f = open("test.dat", "r") | |
| ## print f.readline() | |
| ## f.close() | |
| ## return "Done!" | |
| ### readlines | |
| ##def readlinesFile(): | |
| ## """ returns all the remaining lines as a list of strings """ | |
| ## f = open("test.dat", "w") | |
| ## f.write("first\nsecond\nthird") | |
| ## f = open("test.dat", "r") | |
| ## print f.readlines() | |
| ## f.close() | |
| ## return "Done!" | |
| ### mixing things up | |
| ## | |
| ##def filterFile(oldFile, newFile, ch): | |
| ## """ makes a copy of 'oldFile', omitting any | |
| ## lines that begin with 'ch' """ | |
| ## | |
| ## f1 = open(oldFile, "r") | |
| ## f2 = open(newFile, "w") | |
| ## while True: | |
| ## text = f1.readline() | |
| ## if text == "": | |
| ## break | |
| ## if text[0] == ch: | |
| ## continue | |
| ## f2.write(text) | |
| ## f1.close() | |
| ## f2.close() | |
| ## return | |
| ### -> writing variables | |
| ### 1st example | |
| ##age = 22 | |
| ##str(age) | |
| ## | |
| ### 2nd example | |
| ### 'd' = decimal | |
| ##age = 22 | |
| ##"Mario has %d years old." % age | |
| ## | |
| ### 'f' = float | |
| ##grade = 1.5 | |
| ##"My grad is %f" % grade | |
| ## | |
| ### 's' = string | |
| ##name = "Mario" | |
| ##"Hi there! My name is %s" % name | |
| ## | |
| ### mixing things up | |
| ##name = "Luan" | |
| ##age = 22 | |
| ##grade = 1.5 | |
| ##"My name is %s, I'm %d and my grade was %f" % (name, age, grade) | |
| ## | |
| ### defining a minimum number of digits for each element | |
| ### e.g: %10s, %2d, %1.2f | |
| ### useful when working with float-point numbers | |
| ##"My name is %s, I'm %d and my grade was %1.2f" % (name, age, grade) | |
| ##def report(wages): | |
| ## students = wages.keys() | |
| ## students.sort() | |
| ## for student in students: | |
| ## print "%-20s %12.2f" % (student, wages[student]) | |
| ## | |
| ##>>> wages = {'mary': 6.23, 'joe': 5.45, 'joshua': 4.25} | |
| ##>>> report(wages) | |
| ##joe 5.45 | |
| ##joshua 4.25 | |
| ##mary 6.23 | |
| ### -> directories | |
| ##def readFile(): | |
| ## f = open("/home/mario/Desktop/test.dat", "r") | |
| ## print f.readlines() | |
| ## f.close() | |
| ### -> pickling | |
| ### preserves data structures | |
| ## | |
| ##>>> import pickle | |
| ##>>> f = open("test.dat", "w") | |
| ##>>> pickle.dump(12.3, f) | |
| ##>>> pickle.dump([1, 2, 3], f) | |
| ##>>> f.close() | |
| ##>>> f = open("test.dat", "r") | |
| ##>>> x = pickle.load(f) | |
| ##>>> x | |
| ##12.3 | |
| ##>>> type(x) | |
| ##<type 'float'> | |
| ##>>> y = pickle.load(f) | |
| ##>>> y | |
| ##[1, 2, 3] | |
| ##>>> type(y) | |
| ##<type 'list'> | |
| ### -> exceptions | |
| ### handling erros: try, except and raise | |
| ## | |
| ##def fileExists(filename): | |
| ## try: | |
| ## f = open(filename) | |
| ## f.close() | |
| ## return True | |
| ## except IOError: # type or the error | |
| ## return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -> return values | |
| ### example 1 | |
| ##import math | |
| ##def area(radius): | |
| ## temp = math.pi * radius**2 | |
| ## return temp | |
| ### example 2 | |
| ##import math | |
| ##def area(radius): | |
| ## return math.pi * radius**2 | |
| ### example 3, using return for debugging | |
| ##def absoluteValue(x): | |
| ## if x < 0: | |
| ## return -x | |
| ## else: | |
| ## return x | |
| ### example 4 | |
| ## | |
| ##def compare(x, y): | |
| ## if x == y: | |
| ## return 0 | |
| ## elif x > y: | |
| ## return 1 | |
| ## else: | |
| ## return -1 | |
| ### -> Program development | |
| ### test functions before released it | |
| ### first step | |
| ##def distance(x, y): | |
| ## return 0.0 | |
| ### second step | |
| ##def distance(x1, y1, x2, y2): | |
| ## dx = x2 - x1 | |
| ## dy = y2 - y1 | |
| ## print "dx is", dx | |
| ## print "dy is", dy | |
| ## return 0.0 | |
| ### third step | |
| ##def distance(x1, y1, x2, y2): | |
| ## dx = x2 - x1 | |
| ## dy = y2 - y1 | |
| ## dsquared = dx**2 + dy**2 | |
| ## print "dsquared is: ", dsquared | |
| ## return 0.0 | |
| ### fourth and final step | |
| ##def distance(x1, y1, x2, y2): | |
| ## dx = x2 - x1 | |
| ## dy = y2 - y1 | |
| ## dsquared = dx**2 + dy**2 | |
| ## result = math.sqrt(dsquared) | |
| ## return result | |
| ### -> composition | |
| ### creating a function using others functions inside it | |
| ### example 1, debugging version | |
| ##def area2(xc, yc, xp, yp): | |
| ## radius = distance(1, 2, 4, 6) | |
| ## result = area(radius) | |
| ## return result | |
| ## example 2 | |
| ##def area2(xc, yc, xp, yp): | |
| ## return area(distance(xc, yc, xp, yp)) | |
| ### -> boolean functions | |
| ### example using IFs | |
| ##def isDivisible(x, y): | |
| ## if x % y == 0: | |
| ## return True | |
| ## else: | |
| ## return False | |
| ### example using RETURN | |
| ##def isDivisible(x, y): | |
| ## return x % y == 0 | |
| ### -> more recursion | |
| ### debugging example | |
| ##def factorial(n): | |
| ## if n == 0: | |
| ## return 1 | |
| ## else: | |
| ## recurse = factorial(n-1) | |
| ## result = n * recurse | |
| ## return result | |
| ## | |
| ### simple example | |
| ##def factorial(n): | |
| ## if n == 0: | |
| ## return 1 | |
| ## else: | |
| ## return n * factorial(n-1) | |
| ### -> fibonacci | |
| ## | |
| ##def fibonacci(n): | |
| ## if n == 0 or n == 1: | |
| ## return 1 | |
| ## else: | |
| ## return fibonacci(n-1) + fibonacci(n-2) | |
| ##def factorial(n): | |
| ## if not isinstance(n, int): | |
| ## print "Factorial is only defined for integers." | |
| ## return -1 | |
| ## elif n < 0: | |
| ## print "Factorial is only defined for positive integers." | |
| ## return -1 | |
| ## elif n == 0: | |
| ## return 1 | |
| ## else: | |
| ## return n * factorial(n-1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> creating functions | |
| ##def newLine(): | |
| ## | |
| ### function that prints two single lines, using the function above | |
| ##def twoLines(): | |
| ## newLine() | |
| ## newLine() | |
| ## | |
| ### function that prints two single lines from function above and one single line from the first function | |
| ##def threeLines(): | |
| ## twoLines() | |
| ## newLine() | |
| ### -> arguments and parameters | |
| ##def printTwice(parameter): | |
| ## print parameter, parameter | |
| ## | |
| ##printTwice(1) | |
| ### -> recursive function | |
| ##def nLines(n): | |
| ## if n > 0: | |
| ## nLines(n-1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### is_divisible | |
| ##def is_divisible(m,n): | |
| ## if m % n == 0: | |
| ## return True | |
| ## else: | |
| ## return False | |
| ## | |
| ### =! | |
| ##def not_equal(x, y): | |
| ## if x == y: | |
| ## return False | |
| ## else: | |
| ## return True | |
| ### radians | |
| ##import math | |
| ## | |
| ##radians = (280.0 / 360.0) * 2 * math.pi | |
| ##print math.sin(radians) | |
| ### multadd | |
| ##def multadd(a, b, c): | |
| ## x = a * b + c | |
| ## return x | |
| ##import math | |
| ##angle_test = math.sin(math.pi/4) + math.cos(math.pi/4)/2 | |
| ##ceiling_test = math.ceil(276/19) + 2*math.log(12, 7) | |
| ## | |
| ##print angle_test | |
| ##print ceiling_test | |
| ##import math | |
| ## | |
| ##def exe_3(x): | |
| ## return x *(math.e**-x) + math.sqrt(1 - (math.e**-x)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> inheritance | |
| ### desc: define a new class that is a modified version of an existing class | |
| ## | |
| ##class Card: | |
| ## # class attributes | |
| ## suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] | |
| ## rankList = ["nothing_here", "Ace", "2", "3", "4", "5", "6", | |
| ## "7", "8", "9", "10", "Jack", "Queen", "King"] | |
| ## | |
| ## def __init__(self, suit=0, rank=2): | |
| ## self.suit = suit | |
| ## self.rank = rank | |
| ## | |
| ## def __str__(self): | |
| ## return (self.rankList[self.rank] + " of " + self.suitList[self.suit]) | |
| ## | |
| ## def __cmp__(self, other): | |
| ## """ compares cards """ | |
| ## # check the suits | |
| ## if self.suit > other.suit: | |
| ## return 1 | |
| ## if self.suit < other.suit: | |
| ## return -1 | |
| ## | |
| ## # suits are the same... check ranks | |
| ## | |
| ## # in case we're dealing with Ace rank | |
| ## if self.rank == 1 and other.rank != 1: | |
| ## return 1 | |
| ## elif self.rank != 1 and other.rank == 1: | |
| ## return -1 | |
| ## | |
| ## if (self.rank != 1 and other.rank != 1) and self.rank > other.rank: | |
| ## return 1 | |
| ## elif (self.rank != 1 and other.rank != 1) and self.rank < other.rank: | |
| ## return -1 | |
| ## # ranks are the same.. it's a tie | |
| ## return 0 | |
| ## | |
| ##class Deck: | |
| ## def __init__(self): | |
| ## self.cards = [] | |
| ## for suit in range(4): | |
| ## for rank in range(1, 14): | |
| ## self.cards.append(Card(suit, rank)) | |
| ## | |
| ## # printing | |
| ## # nice print | |
| ## def __str__(self): | |
| ## s = "" | |
| ## for i in range(len(self.cards)): | |
| ## s = s + " "*i + str(self.cards[i]) + "\n" | |
| ## return s | |
| ## | |
| ## # basic print | |
| ## def printDeck(self): | |
| ## for card in self.cards: | |
| ## print card | |
| ## | |
| ## # shuffling | |
| ## def shuffle(self): | |
| ## import random | |
| ## nCards = len(self.cards) | |
| ## for i in range(nCards): | |
| ## j = random.randrange(i, nCards) | |
| ## self.cards[i], self.cards[j] = self.cards[j], self.cards[i] | |
| ## | |
| ## # removing | |
| ## def removeCard(self, card): | |
| ## # note: Python uses the object's __cmp__ method to | |
| ## # determine equality with items in the list | |
| ## if card in self.cards: | |
| ## self.cards.remove(card) | |
| ## return True | |
| ## else: | |
| ## return False | |
| ## | |
| ## def popCard(self): | |
| ## """ removes the last card in the list """ | |
| ## return self.cards.pop() | |
| ## | |
| ## def isEmpty(self): | |
| ## """ returns true if deck contains no cards """ | |
| ## return (len(self.cards) == 0) | |
| ## | |
| ## def nCards(self): | |
| ## """ returns the number of cards in deck """ | |
| ## return len(self.cards) | |
| ## | |
| ## def deal(self, hands, nCards=999): | |
| ## """ takes in: the deck, a list/tuple of hands and | |
| ## total number of cards to deal. """ | |
| ## nHands = len(hands) # len(number of hands) | |
| ## for i in range(nCards): | |
| ## if self.isEmpty(): # break if out of cards | |
| ## break | |
| ## card = self.popCard() # take the top card | |
| ## hand = hands[i % nHands] # whose turn is next? | |
| ## hand.addCard(card) # add the card to the hand | |
| ## | |
| ##class Hand(Deck): | |
| ## # Deck = parent | |
| ## # Hand = child/subclass | |
| ## | |
| ## def __init__(self, name=""): | |
| ## self.cards = [] # list of cards in the hand | |
| ## self.name = name # player's name | |
| ## | |
| ## def __str__(self): | |
| ## """ this method overrides parent's one """ | |
| ## s = "Hand " + self.name | |
| ## if self.isEmpty(): | |
| ## return s + " is empty\n" | |
| ## else: | |
| ## return s + " contains\n" + Deck.__str__(self) | |
| ## | |
| ## def addCard(self, card): | |
| ## self.cards.append(card) | |
| ## | |
| ## | |
| ##deck = Deck() | |
| ##deck.shuffle() | |
| ##hand1 = Hand("mario") | |
| ##hand2 = Hand("luan") | |
| ##deck.deal([hand1, hand2], 10) | |
| ##print hand1 | |
| ##print hand2 | |
| ## | |
| ### -> the CardGame | |
| ##class CardGame: | |
| ## | |
| ## def __init__(self): | |
| ## self.deck = Deck() | |
| ## self.deck.shuffle() | |
| ## | |
| ### Old maid game simulation | |
| ## | |
| ##class OldMaidHand(Hand): | |
| ## | |
| ## def removeMatches(self): | |
| ## count = 0 | |
| ## originalCards = self.cards[:] | |
| ## for card in originalCards: | |
| ## match = Card(3 - card.suit, card.rank) | |
| ## if match in self.cards: | |
| ## self.cards.remove(card) | |
| ## self.cards.remove(match) | |
| ## print "Hand %s: %s matches %s" % (self.name, card, match) | |
| ## count += 1 | |
| ## return count | |
| ## | |
| ## def printHands(self): | |
| ## for hand in self.hands: | |
| ## print hand | |
| ## | |
| ### example 1 | |
| ##game = CardGame() # new game object (init and shuffle deck) | |
| ##hand = OldMaidHand("frank") # new hand object (player's name) | |
| ##game.deck.deal([hand], 13) # generates player's cards | |
| ##print hand # prints player's cards | |
| ##hand.removeMatches() # remove matching cards | |
| ##print hand # prints player's cards after removal |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> Mutiple assignment | |
| ##bruce = 5 | |
| ##print bruce, | |
| ##bruce = 7 | |
| ##print bruce | |
| ##a = 5 | |
| ##print a | |
| ##b = a # a and b are now equal | |
| ##print a, b | |
| ##a = 3 # a and b are no longer equal | |
| ##print a | |
| # -> while statement | |
| ##def countdown(n): | |
| ## while n > 0: | |
| ## print n | |
| ## n = n-1 | |
| ## | |
| ## print "Bastoff!" | |
| ##def countdown(n): | |
| ## while n != 1: | |
| ## print n, | |
| ## if n % 2 == 0: #n is even | |
| ## n = n/2 | |
| ## else: | |
| ## n = n*3+1 #n is odd | |
| ### -> function using iteration | |
| ##def nLines(n): | |
| ## l = n | |
| ## while n > 0: | |
| ## n = n-1 | |
| ## print "There're were printed", l, "lines" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### lambdas | |
| ### useful when we need a quick function to do some work for | |
| ## | |
| ### -> anonymous functions | |
| ##my_list = range(16) | |
| ##print filter(lambda x: x % 3 == 0, my_list) | |
| ### lambda is equivalent to: | |
| ##def by_three(x): | |
| ## return x % 3 == 0 | |
| ## | |
| ### -> syntax | |
| ##""" lambda variable: expression """ | |
| ##""" filter(function, sequence) """ | |
| ## | |
| ### -> extract the secret message | |
| ### using list slicing | |
| ##garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI" | |
| ##message = garbled[-1::-2] | |
| ##print message | |
| ## | |
| ### using lambda \o/ | |
| ##garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX" | |
| ##message = filter(lambda x: x != "X", garbled) | |
| ##print message |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### lecture 4 | |
| ##x = 0.5 | |
| ##epsilon = 0.01 | |
| ##low = 0.0 | |
| ##high = max(x, 1.0) | |
| ##ans = (high + low)/2.0 | |
| ##while abs(ans**2 - x) >= epsilon and ans <= x: | |
| ## print 'ans =', ans, 'low =', low, 'high =', high | |
| ## if ans**2 < x: | |
| ## low = ans | |
| ## else: | |
| ## high = ans | |
| ## ans = (high + low)/2.0 | |
| ##print ans, 'is close to square root of', x | |
| ##def withinEpsilon(x, y, epsilon): | |
| ## """x,y,epsilon ints or floats. epsilon > 0.0 | |
| ## returns True if x is within epsilon of y""" | |
| ## return abs(x - y) <= epsilon | |
| ##print withinEpsilon(2,3,1) | |
| ##val = withinEpsilon(2,3,0.5) | |
| ##print val | |
| ##def f(x): | |
| ## x = x + 1 | |
| ## print 'x =', x | |
| ## return x | |
| ## | |
| ##x = 3 | |
| ##z = f(x) | |
| ##print 'z =', z | |
| ##print 'x =', x | |
| ##def f1(x): | |
| ## def g(): | |
| ## x = 'abc' | |
| ## x = x + 1 | |
| ## print 'x =', x | |
| ## g() | |
| ## assert False # validation, it stops the program if set to False | |
| ## return x | |
| ## | |
| ##x = 3 | |
| ##z = f1(x) | |
| ## | |
| ##def isEven(i): | |
| ## """assumes i a positive int | |
| ## returns True if i is even, otherwise False""" | |
| ## return i%2 == 0 | |
| ## | |
| ##def findRoot(pwr, val, epsilon): | |
| ## """assumes pwr an int; val, epsilon floats | |
| ## pwr and epsilon > 0 | |
| ## if it exists, | |
| ## returns a value within epsilon of val**pwr | |
| ## otherwise returns None""" | |
| ## assert type(pwr) == int and type(val) == float\ | |
| ## and type(epsilon) == float | |
| ## assert pwr > 0 and epsilon > 0 | |
| ## if isEven(pwr) and val < 0: | |
| ## return None | |
| ## low = -abs(val) | |
| ## high = max(abs(val), 1.0) | |
| ## ans = (high + low)/2.0 | |
| ## while not withinEpsilon(ans**pwr, val, epsilon): | |
| ## #print 'ans =', ans, 'low =', low, 'high =', high | |
| ## if ans**pwr < val: | |
| ## low = ans | |
| ## else: | |
| ## high = ans | |
| ## ans = (high + low)/2.0 | |
| ## return ans | |
| ##def testFindRoot(): | |
| ## """x float, epsilon float, pwr positive int""" | |
| ## for x in (-1.0, 1.0, 3456.0): | |
| ## for pwr in (1, 2, 3): | |
| ## ans = findRoot(pwr, x, 0.001) | |
| ## if ans == None: | |
| ## print 'The answer is imaginary' | |
| ## else: | |
| ## print ans, 'to the power', pwr,\ | |
| ## 'is close to', x | |
| #testFindRoot() | |
| ##sumDigits = 0 | |
| ##for c in str(1952): | |
| ## sumDigits += int(c) | |
| ##print sumDigits | |
| ##x = 100 | |
| ##divisors = () | |
| ##for i in range(1, x): | |
| ## if x%i == 0: | |
| ## divisors = divisors + (i,) | |
| ## | |
| ##print divisors | |
| ##print divisors[0] + divisors[1] | |
| ##print divisors[2:4] | |
| ### recitation 2 | |
| ### Prints even numbers from 2 to 10 | |
| ## while loop | |
| ##even_number = 2 | |
| ##while (even_number <= 10): | |
| ## print even_number | |
| ## even_number += 2 | |
| ### for loop | |
| ##for i in (2, 4, 6, 8, 10): | |
| ## print i | |
| ### range function | |
| ##for i in range(2,11,2): | |
| ## print i | |
| ### Tuple - ordered list of elements | |
| """ | |
| *immutable, enclose in parentheses, accept slices and indeces for selections. | |
| **creating a tuple with a single element, requires a comma.Without the comma, | |
| Python treats it as a string, eg: | |
| tuple = ('a',) | |
| type(tuple) | |
| tuple = ('a') | |
| type(tuple) | |
| """ | |
| ### we can't modify | |
| ##tuple_a = ['a', 'b', 'c'] | |
| ##tuple_a[0] = 'A' | |
| ##> Error | |
| ## | |
| ### but we can create a new tuple | |
| ##tuple_b = ('A',) + tuple_a[1:] | |
| ##tuple_b | |
| ##> ('A', 'b', 'c') | |
| ##tuple_of_numbers = (3.14159, 2, 1, -100, 100, 240) | |
| ##tuple_of_strings = ('What', 'is', 'my', 'name') | |
| # usage examples | |
| ##print tuple_of_numbers[1] | |
| ##print tuple_of_strings[0] | |
| ##print tuple_of_strings[-3] | |
| ##print tuple_of_strings[4] | |
| ## | |
| # how many elements in the tuple? | |
| ##print len(tuple_of_numbers) | |
| ## | |
| #### can hold different types | |
| ##tuple_of_numbers_and_strings = (22, 'is', 'an even', 'number', 'divided by', 2) | |
| ## including other tuples | |
| ##tuple_of_tuples = (('mario', 'luan'), 55, 'got') | |
| ##print tuple_of_tuples[0] | |
| ##print tuple_of_tuples[0][0] | |
| ##print tuple_of_tuples[0][1] | |
| ##print len(tuple_of_tuples) | |
| # slice | |
| ##print tuple_of_numbers[1:3] | |
| ##print tuple_of_numbers[:2] | |
| ##print tuple_of_numbers[1:] | |
| ##print tuple_of_numbers[:-1] | |
| ##print tuple_of_numbers[:] | |
| #### assignment | |
| ##x, y = (1, 2, 3), (10, 20, 30) # x and y are tuples variables | |
| ##print x, y | |
| ##### iterate over! | |
| ##for number in tuple_of_numbers: | |
| ## print number | |
| ### Oddity | |
| ##print 'Before: ', tuple_of_numbers | |
| ###insert 100 and 20 into tuple | |
| ##tuple_of_numbers = tuple_of_numbers + (100,20) | |
| ##print 'After: ', tuple_of_numbers | |
| ### Wart | |
| ##oppsie = (50) | |
| ##print 'oppsie: ', oppsie | |
| ##onesie = (50,) | |
| ##print 'onesie: ', onesie | |
| # Strings | |
| ##name = 'Mario' | |
| # functions | |
| ##print name.upper() | |
| ##print name.lower() | |
| ##print name.find('i') | |
| ##print name.find('io') | |
| ##print name.find('io') | |
| ##print name.replace('Mario', 'Luan') | |
| ##name = name.replace('Luan', 'Mario') | |
| ##print name | |
| ##name = name.lower().replace('m', 'x') | |
| ##print name | |
| # dir(str) | |
| # help(str.replace) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # lecture 5 | |
| # -> tuples | |
| # note: immutable | |
| ##intTuple = (1, 2, 3, 4) | |
| ##strTuple = ('red', 'yellow', 'green') | |
| ##print len(intTuple) | |
| ### storing divisors of 100 in a tuple | |
| ##x = 100 | |
| ##divisors = () | |
| ##for i in range(1,x): | |
| ## if x % i == 0: | |
| ## divisors = divisors+(i,) | |
| ##print divisors | |
| ### -> lists | |
| # defining lists | |
| ##techs = ['mit', 'cal tech'] | |
| ##ivys = ['harvard', 'yale', 'brown'] | |
| ##univs = [] # create an empty list | |
| # append | |
| ##univs.append(techs) # mutates the list, side effect | |
| ##print 'univs = ', univs | |
| ##univs.append(ivys) | |
| ##print 'univs =', univs | |
| ##for e in univs: # print each element inside the list | |
| ## print 'e =', e | |
| ### concatenate | |
| ##flat = techs + ivys | |
| ##print 'flat =', flat | |
| ## | |
| ### removing | |
| ##artSchools = ['risd', 'harvard'] | |
| ##for u2 in artSchools: | |
| ## if u2 in flat: | |
| ## flat.remove(u2) | |
| ##print 'flat =', flat | |
| ## | |
| ### sorting | |
| ##flat.sort() | |
| ##print 'flat =', flat | |
| ## | |
| ### updating | |
| ##flat[1] = 'umass' | |
| ##print 'flat =', flat | |
| ### difference of mutating from assigment | |
| ### -> mutating | |
| ##L1 = [2] | |
| ##L2 = [L1, L1] | |
| ##print 'L2 = ', L2 | |
| ##L1[0] = 3 | |
| ##print 'L2 = ', L2 | |
| ##L2[0] = 'a' | |
| ##print 'L2 = ', L2 | |
| ### -> assignment | |
| ##L1 = [2] | |
| ##L2 = L1 | |
| ##print id(L1), id(L2) # they refer to the same object | |
| ##L2[0] = 'a' | |
| ##print 'L1 = ', L1 | |
| ##print 'L2 = ', L2 | |
| ##def copyList(source, dest): | |
| ## for e in source: | |
| ## dest.append(e) | |
| ## print 'dest =', dest | |
| ## | |
| ##L1 = [] | |
| ##L2 = [1, 2, 3] | |
| ##copyList(L2, L1) | |
| ##print L1 | |
| ##print L2 | |
| # avoid using the same alias to modify objects | |
| # -> dictionary | |
| #- elements are not orderer | |
| #- indeces is now keys, and can be any immutable type | |
| ### example 1 | |
| ##d = {1: 'none', 'deux': 'two', 'pi': 3.14159} | |
| ##d1 = d | |
| ##print d1 | |
| ##d[1] = 'uno' | |
| ##print d1 | |
| ##for k in d1.keys(): | |
| ## print k, '=', d1[k] | |
| ### example 2 | |
| ##EtoP = {'bread': 'pao', 'love': 'amor',\ | |
| ## 'drinks': 'bebidas', 'wake up': 'acordar',\ | |
| ## 'tattoo': 'tatuagem', 'pot': 'baseado',\ | |
| ## 'table': 'mesa'} | |
| ##print EtoP # dict object in an unodered order (by default) | |
| ##print EtoP.keys() # call the method and print keys from dict object | |
| ##print EtoP.keys # it says what type of call is keys, bu doesnt execute the method at all | |
| ### deleting | |
| ##del EtoP['bread'] | |
| ##print EtoP | |
| ### example 3 | |
| ## | |
| ##d = {1: 'one', 'deux': 'two', 'pi' : 3.14159} | |
| ##d1 = d | |
| ##print d1 | |
| ##d[1] = 'uno' | |
| ##print d1 | |
| ##for k in d1.keys(): | |
| ## print k, '=', d1[k] | |
| ### example 4 - creating a dictionary | |
| ## | |
| ### creating the dictionary | |
| ##EtoP = {'red': 'vermelho', 'blue': 'azul', 'yellow': 'amarelo'} | |
| ## | |
| ### checks if the word is in the dictionary | |
| ##def translateWord(word, dictionary): | |
| ## if word in dictionary: | |
| ## return dictionary[word] # e.g: EtoP['red'] = vermelho | |
| ## else: | |
| ## return word | |
| ## | |
| ### iterates trough each word and try to translate it | |
| ##def translate(setence): | |
| ## translation = '' | |
| ## word = '' | |
| ## for e in setence: | |
| ## if e != ' ': | |
| ## word = word + e | |
| ## else: | |
| ## translation = translation + ' ' + translateWord(word, EtoP) | |
| ## word = '' | |
| ## return translation[1:] + ' ' + translateWord(word, EtoP) | |
| ## | |
| ##print translate('My t-shirt is blue') | |
| ##print translate('I love red shoes') | |
| ##print translate('My computer is yellow') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### linked lists | |
| ## | |
| ### -> the node class | |
| ##class Node: | |
| ## def __init__(self, cargo=None, next=None): | |
| ## self.cargo = cargo | |
| ## self.next = next | |
| ## | |
| ## def __str__(self): | |
| ## return str(self.cargo) | |
| ## | |
| ### creating nodes | |
| ##node1 = Node(1) | |
| ##node2 = Node(2) | |
| ##node3 = Node(3) | |
| ### stat diagram | |
| ## node1 node2 node3 | |
| ## cargo -> 1 cargo -> 2 cargo -> 3 | |
| ## next -> none next -> none next -> none | |
| ### link nodes into lists | |
| ##node1.next = node2 | |
| ##node2.next = node3 | |
| ### stat diagram | |
| ## node1 node2 node3 | |
| ## cargo -> 1 cargo -> 2 cargo -> 3 | |
| ## next ---------> next ----------> next -> none | |
| ##### -> lists as collections | |
| ##def printList(node): | |
| ## """ prints list collection in list format """ | |
| ## print "[", | |
| ## print node, | |
| ## print ",", | |
| ## while node: | |
| ## if node.next != None: | |
| ## print node.next, | |
| ## node = node.next | |
| ## if node.next == None: | |
| ## print "]" | |
| ## break | |
| ## else: | |
| ## print ",", | |
| ## | |
| ##printList(node1) | |
| ### -> lists and recursion | |
| ## | |
| ##def printBackward(list): | |
| ## if list == None: | |
| ## return | |
| ## printBackward(list.next) # treats its arguments as a list collection | |
| ## print list, # treats its arguments as a single object | |
| ## | |
| ##printBackward(node1) | |
| ## | |
| ### -> fundamental ambiguity theorem | |
| ##""" a variable that refers to a node might | |
| ##treat the node as a single object or as the | |
| ##first in a list of nodes""" | |
| ### -> modifying lists | |
| ##def removeSecond(list): | |
| ## if list == None: | |
| ## return | |
| ## first_node = list | |
| ## second_node = list.next | |
| ## # make the first node refer to the third | |
| ## first_node.next = second_node.next | |
| ## # separate the seconds node from the rest of the list | |
| ## second_node.next = None | |
| ## return second_node | |
| ##printList(node1) | |
| ## | |
| ##### stat diagram | |
| #### node1 node2 node3 | |
| #### cargo -> 1 cargo -> 2 cargo -> 3 | |
| #### next ---------> next ----------> next -> none | |
| ##removed = removeSecond(node1) | |
| ##printList(removed) | |
| ##print printList(node1) | |
| ##### stat diagram | |
| #### node1 node2 node3 | |
| #### cargo -> 1 cargo -> 2 cargo -> 3 | |
| #### next ---------------------------> next -> None | |
| ##def printBackwardNicely(list): # wrapper | |
| ## print "[", | |
| ## printBackward(list) # helper | |
| ## print "]", | |
| ## | |
| ##printBackwardNicely(node1) | |
| ##class LinkedList: | |
| ## def __init__(self): | |
| ## self.length = 0 | |
| ## self.head = None | |
| ## | |
| ## def printBackward(self): # the wrapper | |
| ## print "[", | |
| ## if self.head != None: | |
| ## self.head.printBackward() | |
| ## print "]", | |
| ## | |
| ## def addFirst(self, cargo): | |
| ## node = Node(cargo) | |
| ## node.next = self.head | |
| ## self.head = node | |
| ## self.length = self.length + 1 | |
| ## | |
| ## | |
| ##class Node: | |
| ## def __init__(self, cargo=None, next=None): | |
| ## self.cargo = cargo | |
| ## self.next = next | |
| ## | |
| ## def __str__(self): | |
| ## return str(self.cargo) | |
| ## | |
| ## def printBackward(self): # the helper | |
| ## if self.next != None: | |
| ## tail = self.next | |
| ## tail.printBackward() | |
| ## print self, | |
| ## | |
| ### creation of a liked list | |
| ##node = LinkedList() | |
| ##node.addFirst(1) | |
| ##node.addFirst(2) | |
| ##node.addFirst(3) | |
| ##node.printBackward() | |
| ## | |
| ### it is the same as performing | |
| ##node1 = Node(1) | |
| ##node2 = Node(2) | |
| ##node3 = Node(3) | |
| ##node1.next = node2 | |
| ##node2.next = node3 | |
| ##printList(node1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### prints a list of cubes of the numbers of 1 through 10 | |
| ##def cube_list(): | |
| ## return [i**3 for i in range(1,10)] | |
| ## | |
| ##print cube_list() | |
| ### takes in a string and return all the vowels in the string | |
| ##def remove_vowels(text): | |
| ## import string | |
| ## vowels = "aeiou" | |
| ## text = text.lower() | |
| ## text = [text[i] for i in range(0,len(text)) if text[i] in vowels] | |
| ## return string.join(text, "") | |
| ## | |
| ##print remove_vowels("mario") | |
| #### comparing nested list to list comprehension | |
| ### list comprehension | |
| ##print [x+y for x in [10, 20, 30] for y in [1, 2, 3]] | |
| ### nested list | |
| ##def nested_list(): | |
| ## x = [10, 20, 30] | |
| ## y = [1, 2, 3] | |
| ## new_list = [] | |
| ## | |
| ## for i in range(0,len(x)): | |
| ## for e in range(0,len(y)): | |
| ## new_list.append(x[i]+y[e]) | |
| ## return new_list | |
| ##print nested_list() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### list = ordered set of values/sequences | |
| ### elements = values in the list | |
| ### -> lists values | |
| ##[10, 20, 30, 40] # int | |
| ##["spam", "bungee", "swallow"] # str | |
| ##["hello", 2.0, 5 [10, 20]] # str, float, int and a nested list | |
| ## | |
| ### these functions creates lists of consecutive integers | |
| ##range(1, 5) # [1, 2, 3, 4] | |
| ##range(5) # = [0, 1, 2, 3, 4] | |
| ##range(1, 10, 2) # = [1, 3, 5, 7, 9] | |
| ### -> special list, the empty list | |
| ##empty = [] | |
| ### -> assign list values to variables | |
| ##empty = [] | |
| ##vocabulary = ["ameliorate", "castigate", "defenestrate"] | |
| ##numbers = [17, 123] | |
| ##print vocabulary, numbers, empty | |
| ##print vocabulary[1], numbers[0], empty | |
| ### -> accessing elements | |
| ##number = [0, 1, 2, 3, 4] | |
| ##print number[0] | |
| ##number[0] = 1 | |
| ##print number[0] | |
| ##print number[3-2] # (3 - 2) = 1 | |
| # -> list traversal | |
| ##months = ['jan', 'feb', 'mar', 'apr'] | |
| ##i = 0 | |
| ##while i < 4: | |
| ## print months[i] | |
| ## i += 1 | |
| # -> list length | |
| ##colors = ['red', 'yellow', 'blue', 'black'] | |
| ##i = 0 | |
| ##while i < len(colors): | |
| ## print colors[i] | |
| ## i += 1 | |
| ##wow = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] | |
| ##i = 0 | |
| ##while i < len(wow): | |
| ## print wow[i] # prints the value | |
| ## print len(wow[i]) # prints the length of the value | |
| ## i += 1 | |
| ### -> list membership | |
| ### in = boolean operator | |
| ##dogs = ['neguinha', 'marcela', 'raquel'] | |
| ##print 'marcela' in dogs # returns True | |
| ##print 'mel' not in dogs # returns True | |
| ### -> lists and loops | |
| ### using a while loop | |
| ##i = 0 | |
| ##while i < len(dogs): | |
| ## print dogs[i] | |
| ## i += 1 | |
| # using a for loop | |
| ##for dogs in dogs: | |
| ## print dogs | |
| #another examples | |
| ##for i in range(0, 20, 2): | |
| ## print i | |
| ##for i in range(20): | |
| ## if i % 2 == 0: | |
| ## print i | |
| ##for i in ['winter', 'summer', 'spring']: | |
| ## print 'I love', i | |
| ### -> list operations | |
| ### concatenating | |
| ##myDogs = ['neguinha', 'marcela'] | |
| ##wifeDogs = ['raquel'] | |
| ##allDogs = myDogs + wifeDogs | |
| ##print allDogs | |
| ### calculating | |
| ##number = [100, 2] | |
| ##percent = [1.5] | |
| ##total = bills[0]*percent[0]/number[1] | |
| ##print total | |
| ### duplicating | |
| ##numbers = [1, 2, 3] | |
| ##doubleNumbers = numbers*2 | |
| ##print doubleNumbers | |
| ##names = ['python', 'java'] | |
| ##doubleNames = names*2 | |
| ##print doubleNames | |
| ### -> list slices | |
| ##letters = ['a', 'b', 'c', 'd', 'e'] | |
| ##print letters[1:3] # b, c | |
| ##print letters[:3] # a, b, c | |
| ##print letters[3:] # d, e | |
| ### -> lists are mutable | |
| ### update one element at a time | |
| ##colors = ['orange', 'green', 'red', 'yellow'] | |
| ##colors[0] = 'black' | |
| ##colors[-2] = 'white' | |
| ##print colors | |
| ### update multiple elements at once | |
| ##colors[1:3] = ['black', 'white'] | |
| ##print colors | |
| ### remove elements (not a best practice, see list deletion) | |
| ##colors[1:3] = [] | |
| ##print colors | |
| ### add elements | |
| ##letters = ['a', 'b'] | |
| ##letters[2:2] = ['c', 'd'] | |
| ##print letters | |
| ##letters[4:4] = ['e'] | |
| ##print letters | |
| ### -> list deletion | |
| ##sequence = ['one', 'two', 'three'] | |
| ##del sequence[0] | |
| ##print sequence | |
| ### -> objects and values | |
| ##id(x) # prints the object identifier | |
| ##a = 'red' | |
| ##b = 'red' | |
| ##print id(a) | |
| ##print id(b) | |
| ### we get the same identifier with strings | |
| ##a = [1, 2, 3] | |
| ##b = [1, 2, 3] | |
| ##print id(a), id(b) | |
| ### we get different identifier with lists | |
| ### -> aliasing | |
| ### good for mutable objects | |
| ##a = [1, 2, 3] | |
| ##b = a | |
| ##print id(a), id(b) | |
| ### now we get the same identifier | |
| ##b[0] = 2 | |
| ##print a | |
| # note: if we make changes to b, a is automatic affected. (see cloning lists) | |
| ### -> cloning lists | |
| ### fisrt, we clone a | |
| ##a = [1, 2, 3] | |
| ##b = a[:] | |
| ### than we can make changes to b without worrying about a: | |
| ##b[0] = 2 | |
| ##print a, b | |
| ### -> list parameters | |
| ##numbers = [1, 2, 3] | |
| ## | |
| ##def head(list): | |
| ## print list[0] | |
| ## | |
| ##def delHead(list): | |
| ## del list[0] | |
| ## | |
| ##def tail(list): | |
| ## return list[1:] | |
| ### -> nested list | |
| ##list = ['mario', 1, 2, [10, 20, 30], 'luan'] | |
| ##print list[3] # prints [10, 20, 30] | |
| ##print list[3][:2] # prints [10, 20] | |
| ##newList = list[3][:3] # assign [10, 20, 30] to a new variable | |
| ##print newList[0], newList[1], newList[2] | |
| ### -> matrices | |
| ##matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | |
| ##print matrix[0] # first row | |
| ##print matrix[0][0] # first row, first column | |
| ##print matrix[0][1] # first row, second column | |
| ##print matrix[0][2] # first row, thrid column | |
| ### -> string and lists | |
| ##import string | |
| ### split | |
| ## | |
| ##song = 'When I was_looking for_syou' | |
| ##songList = string.split(song) # by default, it takes whitespaces as delimiters | |
| ####print songList[:] | |
| ## | |
| ##songList = string.split(song, '_') # using delimiter argument | |
| ##print songList[:] | |
| ### join | |
| ##song = 'When I was looking for you' | |
| ##songListSplit = string.split(song) | |
| ##print songListSplit | |
| ##songListJoin = string.join(songListSplit) | |
| ##print songListJoin |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -> Queue ADT and Priority Queue ADT | |
| # both have the same set of operations/methods, but: | |
| # Queue uses the FIFO policy = first-in-first-out | |
| # Priority Queue uses the priority queueing policy | |
| # Queue = made up of linked Node objects | |
| # policy = FIFO - first-in-first-out | |
| # the Queue ADT interface: | |
| ##__init__ = initialize a new empty queue | |
| ##insert = add a new item to the queue | |
| ##remove = remove and returns the first item added to the list | |
| ##isEmpty = checks if queue is empty | |
| ##### -> Linked Queue | |
| ##class Node: | |
| ## def __init__(self, cargo=None, next=None): | |
| ## self.cargo = cargo | |
| ## self.next = next | |
| ## | |
| ## def __str__(self): | |
| ## return str(self.cargo) | |
| ##class Queue: | |
| ## | |
| ## def __init__(self): | |
| ## self.length = 0 | |
| ## self.head = None | |
| ## | |
| ## def isEmpty(self): | |
| ## return (self.length == 0) | |
| ## | |
| ## # linear time | |
| ## # the runtime is a linear function of the length | |
| ## def insert(self, cargo): | |
| ## node = Node(cargo) | |
| ## node.next = None | |
| ## if self.head == None: | |
| ## # if list is empty the new node goes first | |
| ## self.head = node | |
| ## else: | |
| ## # find the last node in the list | |
| ## last = self.head | |
| ## while last.next: | |
| ## last = last.next | |
| ## last.next = node | |
| ## self.length += 1 | |
| ## | |
| ## # constant time operation/method | |
| ## # the runtime of this method is the same every time | |
| ## # because it has no loops of function calls | |
| ## def remove(self): | |
| ## cargo = self.head.cargo | |
| ## self.head = self.head.next | |
| ## self.length -= 1 | |
| ## return cargo | |
| # -> Improved Linked Queue | |
| # let's modify the implementation of the Queue ADT, | |
| # so we can perform all operations in constant time | |
| ##class ImprovedQueue: | |
| ## | |
| ## def __init__(self): | |
| ## self.length = 0 | |
| ## self.head = None | |
| ## self.last = None # added | |
| ## | |
| ## def isempty(self): | |
| ## return (self.length == 0) | |
| ## | |
| ## def insert(self, cargo): | |
| ## node = Node(cargo) | |
| ## node.next = None | |
| ## if self.length == 0: | |
| ## # if list is empty, the new node is head and last | |
| ## self.head = node | |
| ## self.last = node | |
| ## else: | |
| ## # find the last node | |
| ## last = self.last | |
| ## # append the new node | |
| ## last.next = node | |
| ## self.last = node | |
| ## self.length += 1 | |
| ## | |
| ## def remove(self): | |
| ## cargo = self.head.cargo | |
| ## self.head = self.head.next | |
| ## self.length -= 1 | |
| ## if self.length == 0: | |
| ## self.last = None | |
| ## return cargo | |
| ### -> Queue with Python Lists | |
| ##class QueueList: | |
| ## | |
| ## def __init__(self): | |
| ## self.items = [] | |
| ## print "new empty list created" | |
| ## | |
| ## def __str__(self): | |
| ## if self.isEmpty(): | |
| ## return "Queue list is empty!" | |
| ## else: | |
| ## return "current list= " + str(self.items) | |
| ## | |
| ## def isEmpty(self): | |
| ## return (self.items == []) | |
| ## | |
| ## def insert(self, item): | |
| ## self.items.append(item) | |
| ## print "new item added!" | |
| ## | |
| ## def remove(self): | |
| ## if self.isEmpty(): | |
| ## return False | |
| ## else: | |
| ## removed = self.items[0] | |
| ## del self.items[0] | |
| ## print "item %s removed from list" % str(removed) | |
| ## return True | |
| ### -> testing the implementation | |
| ##newList = QueueList() | |
| ##newList.insert(1) | |
| ##newList.insert(2) | |
| ##newList.insert(3) | |
| ##print newList | |
| ##newList.remove() | |
| ##newList.remove() | |
| ##newList.remove() | |
| ##print newList | |
| ### -> Priority queue | |
| ### ADT interface: | |
| ##__init__ = initialize a new empty queue | |
| ##insert = add a new item to the queue | |
| ##remove = remove and returns the item with highest priority from list | |
| ##isEmpty = checks if queue is empty | |
| ##class PriorityQueue: | |
| ## def __init__(self): | |
| ## self.items = [] | |
| ## | |
| ## def isEmpty(self): | |
| ## return self.items == [] | |
| ## | |
| ## def insert(self, item): | |
| ## self.items.append(item) | |
| ## | |
| ## def remove(self): | |
| ## maxi = 0 | |
| ## for i in range(1,len(self.items)): | |
| ## if self.items[i] > self.items[maxi]: | |
| ## maxi = i | |
| ## removed = self.items[maxi] | |
| ## del self.items[maxi] | |
| ## return removed | |
| ### testing the implementation | |
| ##q = PriorityQueue() | |
| ##q.insert(11) | |
| ##q.insert(12) | |
| ##q.insert(13) | |
| ##q.insert(14) | |
| ##print q.remove() | |
| ##print q.remove() | |
| ##print q.remove() | |
| ##print q.remove() | |
| ### -> the Golfer class | |
| ##class Golfer: | |
| ## | |
| ## def __init__(self, name, score): | |
| ## self.name = name | |
| ## self.score = score | |
| ## | |
| ## def __str__(self): | |
| ## return "%-16s: %d" % (self.name, self.score) | |
| ## | |
| ## def __cmp__(self, other): | |
| ## if self.score < other.score: # less is more | |
| ## return 1 | |
| ## if self.score > other.score: | |
| ## return -1 | |
| ## return 0 | |
| ### testing the implementation | |
| ### initiating players and its scores | |
| ##mario = Golfer("mario", 22) | |
| ##luan = Golfer("luan", 5) | |
| ##souza = Golfer("souza", 11) | |
| ### initiating PriorityQueue | |
| ##pq = PriorityQueue() | |
| ##pq.insert(mario) | |
| ##pq.insert(luan) | |
| ##pq.insert(souza) | |
| ##print pq.remove() | |
| ##print pq.remove() | |
| ##print pq.remove() | |
| # constant time | |
| """ an operation whose runtime doesn't depend | |
| on the size of the data """ | |
| # linear time | |
| """ an operation whose runtime is a linear | |
| functions of the size of the data structure """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> sets of objects | |
| ## | |
| ### -> card objects | |
| ##class Card: | |
| ## # class attributes | |
| ## suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] | |
| ## rankList = ["nothing_here", "Ace", "2", "3", "4", "5", "6", | |
| ## "7", "8", "9", "10", "Jack", "Queen", "King"] | |
| ## | |
| ## def __init__(self, suit=0, rank=2): | |
| ## self.suit = suit | |
| ## self.rank = rank | |
| ## | |
| ## def __str__(self): | |
| ## return (self.rankList[self.rank] + " of " + self.suitList[self.suit]) | |
| ## | |
| ## def __cmp__(self, other): | |
| ## """ compares cards """ | |
| ## # check the suits | |
| ## if self.suit > other.suit: | |
| ## return 1 | |
| ## if self.suit < other.suit: | |
| ## return -1 | |
| ## | |
| ## # suits are the same... check ranks | |
| ## | |
| ## # in case we're dealing with Ace rank | |
| ## if self.rank == 1 and other.rank != 1: | |
| ## return 1 | |
| ## elif self.rank != 1 and other.rank == 1: | |
| ## return -1 | |
| ## | |
| ## if (self.rank != 1 and other.rank != 1) and self.rank > other.rank: | |
| ## return 1 | |
| ## elif (self.rank != 1 and other.rank != 1) and self.rank < other.rank: | |
| ## return -1 | |
| ## # ranks are the same.. it's a tie | |
| ## return 0 | |
| ## | |
| ##card1 = Card(1, 1) | |
| ##card2 = Card(1, 1) | |
| ##print card2 | |
| ##print card2.suitList[1] | |
| ### avoid modifing class attributes | |
| ### if we modify a class attribute, every instance will be affected | |
| ##card1.suitList[1] = "Swirly Whales" | |
| ##print card1 | |
| ##print card2 | |
| ### -> comparing cards | |
| ### card1 > card2 | |
| ##print card1, '<', card2 | |
| ##print card1 < card2 | |
| ### -> creating the deck with 52 cards | |
| ##class Deck: | |
| ## def __init__(self): | |
| ## self.cards = [] | |
| ## for suit in range(4): | |
| ## for rank in range(1, 14): | |
| ## self.cards.append(Card(suit, rank)) | |
| ## | |
| ## # printing | |
| ## # nice print | |
| ## def __str__(self): | |
| ## s = "" | |
| ## for i in range(len(self.cards)): | |
| ## s = s + " "*i + str(self.cards[i]) + "\n" | |
| ## return s | |
| ## | |
| ## # basic print | |
| ## def printDeck(self): | |
| ## for card in self.cards: | |
| ## print card | |
| ## | |
| ## # shuffling | |
| ## def shuffle(self): | |
| ## import random | |
| ## nCards = len(self.cards) | |
| ## for i in range(nCards): | |
| ## j = random.randrange(i, nCards) | |
| ## self.cards[i], self.cards[j] = self.cards[j], self.cards[i] | |
| ## | |
| ## # removing | |
| ## def removeCard(self, card): | |
| ## # note: Python uses the object's _-cmp__ method to | |
| ## # determine equality with items in the list | |
| ## if card in self.cards: | |
| ## self.cards.remove(card) | |
| ## return True | |
| ## else: | |
| ## return False | |
| ## | |
| ## def popCard(self): | |
| ## """ removes the last card in the list """ | |
| ## return self.cards.pop() | |
| ## | |
| ## def isEmpty(self): | |
| ## """ returns true if deck contains no cards """ | |
| ## return (len(self.cards) == 0) | |
| ## | |
| ## def nCards(self): | |
| ## """ returns the number of cards in deck """ | |
| ## return len(self.cards) | |
| ### creating a new instance of deck object | |
| ##deck = Deck() | |
| ## | |
| ### -> printing the deck | |
| ##print deck | |
| ##deck.printDeck() | |
| ### -> shuffling the deck | |
| ##deck.shuffle() | |
| ##card1 = Card(3,4) | |
| ### -> removing cards | |
| ##print len(deck.cards) # before removal | |
| ##print deck.removeCard(card1) | |
| ##print deck.popCard() | |
| ##print len(deck.cards) # after removal | |
| ##print deck.isEmpty() | |
| ##print deck.nCards() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### -> compound data type | |
| ##fruit = "banana" | |
| ##letter = fruit[1] | |
| ##print letter | |
| ### -> length | |
| ##length = len(fruit) | |
| ##print length # 0,1,2,3,4,5 = 6 | |
| ##print fruit[length-1] # 6-1 = 5 = last letter | |
| ##print fruit[-1] # prints the last letter | |
| #### -> traversal and the for loop | |
| ### -> traversal | |
| ##name = "mario" | |
| ##index = 0 | |
| ##while index < len(name): | |
| ## letter = name[index] | |
| ## print letter | |
| ## index = index + 1 | |
| ##def backward(string): | |
| ## index = len(string)-1 | |
| ## while index >= 0: | |
| ## slot = string[index] | |
| ## print slot | |
| ## index = index - 1 | |
| ##string = raw_input("type a word to backward the letters\n") | |
| ##backward(string) | |
| ### -> for loop | |
| ##for char in fruit: | |
| ## print char | |
| ### -> for (Abecedarian) | |
| ##prefixes = "JKLMNOPQ" | |
| ##suffix = "ack" | |
| ## | |
| ##for letter in prefixes: | |
| ## if letter == "O": | |
| ## print letter + "u" + suffix | |
| ## else: | |
| ## print letter + suffix | |
| ### -> string slices [n:m] = including n but not m | |
| ##full_name = "Mario Luan Santos de Souza" | |
| ##print full_name[0:5] # from 0 to 4 | |
| ##print full_name[:5] # from 0 to 4 | |
| ##print full_name[6:10] # from 6 to 9 | |
| ##print full_name[6:] # from 6 to the end | |
| ##print full_name[:] # from n to m | |
| ### -> string comparison | |
| ##word = 'anana' | |
| ##if word == 'banana': | |
| ## print 'Your word is banana' | |
| ### putting words in alphabetical order | |
| ### ps: uppercase letters comes before all uppercase letters | |
| ##if word > 'banana': | |
| ## print 'Your word,', word, 'comes after banana' | |
| ##elif word < 'banana': | |
| ## print 'Your word,', word, 'comes before banana' | |
| ##else: | |
| ## print 'Yes, we have no banana' | |
| ### -> strings are ummutable | |
| ### we can't change an existing string, | |
| ##name = "Mario Luan" | |
| ##name[0] = "W" | |
| # instead we should create another string | |
| ##name = "Mario Luan" | |
| ##new_name = "W" + name[1:] | |
| ##print new_name | |
| ### -> the FIND function | |
| ##def find(str, ch, index): | |
| ## while index < len(str): | |
| ## if str[index] == ch: | |
| ## return index | |
| ## index = index + 1 | |
| ## return -1 | |
| ### -> looping and couting | |
| ## | |
| ### traversal mode | |
| ##def countLetters(str, ch): | |
| ## i = 0 | |
| ## for char in str: | |
| ## if char == ch: | |
| ## i = i + 1 | |
| ## print 'Letter', ch,'appeared', i,'times' | |
| ### using find function | |
| ##def find(str, ch, index): | |
| ## i = 0 | |
| ## while index < len(str): | |
| ## if str[index] == ch: | |
| ## i = i + 1 | |
| ## index = index + 1 | |
| ## if i == 0: | |
| ## return -1 | |
| ## else: | |
| ## return i | |
| ### -> the string module | |
| ##import string | |
| ##name = 'baneni' | |
| ##index = string.find(name, 'a') | |
| ##print index | |
| ## | |
| ##print string.find(name, 'ne') # find 'ne' | |
| ##print string.find(name, 'ne', 3) # find 'ne' from index 3 to last index | |
| ##print string.find(name, 'ne', 2, 4) # find 'ne' from index 2 to index 4 | |
| ### -> character classification | |
| ##import string | |
| ##print string.lowercase # contains all lowercase letters | |
| ##print string.uppercase # contains all uppercase letters | |
| ##print string.digits # contains all numeric numbers | |
| ### example 1 | |
| ##def isLower(ch): | |
| ## return string.find(string.lowercase, ch) != -1 | |
| # this one is the worst one to use, cause I have to worry about letter indexes | |
| ### example 2 | |
| ##def isLower(ch): | |
| ## return ch in string.lowercase | |
| # this one is better to understand | |
| ### example 3 | |
| ##def isLower(ch): | |
| ## return 'a' <= ch <= 'z' | |
| ### this one is useful when I want to limit the range of the search | |
| ## exercise 1 | |
| ##for y in range(2,11): | |
| ## print "1 /", y | |
| ## | |
| ## exercise 2 | |
| ##validation = False | |
| ##while validation == False: | |
| ## number = int(raw_input("Enter a positive number\n")) | |
| ## if number > 0: | |
| ## while number > 0: | |
| ## print number | |
| ## number -= 1 | |
| ## validation = True | |
| ## elif number == 0: | |
| ## print "type a number greater than 0" | |
| ## else: | |
| ## print "you must enter a positive number!" | |
| ## | |
| ### exercise 4 | |
| ##isEven = False | |
| ##while isEven == False: | |
| ## x = int(raw_input("Enter a number divisible by 2\n")) | |
| ## if x % 2 == 0: | |
| ## print "You got it!" | |
| ## isEven = True | |
| ## else: | |
| ## print "Ohh, you didn't get it. Try again!" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### trees = made up of nodes, recursive data structure | |
| ### stat diagram | |
| ##tree -> cargo -> 1 # root | |
| ## left -> cargo -> 2 # branch | |
| ## left -> None # leave | |
| ## right -> None # leave | |
| ## right -> cargo -> 3 # branc | |
| ## left -> None # leave | |
| ## right -> None # leave | |
| ### tree metaphor | |
| ####cargo 1 = top of the tree = root | |
| ####cargo 2 and cargo 3 = branches | |
| ####left None and right None = leaves | |
| ### family tree | |
| ####cargo 1 = parent | |
| ####cargo 2, cargo 3, left and right = children | |
| ####note: nodes with the same parent = siblings | |
| ##### -> building trees | |
| ##class Tree: | |
| ## def __init__(self, cargo, left=None, right=None): | |
| ## self.cargo = cargo # any type | |
| ## self.left = left # tree nodes | |
| ## self.right = right # tree nodes | |
| ## | |
| ## def __str__(self): | |
| ## return str(self.cargo) | |
| ### first, we allocate the child nodes: | |
| ##left = Tree(2) | |
| ##right = Tree(3) | |
| ### than, create the parent node | |
| ##tree = Tree(1, left, right) | |
| ##print tree.left, tree.right, tree.cargo | |
| ### -> traversing trees | |
| ##def total(tree): | |
| ## if tree == None: | |
| ## return 0 | |
| ## return total(tree.left) + total(tree.right) + total(tree.cargo) | |
| ## | |
| ##print total(tree) | |
| # -> expression trees | |
| ##tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3))) | |
| # previous tree is equivalent to "1 + (2*3)" | |
| ### -> tree traversal | |
| ##def printTree(tree): | |
| ## if tree == None: | |
| ## return | |
| ## print tree.cargo, # prints tree root | |
| ## printTree(tree.left) | |
| ## printTree(tree.right) | |
| ## | |
| ##printTree(tree) | |
| ##def printTreeIndented(tree, level=0): | |
| ## if tree == None: | |
| ## return | |
| ## printTreeIndented(tree.right, level+1) | |
| ## print ' '*level + str(tree.cargo) | |
| ## printTreeIndented(tree.left, level+1) | |
| ## | |
| ##printTreeIndented(tree) | |
| ##def printTreePostorder(tree): | |
| ## if tree == None: | |
| ## return | |
| ## printTreePostorder(tree.left) | |
| ## printTreePostorder(tree.right) | |
| ## print tree.cargo, | |
| ## | |
| ### -> building an expression tree | |
| ##def parseInfix(string): | |
| ## tokenList = [] | |
| ## for item in string: | |
| ## tokenList.append(item) | |
| ## | |
| ## length = len(tokenList) | |
| ## tokenList.append("end") | |
| ## return tokenList | |
| ##string = "(3+7)*9" | |
| ##print parseInfix(string) | |
| ##def getToken(tokenList, expected): | |
| ## if tokenList[0] == expected: | |
| ## del tokenList[0] | |
| ## return True | |
| ## else: | |
| ## return False | |
| ## | |
| ##def getNumber(tokenList): | |
| ## if getToken(tokenList, '('): | |
| ## x = getSum(tokenList) | |
| ## if not getToken(tokenList, ')'): | |
| ## raise ValueError, 'missing parenthesis' | |
| ## return x | |
| ## else: | |
| ## x = tokenList[0] | |
| ## if not isinstance(x, int): | |
| ## return None | |
| ## tokenList[0:1] = [] | |
| ## return Tree(x, None, None) | |
| ## | |
| ##def getProduct(tokenList): | |
| ## a = getNumber(tokenList) | |
| ## if getToken(tokenList, '*'): | |
| ## b = getProduct(tokenList) | |
| ## return Tree ('*', a, b) | |
| ## else: | |
| ## return a | |
| ## | |
| ##def getSum(tokenList): | |
| ## a = getProduct(tokenList) | |
| ## if getToken(tokenList, '+'): | |
| ## b = getSum(tokenList) | |
| ## return Tree('+', a, b) | |
| ## else: | |
| ## return a | |
| ### first example | |
| ##tokenList = [9, '*', 11, 'end'] | |
| ##tree = getProduct(tokenList) | |
| ##printTreePostorder(tree) | |
| ### second example | |
| ##tokenList = [9, '+', 11, 'end'] | |
| ##tree = getProduct(tokenList) | |
| ##printTreePostorder(tree) | |
| ### third example | |
| ##tokenList = [2, '*', 3, '*', 5, '*', 7, 'end'] | |
| ##tree = getProduct(tokenList) | |
| ##printTreePostorder(tree) | |
| ### fourth example | |
| ##tokenList = [9, '*', 11, '+', 5, '*', 7, 'end'] | |
| ##tree = getSum(tokenList) | |
| ##printTreePostorder(tree) | |
| ### fifth example | |
| ##tokenList = [9, '*', '(', 11, '+', 5, ')', '*', 7, 'end'] | |
| ##tree = getSum(tokenList) | |
| ##printTreePostorder(tree) | |
| ### -> animal tree | |
| ##def animal(): | |
| ## # start with a singleton | |
| ## root = Tree("bird") | |
| ## | |
| ## # loop until the user quits | |
| ## while True: | |
| ## if not yes("Are you thinking of an animal?"): | |
| ## break | |
| ## | |
| ## # walk the tree | |
| ## tree = root | |
| ## while tree.getLeft != None: | |
| ## prompt = tree.getCargo() + "? " | |
| ## if yes(prompt): | |
| ## tree = tree.getRight() | |
| ## else: | |
| ## tree = tree.getLeft() | |
| ## | |
| ## # make a guess | |
| ## guess = tree.getCargo() | |
| ## prompt = "Is it a " + guess + "? " | |
| ## if yes(prompt): | |
| ## print "I rule!" | |
| ## continue | |
| ## | |
| ## # get new information | |
| ## prompt = "What is the animal's name? " | |
| ## animal = raw_input(prompt) | |
| ## prompt = "What question would distinguish a %s from a %s? " | |
| ## question = raw_imput(prompt % (animal, guess)) | |
| ## | |
| ## # add new information to the tree | |
| ## tree.setCargo(question) | |
| ## prompt = "If the animal were %s the answer would be? " | |
| ## if yes(prompt % animal): | |
| ## tree.setLeft(Tree(guess)) | |
| ## tree.setRight(Tree(animal)) | |
| ## else: | |
| ## tree.setLeft(Tree(animal)) | |
| ## tree.setRight(Tree(guess)) | |
| ## | |
| ##def yes(ques): | |
| ## from string import lower | |
| ## ans = lower(raw_input(ques)) | |
| ## return (ans[0] == 'y') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment