Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added Examples/Session05/codingbat.pyc
Binary file not shown.
151 changes: 151 additions & 0 deletions Students/salim/notes/class_notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,12 @@ def complex_function(arg1, arg2, kwarg1=u'bannana'):

############################## SESSION03 ##############################

"""
making a python file an executable:
- change the mode of the file to executable: chmod +x myscript.py
- add the path to python at the top with '#!' before
"""

"""
git question:
- create a pull request for the branch itself
Expand Down Expand Up @@ -643,3 +649,148 @@ def func(c, list=[]): # this is wrong because it dones't create a function le
return list.append(c)


############################## SESSION03 ##############################
"""
you almost never have to loop through sequences using range()
- zip() will zip lists together
- unpack embedded squences using this construct
"""

a_list = [(1,2), (3,4), (5,6)]

for i, j in a_list:
print i
print j

"""
enumerate allows you to get the indix while you are looping through a sequence
"""

for i, item in enumerate(a_list):
print i
print item

"""
buidling up a long string:
- one option is to continue to keep += to the string. however, this is
an inefficent process
- a better way is to build a list, then use " ".join(list)

sorting data:
- when you

"""

fruits = ['Apples', 'Pears', 'Grapes']
numbers = [1, 2, 3]
combine = zip(fruits, numbers)

def sort_key(item):
return item[1]

combine.sort(key=sort_key)

"""
you can build up strings for formatting before you subistiute values in
"""

s = 'Hello ' + '%d' * 4
print s % (1,2,3,4)

"""
dictionaries:
- create a dict with d = {}
- keys don't have to be the same type and values don't have to be the same
type
- keys can be any immutable object (technically "hash" objects):
- number
- string
- tuple
- dictionaries are unordered (due to the way they are built using hasing)
- dictionaries are very effecicent

dictionary methods
- dict.setdefault() <-- will use this in the homework
- dict.iteritems() <-- will not return a list

hashing:
- missed this so read the class notes
"""

"""
Exceptions:
- you can use "finally" at the end of an exception, which will always get
run
- they also have an "else" which will run if there is no exception
"""
# never do this! this doesn't give you information about the exception
try:
do_something()
except:
print "something went wrong."

"""
reading and writing files:

text files:
- f
"""

f = open('secrets.txt')
secret_data = f.read()
f.close()



############################## SESSION04 ##############################

""" dealing with "ordered" / "sorted" dicts """

# option #1
import collections # package with tools for dealing with dicts
o_dict = collections.OrderedDict() # this will create an ordered dict

# option #2
sorted() # built in function that sorts iterables

""" Advanced argument passing """

# keyword arguments
def fun(a, b = True, c = False):
return

# functional arguments

def func(x, y, w=0, h=0): # positional arguments are tuples
# keywork arguments are dictionaries
print "%s %s %s %s" % (x, y, x, h)

a_tuple = (1, 2)
a_dict = {'w':1, 'h': 2}
func(*a_tuple, **a_dict) # you can pass the tuple and dict in directly

def func(*args, **kwargs): # you can recieve an undefined number of args
print args
print kwargs

"""mutablility"""

import copy # for making copies of objects

copy.deepcopy() # this is how you make a deep copy


"""list comprehensions"""
l = [1, 2, 3]
[i * 2 for i in l]
[i * 2 for i in l if i > 1] # you can have an if statement here

# searching 'in' a sequence is faster with sets because they are hash tables

"""set comprehension"""

"""dict comprehensions"""


"""testing in python"""

Binary file added Students/salim/session03/.mailroom.py.swp
Binary file not shown.
1 change: 1 addition & 0 deletions Students/salim/session03/list_lab.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python


# print original list
a_list = ['Apples', 'Pears', 'Oranges', 'Peaches']
print a_list
Expand Down
81 changes: 81 additions & 0 deletions Students/salim/session04/cp_dict_set_lab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python


# #############################Lesson 1##############################

# create dict
d1 = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
print d1

# delete entry for cake
del d1['cake']
print d1

# add an entry to the dict
d1['fruit'] = 'Mango'
print d1

# display the values
d1.values()

# display the keys
d1.keys()

# is 'cake' a key in the dict?
'cake' in d1

# is 'Mango' a value in the dict?
'Mango' in d1.values()


# #############################Lesson 2##############################

# create list from 0 to 15
l2 = range(16)

# create list with hex representation
s2 = []
for item in l2:
s2.append(hex(item))

# zip lists into dict
d2 = dict(zip(l2, s2))


# #############################Lesson 3##############################

# use d1 to create a new dict with same keys but number of 't's in values
d3 = {}
for key, value in d1.iteritems():
d3[key] = value.count('t')


# #############################Lesson 4##############################

# make three sets
s2 = set(range(0, 20, 2))
s3 = set(range(0, 20, 3))
s4 = set(range(0, 20, 4))

# print the sets
print s2
print s3
print s4

# check sets
s3.issubset(s2)
s4.issubset(s2)


# #############################Lesson 4##############################

a_set = set('Python')
a_set.add('i')

b_set = frozenset('marathon')

u_set = a_set.union(b_set)
i_set = a_set.intersection(b_set)

print u_set
print i_set
81 changes: 81 additions & 0 deletions Students/salim/session04/dict_set_lab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python


# #############################Lesson 1##############################

# create dict
d1 = {'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate'}
print d1

# delete entry for cake
del d1['cake']
print d1

# add an entry to the dict
d1['fruit'] = 'Mango'
print d1

# display the values
d1.values()

# display the keys
d1.keys()

# is 'cake' a key in the dict?
'cake' in d1

# is 'Mango' a value in the dict?
'Mango' in d1.values()


# #############################Lesson 2##############################

# create list from 0 to 15
l2 = range(16)

# create list with hex representation
s2 = []
for item in l2:
s2.append(hex(item))

# zip lists into dict
d2 = dict(zip(l2, s2))


# #############################Lesson 3##############################

# use d1 to create a new dict with same keys but number of 't's in values
d3 = {}
for key, value in d1.iteritems():
d3[key] = value.count('t')


# #############################Lesson 4##############################

# make three sets
s2 = set(range(0, 20, 2))
s3 = set(range(0, 20, 3))
s4 = set(range(0, 20, 4))

# print the sets
print s2
print s3
print s4

# check sets
s3.issubset(s2)
s4.issubset(s2)


# #############################Lesson 4##############################

a_set = set('Python')
a_set.add('i')

b_set = frozenset('marathon')

u_set = a_set.union(b_set)
i_set = a_set.intersection(b_set)

print u_set
print i_set
11 changes: 11 additions & 0 deletions Students/salim/session04/exception_lab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env python


def safe_input():
try:
return raw_input('Type ^c or ^d to raise an error.')
except (KeyboardInterrupt, EOFError):
return None

if __name__ == '__main__':
safe_input()
48 changes: 48 additions & 0 deletions Students/salim/session04/files_lab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python


def read_file_to_list(a_file):
"""Return a list of the lines in a file with newlines removed"""
# move file to begining
a_file.seek(0)

# add lines to list
a_list = []
for line in a_file:
a_list.append(line.strip())

return a_list


def parse_languages(a_list):
"""Return a list of distinct languages."""
a_set = set()

# parse text file
for item in a_list:
# split students and languages
student_lang = item.split(':')

# split languages
lang = student_lang[1].split(',')

# add languages to set
for l in lang:
if len(l.strip()) > 0:
a_set.add(l.strip())

# convert to list
b_list = []
for language in a_set:
b_list.append(language)

# sort list
b_list.sort()

return b_list


path_students = '../../../Examples/Session01/students.txt'
file_students = open(path_students, 'r')
list_students = read_file_to_list(file_students)
list_languages = parse_languages(list_students)
Loading