Você está na página 1de 15

if t1:

s1

elif t2:

s2

elif t3:

s3

else

s4

# A quick multi-way branch

# Loops - While, No do-loop

# A stimulation of a do loop

while True:

if not t:

break

"""

not in python !

and && or ||

blanky('') - false

blanky(' ') - true

blanky('prince') - false

blanky('s sd sds') - true

"""

# Version 1

def blanky(s):

j=0
while(j<len(s)):

if s[j] == ' ':

return True

else:

j+=1

return false

blanky('s')

#Version 2 - Much easier to read

def blanky(s):

for x in s:

if x == ' ':

return True

return False

#Version 3 - Recursive function without any loop

s[i:j] # the subsequence of s from index i upto but not including j

def blanky(s):

if len(s) == 0:

return false

elif s[0]==' ':

return True

else:

return blanky(s[1:])
# DAY 3 PYTHON

"""

Python sequences, tuple, list, dictionary (Examples if time) One more blanky example...

# naive way

def blanky(s):

if ' ' in s:

return True

else:

return false

Tuple ordered sequence of 0 or more objects, not necessarily all of the same type. Objects = elements
of the tuple

e's are expressions (e0, e1, e2,..., en) returns a tuple whose elements are the e's

A tuple doesn't specify type for instance (3, "cheers", 4, "python", (1, 3))

Tuples are immutable

Tuples can have 0 elements, however if we want a tuple with one element needs a trailing comma (1,)

Q[0][2]

Concatenate works with strings for instance "ab" + "c" ="abc"

(1,2) + ("a", "b", "c") = (1, 2, "a", "b", "c") -- This does not change the original tuples

Purpose for a 0 length tuple

s = (,)

while J < 3

s= s + (J,)

J+= 1
s = (0, 1,2)

Lists are mutable and they use square parenthesis. No extra comman needed to show its a list

T=[1,'x',5] from T=[1,2,4] by T[1] = 'x'

del([2]) will delete an element

Dictionaries (mutable):

An unordered sequence of key-value pairs

{k0:v0, k1:v1, ... , kn:vn}

Keys are immutable whilst values may be either mutable or immutable.

No two keys in a single dictionary can be ==

9/15

More things about python !

Try and catcg statements in python which allow you to process exceptions!

An example on inheritance as well !

HOW TO HANDLE EXCEPTIONS IN PYTHON !

"""

def blanky(s):

return ' ' in s

# The in operator takes any sequence (string etc) if blank return true else false
try:

doSomething() #raise E, v

except: # Note that here you should be able to specify what exception to negate, without passing any
specification this will catch all statements

pass # Here nothing happens

else: # in this instance python could also use this syntax in line with a try statement

print "Something here does not match"

# Note that the else statement is optional.

# An example

class Person:

deg __init__(self, name, age):

self.name = name

self.age = age

p = Person("Harry Potter", 34)

def doSomethingWithPerson():

name = readName()

age = readAge()

person = Person(name, age) # Note that this might value error !


# create 100 persons

message = "Something bad has happened here"

j =1

while j <=100:

try:

doSomethingWithPerson() # raise need not be lexically be inside this statement

except ValueError, message:

print message

except ZeroDivisionError, message:

pass

j +=1

# finally in a try statement will always execute the try except clause! Think of this as a clean up

# ALSO NOTE THAT YOU CAN USE RAISE WITHOUT WRITING A TRY STATEMENT! - It just reminds you of
your last excpetion...

""" ****************************************

INHERITANCE

Abstract data types ! - Pretty much all before this

Classes form a hierarchy we can make new classes by adding things to old ones.

Python even supports multiple inheritance

SINGLE INHERITANCE ! - Just your usual inheritance

MULTIPLE INHERITANCE ! lastly - we talk about functional programming

Examples:

"""

# INHERITANCE SINGLE
class Person:

def __init__(self, name, age):

self.__name = name

self.__age = age

class Wizard(Person):

def __init__(self, name, age, wand):

# super()

Person.__init__(self, name, age)

self.__wand = wand

# get all of person's methods without writing them again

def getWand(self):

return self.__wand

class Muggle(Person):

def __init__(self, name, age, salary):

Person.__init__(self, name, age)

self.__salary = salary

def getSalary(self):

return self.__salary

W = Wizard("Dumbledore", 115, "Elder")

M = Muggle("Dursley", 65, 50000)

# MULTIPLE INHERITANCE

class Scary:

def __init__(self, feature, size):


self.__feature = feature

self.__size = size

class Alive(Scary):

def __init__(self, feature, size, howAlive):

Scary.__init__(self, feature, size)

self.__howAlive = howAlive

class Dead(Scary):

def __init__(self, feature, size, howDead):

Scary.__init__(self, feature, size)

self.__howDead = howDead

class Vampire(Alive, Dead):

# CODE HERE

# SEARCHING UP THE HIEARARCHY HAPPENS LEFT TO RIGHT

"""

Functional programming - WHY

Higher-order functions

examples

Map

Filter

Reduce

Moore's Law 1929-present

Number of transistors in dense chips doubles every 2 years

However, this is reducing nowadays because it will eventually get bound by the laws

of physics (special relativity)'

As transistors get smaller - dissipate more heat.

Quantam mechanics claim you will not be able to build very small transistors.
Possibly fail in 2025...

One box with many small chips inside of it and connect it in parallel. Massively

parallel computers

Memory (p1, p2) If we would like for them in parallel. To do this, maybe get rid

of variables?

F(g1(), g2(), g3()) - run g1, g2, g3 in parallel and then feed the result to F.

ABOVE WOULD BE THE REASON WHY FUNCTIONAL PROGRAMMING WOULD BE USEFUL

"""

"""

Higher-order functions - functiosn taht take other functions as arguments and return other functions

as values (BOTH).

"""

def isMember(p, s):

# Takes a predicate - a function that tests if its argument has some properties (T/F)

for s in s:

if p(e):

return True

return False

# From prior programming - improvements

def blanky(s):

return isMember(eq(' '), s)

def eq(k):

return (lambda j:j==k)


isMember(odd, N):

# F = eq(1)

# F(1) - True

# F(0) - True

# map, filter, reduce -- "Canned loops"

# F - function of 1-ary

# map(F, (f1, f2, f3, f4)) (Any sequence - list, string, tuple)

# say that this gives back a list !

"""

def map(F, S):

if len(s) == 0:

return []

else:

return [F(s[0])] + map(F, s[1:])

"""

""" map((lambda N:N+1), (1,2,3)):

#get a list [2,3,4]

[2] + map(inc, (2, 3))

[2] + [3] + map(inc, (3))

[3] + [3] + [4] + map(inc, ())

[2] + [3] + [4] + []

"""

filter(p, (e1,e2,e3,e4))
# list of elements (e1, e2, e3, e4) etc that make p True

# example

filter(odd, (1,2,3,4,5,6))

# we get back [1, 3, 5]

"""

THE LAST PYTHON LECTURE !

Functional programming -

Filter, Reduce

leftReduce and rightReduce

example:

"""

# make a copy of s containing the elements we want to keep.

def filter(p, s):

if len(s) == 0:

return []

elif p(s[0]):

return [s[0]] + filter(p, s[1:])

else:

return filter(p, s[1:])

# Reduce - the more complicated one! (Notice some other programming languages have this same
function but called ~ fold)

# F - function (2-ary)
def reduce(F, (e0, e1, e2), I):

# Will return F(F(F(I, e0), e1), e2) Returns a list of nested calls to F associate to the left (leftReduce)!

reduce(add, (1,2,3), 0) # add(add(add(0,1),2),3) - 6

# Indexing in python s=(e0, e1, e2, e3, e4, e5) from 0 to len(s) -1,

# opposite indexing would be -len(s) to -1 s[-1] is the last element of a nonempty S.

# s[:-1] everything but the last element !

def reduce(F, S, I):

if len(s) == 0:

return I

else:

# Note element 0 in F is actually the recursion call and the 1 element is the last element

return F(reduce(F, S[:-1], I), s[-1])

################ LEFT REDUCE #################

# reduce(add, (1,2,3),0):

# add(reduce(add, (1,2),0),3)

#add(add(reduce(add, (1), 0),2),3)

#add(add(add(reduce(addm (), 0), 1), 2), 3)

#add(add(add(0, 1),2),3)

#((0+1)+2)+3 = 6

############### RIGHT REDUCE ################

# rightReduce(F, (e0, e1, e2), I)

# F(e0, F(e1, F(e2, I)))

# implement this using forward indexing (0...len(s)-1)


#names = ('prince', 'John Quincy Adams', ...)

#oneName = filter((lambda name: not blanky(name)), names)

#lengths = map(len, oneName)

#howMany = len(oneName)

#sumOfLengths = reduce((lambda A, B: A+B), lengths, 0)

#average = sumOflengths/howMany

### How class works

##class Time:

## def __init__(self, hour, minute, seconds):

## self.__hour = hour

## self.__minute = minute

## self.__seconds = seconds

##

## def getHour(self):

## return __self.hour

## def getMinute(self):

## return __self.minute

## def getSecond(self):

## return __self.seconds

## def printTime(self): # METHOD !

## print ("ddfdf")

##

##time = Time(11, 59, 30)

##time.printTime()
def divide(X,Y):

return X / Y

def rightReduce(F,S,I):

if len(S) == 0:

return I

else:

return F(S[-len(S)], rightReduce(F,S[1:],I))

def reduce(F,S,I):

if len(S) == 0:

return I

else:

return F(reduce(F,S[:-1],I), S[-1])

print(rightReduce(divide,(16,4,2),32))

print(reduce(divide,(16,4,2),32))

Você também pode gostar