Oct 22-24, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/arcesium-advanced-oct/day2.html
© Pipal Academy LLP
for c in "some string":
print(c,end=",")
for n in range(10):
print(n, end=",")
def numbers(n):
print("Begin numbers")
i = 0
while i<n:
print("yielding ...")
yield i
print("Back to numbers...")
i += 1
print("Finished numbers!")
five = numbers(5)
five
next(five)
next(five)
next(five)
next(five)
next(five)
next(five)
for i in numbers(4):
print(i, end=",")
def greet():
name = None
while name != "end":
name = yield "Hello, whats your name"
print("Hello ", name)
g = greet()
g.send(None)
g.send("Vikrant")
three = numbers(3)
three
type(three)
type(g)
g
def numbers(n):
print("Begin numbers")
i = 0
while i<n:
print("yielding ...")
yield i
print("Back to numbers...")
i += 1
print("Finished numbers!")
three = numbers(3)
next(three)
next(three)
next(three)
def numbers_sqrs(n):
print("Begin numbers")
i = 0
while i<n:
print("yielding ...")
yield i
print("Back to numbers...1")
yield i*i
print("Back to numbers...2")
i += 1
print("Finished numbers!")
g = numbers_sqrs(3)
next(g)
next(g)
next(g)
next(g)
next(g)
next(g)
next(g)
problem
countdown which yields numbers top down manner.
>>> for n in coutdown(3):
... print(n, end=",")
>>> 3,2,1
take which makes use of next and list comprehensions to take only first n objects from given generator
>>> take(5, countdown(100))
[100,99,98,97,96]
def countdown(n):
while n>0:
yield n
n -= 1
def take(seq, n):
return [next(seq) for i in range(n)]
def fib():
prev, cur = 1, 1
yield prev
while True:
prev, cur = cur, prev+cur
yield prev
f = fib()
take(f, 10)
import os
import os
def find(location=None):
if not location:
location = os.getcwd()
for dirpath, dirnames, files in os.walk(location):
for f in files:
yield os.path.join(dirpath, f)
files = find(location="/home/vikrant/programming/explorations/python/")
take(pyfiles, 5)
import re
def grep(pattern, seq):
p = re.compile(pattern)
for item in seq:
if p.match(item):
yield item
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
take(pyfiles, 5)
def lines(files):
for f in files:
with open(f) as fd:
for line in fd:
yield line
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
lines_ = lines(pyfiles)
take(grep("^def .*", lines_), 10)
def count(seq):
return sum(1 for item in seq)
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
lines_ = lines(pyfiles)
functions = grep("^def .*", lines_)
count(functions)
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
count(pyfiles)
squares = (i*i for i in range(100))
squares
next(squares)
next(squares)
def squares(n):
return (i*i for i in range(n))
s100 = squares(100)
next(s100)
max([i for i in range(10)])
max(i for i in range(10))
sum(i*i for i in range(100))
{a:y for a,y in [(1,1),(2,2)]}
%%file ssq.py
def SSQ(n):
digits = [int(d) for d in str(n)]
return sum([i*i for i in digits])
def SSQ_(n):
while True:
n = SSQ(n)
yield n
if __name__ == "__main__":
ssq = SSQ_(23)
for i in range(5):
print(next(ssq))
!ls
pdb
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
dom
count(pyfiles)
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
dom
count(pyfiles)
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
dom1
print(count(pyfiles))
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
dom_
print(count(pyfiles))
del dom1
files = find(location="/home/vikrant/programming/explorations/python/")
pyfiles = grep(".*\.py$", files)
dom
lines_ = lines(pyfiles)
funs = grep("^def.*",lines_)
print(count(funcs))
%%file saxpy.py
import time
import math
def saxpy(n):
f = 0
for i in range(n):
for j in range(n):
f = f + i*j*1.0
return f
def compute_sqrt(n):
s = 0
for j in range(n):
for i in range(n):
s += math.sqrt(i)
return s
def compute_sqrt1(n):
sqrt = math.sqrt
s = 0
for j in range(n):
for i in range(n):
s += sqrt(i)
return s
def donothing(t=2):
time.sleep(t)
def main():
for i in range(1000, 5000, 1000):
saxpy(i)
compute_sqrt(i)
compute_sqrt1(i)
donothing()
if __name__ == "__main__":
main()
!python -m cProfile saxpy.py
import cProfile
import math
def compute_sqrt(n):
s = 0
for j in range(n):
for i in range(n):
s += math.sqrt(i)
return s
def compute_sqrt1(n):
sqrt = math.sqrt
s = 0
for j in range(n):
for i in range(n):
s += sqrt(i)
return s
cProfile.run("compute_sqrt(1000)")
cProfile.run("compute_sqrt(1000)")
help(cProfile.run)
cProfile.run("compute_sqrt(1000)", filename="sqrt.profiledata")
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
a
a.shape
a.ndim
a100 = np.arange(100).reshape(10,10)
a100.nbytes
a100.ndim
a100.shape
a100[0]
a100[0][0]
a100[0,0]
a100[:,0]
a100[0,:]
a100
np.zeros(100).reshape(5,20)
np.zeros_like(a100)
np.ones_like(a100)
d = np.asarray([1,2,3,4,5,6,7])
d
np.empty(10)
np.empty_like(d)
np.ones(10, dtype=np.int8)
d
subview = a100[:5,:5]
subview
subview[0,0] = -1
subview
a100
scopy = subview.copy()
scopy
scopy[0,0] = 0
subview
scopy
d
d>3
d[d>3]
d - 2
d2 = d*2
d2
d
d + d2
d * d2
np.exp(d)
a100.max()
a100.mean()
a100.std()
a100.cumsum()
x = np.arange(-5, 5, 0.01)
from scipy.misc import face
image = face(gray=True)
image
from matplotlib import pyplot as plt
%matplotlib inline
def imshow(img):
plt.imshow(img, cmap=plt.cm.gray)
plt.show()
imshow(image)
negate = 255 - image
imshow(negate)
thumb = image[::3,::3]
thumb.shape
imshow(thumb)
a100[:,0] = 0
a100
plain = np.zeros_like(thumb)
imshow(plain)
plain = np.zeros_like(thumb)
plain[::10,:] = 255
plain[:,::10] = 255
imshow(plain)
plain[:11,:11]
plain = np.zeros(100).reshape(10,10)
plain[::3,:] = 255
plain[:,::3] = 255
imshow(plain)
plain = np.zeros_like(thumb)
plain[::10,:] = 255
plain[:,::10] = 255
imshow(thumb*0.5 + plain*0.5)
imshow(thumb)
imshow(image)
thumb = thumb.copy()
thumb.shape
def swapcorners(img):
imglike = img.copy()
h, w, = img.shape
q1 = img[:h//2,:w//2].copy()
q4 = img[h//2:,w//2:].copy()
imglike[:h//2,:w//2] = q4
imglike[h//2:,w//2:] = q1
return imglike
imshow(swapcorners(thumb))
thumb = image[::10,::10]
hthumb = np.hstack([thumb,thumb,thumb])
vthump = np.vstack([hthumb, hthumb, hthumb])
imshow(vthump)
Lets look at some data https://notes.pipal.in/2017/arcesium-oct-advpython/HYDERABAD-weather.csv
!wget https://notes.pipal.in/2017/arcesium-oct-advpython/HYDERABAD-weather.csv
import csv
data = csv.reader(open("HYDERABAD-weather.csv"))
import requests
def download(url, filename):
resp = requests.get(url)
with open(filename, "w") as f:
f.write(resp.text)
url = "https://notes.pipal.in/2017/arcesium-oct-advpython/HYDERABAD-weather.csv"
download(url, "wheatherdata.csv")
!tail wheatherdata.csv
data = list(data)
data[0]
d = data[1:]
def floatcolumn(data, n):
return [float(row[n]) for row in data]
maxtemp = floatcolumn(d, 4)
mintemp = floatcolumn(d, 5)
rainfall = floatcolumn(d, 6)
def float_(sf):
try:
return float(sf)
except Exception as e:
print(e)
return 0
def floatcolumn(data, n):
return [float_(row[n]) for row in data]
rainfall = floatcolumn(d, 6)
plt.scatter(rainfall, maxtemp)
plt.scatter(rainfall, mintemp)
data[0]
year = [int(row[3]) for row in d]
ra = np.array(rainfall)
sorteddata = sorted(d, key=lambda r:r[3])
rainfall = floatcolumn(sorteddata, 6)
year = [int(row[3]) for row in sorteddata]
plt.plot(year, rainfall)
import random
plt.bar(range(12), [random.random() for i in range(12)])
months = np.array([row[2] for row in d])
rainfall = np.array(floatcolumn(d, 6))
rainfall[months=="January"].mean()
def get_mean_rainfall(rainfall, months, month):
return rainfall[months==month].mean()
import datetime
d = datetime.datetime(2000,1,1)
d.strftime("%B")
mnames = [datetime.datetime(2000,i+1,1).strftime("%B") for i in range(12)]
mnames
rainfall_ = [get_mean_rainfall(rainfall, months, m) for m in mnames]
rainfall_
plt.bar(mnames, rainfall_)
plt.bar(range(12), rainfall_)
plt.pie(rainfall_, labels=mnames, explode=[0]*12)
from pandas import Series, DataFrame
s = Series(range(5))
s
s = Series([4,2,7,3],index=['a','b','c','d'])
s
s['a']
s[0]
s['a':'c']
s = Series({"a":1,"b":2,"c":3,"d":4})
s
s = Series({"a":1,"b":2,"c":3,"d":4,"j":6}, index=['e','d','c','b','a'])
s
s[s>2]
s*s
s-1
np.exp(s)
s.reindex(['a','b','c','d','f','g'])
s['f'] = 0
s
months_s = Series(months)
months_s.drop_duplicates()
d
data[0]
df = DataFrame(data[1:], columns=['x', 'city', 'month', 'year', 'maxtemp', 'mintemp', 'rainfall'])
df.describe()
df.head()
df.tail()
import pandas as pd
wd = pd.read_csv("HYDERABAD-weather.csv")
wd.head()
wd.plot("maxtemp", "rainfall", kind="scatter")
grpyear = wd.groupby('year').mean()
grpyear.head()
groupbymonth = wd.groupby("month").mean()
groupbymonth
del groupbymonth['year']
del groupbymonth['Unnamed: 0']
groupbymonth
help(groupbymonth.hist)
groupbymonth.plot()
monthindex = [mnames.index(m) for m in groupbymonth.index]
monthindex
groupbymonth.index
groupbymonth['m'] = monthindex
groupbymonth
groupbymonth.set_index('m').sort_index().plot()
groupbymonth.reindex(mnames).plot()
groupbymonth
groupbymonth.reindex(mnames)
%%file bank.py
balance = 0
def get_balance():
return balance
def withdraw(amount):
global balance
balance -= amount
def deposit(amount):
global balance
balance += amount
import bank
bank.get_balance()
bank.deposit(10)
bank.get_balance()
%%file bank1.py
def make_account():
return {"balance":0}
def get_balance(account):
return account['balance']
def withdraw(account, amount):
account['balance'] -= amount
def deposit(account, amount):
account['balance'] += amount
import bank1
a1 = bank1.make_account()
bank1.get_balance(a1)
bank1.get_balance(a1)
%%file mymodule.py
x = 0
print("location 1")
if __name__ == "__main__":
print("location 2")
import mymodule
!python mymodule.py
%%file mymodule1.py
x = 0
print(__name__)
import mymodule1
!python mymodule1.py
%%file backup.py
def backup():
# go to some location
# delete few old unrequired files
# copy new uopdated files from specfied location
pass
backup()
!python backup.py
%%file backup.py
def backup():
# go to some location
# delete few old unrequired files
# copy new uopdated files from specfied location
pass
if __name__ == "__main__":
backup()
!python backup.py
import math
math.pi