In [7]:
#EX from 25 ZS#
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
In [8]:
#EX from 25 ZS#
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print "--------------"
print poem
print "--------------"
five = 10 - 2 + 3 - 6
print "This should be five: %s" % five
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates."
In [9]:
#EX from 25 ZS#
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78,4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
In [11]:
#EX from 20 ZS#
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
In [12]:
#EX from 19 ZS#
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
In [13]:
#EX from 18 ZS#
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no arguments
def print_none():
print "I got nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
In [5]:
#EX 28#
print True and True
print False and True
print 1 == 1 and 2 == 1
print "test" == "test"
print 1 == 1 or 2 != 1
print True and 1 == 1
print False and 0 != 0
print True or 1 == 1
print "test" == "testing"
print 1 != 0 and 2 == 1
print "test" != "testing"
print "test" == 1
print not (True and False)
print not (1 == 1 and 0 != 1)
print not (10 == 1 or 1000 == 1000)
print not (1 != 10 or 3 == 4)
print not ("testing" == "testing" and "Zed" == "Cool Guy")
print 1 == 1 and not ("testing" == 1 or 1 == 0)
print "chunky" == "bacon" and not (3 == 4 or 3 == 3)
print 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
In [6]:
#EX 29#
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than equal to dogs."
if people <= dogs:
print "People are less than equal to dogs."
if people == dogs:
print "People are dogs."
In [7]:
#EX 30#
people = 30
cars = 40
buses = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."
else:
print "Fine, let's stay home then."
In [9]:
#EX 31#
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
elif door == "2":
print "You stare into the endless abyss at Cthuhlu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Good job!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"
else:
print "You stumble around and fall on a knife and die. Good job!"
In [11]:
#EX 32#
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 20 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was: %d" % i
In [13]:
#EX 33#
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
In [ ]:
#EX 35#
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you then pimp slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your crotch off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulu_room():
print "Here you see the great evil Cthulu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulu_room()
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulu_room()
else:
dead("You stumble around the room until you starve.")
start()
In [17]:
#EX 39#
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There's %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!
In [18]:
#Filter function#
print("Filter Functions ................................")
pList1 = list(range(1,10))
print(pList1)
def pEven(x) : return x%2 == 0
pList2 = list(filter(pEven,pList1))
print(pList2)
pList3 = ["Ram", "RamPM", "Shyam", "PMShyam", "Sita", "SiPMMta"]
print(pList3)
def hasPM(x) : return "PM" in x
pList4 = list(filter(hasPM, pList3))
print(pList4)
In [19]:
# Lambda functions#
print("Lambda Functions ................................")
pList2a = list(filter (lambda x : x%2 == 0, pList1))
print(pList2a)
pList4a = list(filter(lambda x: "PM" in x, pList3))
print(pList4a)
In [20]:
# Map
print("Map Functions ................................")
pList5 = list(map(lambda x : x*x, pList1)) # square each number in the list
print(pList5)
pList6 = list(map(lambda x : "Y"+x, pList3)) # appends the char Y to each string in the list
print(pList6)
pList7 = map(lambda x : len(x), pList3) # returns the number of characters in each string of the list
print(pList7)
pList8 = map(lambda x : (x, len(x)),pList3) # returns a list of tuples
print(pList8)
In [21]:
# Reduce
print("Reduce Functions ................................")
import functools
pVal1 = functools.reduce(lambda x,y: x+y, pList1) # adding the numbers in a list
print(pVal1)
pVal2 = functools.reduce(lambda x,y: x+y, pList3) # concatenating string in a list
print(pVal2)
pVal3 = functools.reduce(lambda x,y: (x[0]+y[0], x[1]+y[1]), pList8) # adding and concatenating elements in a list
print(pVal3)
In [22]:
#DS 1
pInt = 2
pReal = 2.318281828
pString = "some Test String"
pList2 = [ pInt, pReal, pString, pList1]
print(pList2)
In [23]:
#DS 2
print("Members ---------------------")
print(pList2[0])
print(pList2[1])
print(pList2[2])
print(pList2[3])
print(pList2[3][0])
print(pList2[3][1])
In [24]:
#DS 3
print("Methods ---------------------")
pList1.append(pInt)
print(pList1)
pList1.insert(1,pReal)
print(pList1)
pList1.remove(pReal)
print(pList1)
pList1.extend(pList2)
print(pList1)
In [25]:
#DS 4
print("More Methods ---------------------")
print(pList1.count("some Test String"), pList1.count(pInt))
print(pList1.index(pInt), pList1.index("some Test String"))
pList1.reverse()
print(pList1)
pList1.sort()
print(pList1)
In [26]:
#DS 5
# List as Stack
print("Stack ---------------------")
pStack1 = [12, 20, 7]
pStack1.append(45)
print(pStack1)
pPopped = pStack1.pop()
print(pPopped, pStack1)
In [27]:
#DS 6
# List as Q
print("Q ---------------------")
from collections import deque
pList3 = ["Ram", "Shyam", "Jadu"]
pQ = deque(["Ram", "Shyam", "Jadu"])
a = pQ.popleft()
print(a)
print(pQ)
pQ.append("Sita")
print(pQ)
In [28]:
#DS 7
# Sets
print("Sets ---------------------")
pList10 = ["Apple", "Orange", "Pear", "Mango", "Apple", "Orange", "Pineapple"]
print(pList10)
pSet = set(pList10)
print(pSet)
In [29]:
#DS 8
# Tuples
print("Tuples ---------------------")
pTuple1 = 1, 34, "king", "queen"
print(pTuple1)
print(pTuple1[0], pTuple1[3])
pTuple2 = 23, "new fellow", pTuple1
print(pTuple2)
In [30]:
#DS 9
# Dictionaries
print("Dictionaries ---------------------")
dTel = { "prithwis": 2066, "charan" : 8077, "govind" : 9234, "jaydeep" : 9324}
print(dTel)
print(dTel.keys())
print(dTel.values())
dTel['SDG'] = 9056
print(dTel)
dTel['prithwis'] = 6602
print(dTel)
print("prithwis" in dTel)
print("Prithwis" in dTel)
In [31]:
#DS 10
# Looping
print("Looping ..........................")
for key, val in dTel.items():
print (key, val)
In [32]:
#DS 11
print("Enumerate ..........................")
for ix, val in enumerate(pList1):
print (ix,val)
for ix, val in enumerate(pTuple1):
print (ix,val)
for ix, val in enumerate(dTel):
print (ix,val)
In [33]:
#DS 12
print("Zip ..........................")
teachers = ["prithwis","charan","jaydeep","subhasis"]
subjects = ["bigdata", "communications", "stats", "datamining"]
for t,s in zip(teachers,subjects):
print(t," teaches ",s)
In [34]:
#DS 13
# Membership
print(pInt in pList2)
print(2 in pList2)
print(33 not in pList2)
fruit1 = ["apple", "pear", "orange", "mango"]
fruit2 = ["apple", "grape", "banana","mango"]
print("pear" in fruit1)
print("pear" in fruit2)
print (set(fruit1).intersection(fruit2))
print (set(fruit1).union(fruit2))
In [39]:
#numpy
import numpy as np
a = np.arange(15).reshape(3, 5)
print a
print a.shape
print a.ndim
print a.dtype.name
print a.size
print a.itemsize
In [40]:
b = np.array([1.2, 3.4, 5.1])
print b.dtype
In [42]:
b = np.array([(1,2), (8,9)], dtype = complex)
b
Out[42]:
In [43]:
a = np.zeros((3,4))
b = np.ones((5,6))
c = np.empty((2,2))
print a
print b
print c
In [44]:
a = np.arange(10,20,2)
print a
In [49]:
from numpy import pi
import matplotlib.pyplot as plt
%matplotlib inline
a = np.linspace(0,2*pi,100)
b = np.sin(a)
plt.plot(a, b)
Out[49]:
In [54]:
a = np.arange(20).reshape(4,5)
b = np.arange(20).reshape(5,4)
a<15
Out[54]:
In [58]:
A = np.array( [[1,1],[0,1]] )
B = np.array( [[2,0],[3,4]] )
print A*B
print np.cross(A, B)
print np.dot(A, B)
In [60]:
a = np.ones((2,3), dtype=int)
b = np.random.random((2,3))
a *= 3
print a
In [65]:
a = np.random.random((2, 3))
print a
print a.min()
print a.max()
print a.mean()
In [67]:
b = np.arange(12).reshape(3,4)
print b
print b.sum(axis=0) # sum of each column
print b.min(axis=1) # min of each row
print b.cumsum(axis=1) # cumulative sum along each row
In [69]:
B = np.arange(3)
C = np.array([2., -1., 4.])
print np.exp(B)
print np.sqrt(B)
print np.add(B, C)
In [78]:
a = np.arange(10)**3
print a
print a[2:5]
print a[1:7:2]
print a[::-1]
for i in a:
print (i**(1/3))
In [87]:
def f(x,y):
return 10*x+y
b = np.fromfunction(f,(5,4),dtype=int)
print b
print b[:, 2]
print b[:3, :]
for row in b:
print row
for element in b.flat:
print element
In [99]:
a = np.floor(10*np.random.random((3,4)))
print a
print a.shape
print a.ravel()
print a.reshape(6,2)
print a.T
print a.T.shape
In [100]:
a = np.floor(10*np.random.random((2,2)))
print a
b = np.floor(10*np.random.random((2,2)))
print b
print np.vstack((a,b))
print np.hstack((a,b))
In [103]:
from numpy import newaxis
print np.column_stack((a,b)) # With 2D arrays
a = np.array([4.,2.])
b = np.array([2.,8.])
print a[:,newaxis] # This allows to have a 2D columns vector
print np.column_stack((a[:,newaxis],b[:,newaxis]))
print np.vstack((a[:,newaxis],b[:,newaxis]))
In [104]:
a = np.floor(10*np.random.random((2,12)))
print a
print np.hsplit(a,3)
print np.hsplit(a,(3,4))
In [105]:
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot( h,w, maxit=20 ):
"""Returns an image of the Mandelbrot fractal of size (h,w)."""
y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ]
c = x+y*1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
for i in range(maxit):
z = z**2 + c
diverge = z*np.conj(z) > 2**2 # who is diverging
div_now = diverge & (divtime==maxit) # who is diverging now
divtime[div_now] = i # note when
z[diverge] = 2 # avoid diverging too much
return divtime
plt.imshow(mandelbrot(400,400))
plt.show()
In [106]:
import numpy as np
a = np.array([[1.0, 2.0], [3.0, 4.0]])
print(a)
a.transpose()
np.linalg.inv(a)
u = np.eye(2) # unit 2x2 matrix; "eye" represents "I"
u
j = np.array([[0.0, -1.0], [1.0, 0.0]])
np.dot (j, j) # matrix product
np.trace(u) # trace
y = np.array([[5.], [7.]])
np.linalg.solve(a, y)
np.linalg.eig(j)
Out[106]:
In [107]:
import numpy as np
import matplotlib.pyplot as plt
# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2
mu, sigma = 2, 0.5
v = np.random.normal(mu,sigma,10000)
# Plot a normalized histogram with 50 bins
plt.hist(v, bins=50, normed=1) # matplotlib version (plot)
plt.show()
In [ ]: