Jun 03-04, 2019 Vikrant Patil
These notes are available online at http://notes.pipal.in/2019/arcesium_basic_jun/day2.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
problems
factors using list comprehension which finds all factors of given number.is_prime which tells whether given number is prime or notprimes which generates all primes less than nbonus
def factors(n):
return [i for i in range(1,n+1) if n%i==0]
def test_factors():
assert factors(2) == [1,2]
assert factors(5) == [1,5]
assert factors(6) == [1,2,3,6]
assert factors(10) == [1,10]
test_factors()
factors(10)
def is_prime(p):
return factors(p) == [1,p]
def prime_check(p):
if len(factors(p))==2:
return True
else:
return False
is_prime(12)
is_prime(13)
def primes(n):
return [p for p in range(2,n) if is_prime(p)]
primes(50)
x = [[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
[[(i,j) for i in range(5)] for j in range(5)]
def diagonal(i, j):
if i==j:
return 1
else:
return 0
[[diagonal(i, j) for i in range(5)] for j in range(5)]
[[1 if i==j else 0 for i in range(5)] for j in range(5)]
d = {True:1, False:0}
[[d[i==j] for i in range(5)] for j in range(5)]
sum([i for i in range(1000) if i%7==0 or i%11==0])
tables = [[i*j for i in range(1,6)] for j in range(1,11)]
tables
[tables[i][2] for i in range(10)]
def column(data, colnum):
return [data[i][colnum] for i in range(len(data))]
column(tables, 2)
column(tables, 3)
def transpose(matrix):
colcount = len(matrix[0])
return [column(matrix, i) for i in range(colcount)]
transpose(tables)
tables
primes_ = primes(50)
primes_
for p in primes_:
print(p, end=" ")
for p in reversed(primes_):
print(p, end=" ")
rprimes = reversed(primes_)
for i in rprimes:
print(i, end=" ")
for i in rprimes:
print(i, end=" ")
rprimes
for i, item in enumerate(primes_):
print(i+1, item)
import this
poem = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
lines = poem.strip().split("\n")
for i, l in enumerate(lines):
print(i+1, l)
enumitr = enumerate(lines)
enumitr
next(enumitr)
next(enumitr)
next(enumitr)
for i, l in enumitr:
print(i, l)
nums = [1, 2, 3, 4, 5]
words = ["one", "two", "three", "four", "five"]
for x,y in zip(nums, words):
print(x, y)
zipped = zip(nums, words)
for i, j in zipped:
print(i, j)
list(zip(*tables))
range(5)
reversed(primes_)
list(reversed(primes_))
for i in range(1,11):
print(i, i*i, i*i*i)
for i in range(1,11):
print(str(i).rjust(2), str(i*i).rjust(3), str(i*i*i).rjust(4))
template = """
<html>
<header>
{header}
</header>
<body>
<p>
{contents}
</p>
</body>
</html>
"""
print(template.format(header="HEADER", contents=poem))
problem
>>> pascal(4)
[[1],[1,1],[1,2,1],[1,3,3,1]]
*
* *
* * *
* * * *
* * * * *
"{} of oz is {}".format("wizard", "python")
"{1} of oz is {0}".format("wizard", "python")
"{char} of oz is {name}".format(char="wizard", name="python")
for i in range(1,11):
print("{unit:2d} {sqr:3d} {cube:4d}".format(unit=i, sqr=i*i, cube=i**3))
row = [1, 2, 1]
def nextrow(row):
r1 = row[:] + [0]
r2 = [0] + row[:]
return [x+y for x,y in zip(r1, r2)]
r = nextrow(row)
r
nextrow(r)
nextrow(nextrow(r))
def pascal(n):
tr = [[1]]
for i in range(n-1):
r = tr[-1]
nr = nextrow(r)
tr.append(nr)
return tr
pascal(4)
def triangle(n):
return ["*"*j for j in range(1, n+1)]
triangle(5)
for item in triangle(7):
print(item.center(7))
def pretty_triangle(t):
pt = []
size = len(t)
for row in t:
formatedrow = ""
for item in row:
formatedrow += " {}".format(item)
pt.append(formatedrow.center(size*2))
return pt
pretty_triangle(triangle(7))
def test_printtraingle():
t = pretty_triangle(triangle(10))
l = len(t[0])
for i, item in enumerate(t):
assert l == len(item)
assert i+1 == item.count("*")
assert len(item.strip().split()) == i+1
test_printtraingle()
def print_triangle(t):
for row in t:
print(row)
t = pretty_triangle(triangle(3))
print_triangle(t)
print_triangle(pretty_triangle(triangle(50)))
print(poem)
%%file poem.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
with open("poem.txt") as f:
print(f.read())
f = open("poem.txt")
f.read()
f.close()
with open("poem.txt", "r") as f:
print(f.readline(), end="")
print(f.readline(), end="")
for line in f.readlines():
print("*", line, end="")
with open("poem.txt") as f:
for i, line in enumerate(f):
print(i+1, line, end="")
with open("poem.txt") as f:
for i, line in enumerate(f):
print(i+1, line.strip())
with open("poem.txt") as f:
lines = f.readlines()
print(max(lines, key=len))
with open("poem.txt") as f:
print(max(f, key=len))
f = open("poem.txt")
next(f)
l = [1, 2, 3, 4, 5,6]
r = reversed(l)
f.close()
with open("numbers.txt", "w") as f:
f.write("one\n")
f.write("two\n")
f.write("three\n")
f.write("four\n")
problems
cat.py which mimics unix commans cat. it prints contents of file to standard output.
python cat.py numbers.txt
one
two
three
four
head.py which prints initial few lines from the file
python head.py 3 numbers.txt
one
two
three
%%file cat.py
import sys
def cat(filename):
with open(filename) as f:
print(f.read(), end="")
if __name__ == "__main__":
cat(sys.argv[1])
!python cat.py numbers.txt
%%file head.py
import sys
def head(filename, n):
with open(filename) as f:
for i in range(n):
print(f.readline(), end="")
if __name__ == "__main__":
if len(sys.argv)==4 and sys.argv[1] == "-n":
n = int(sys.argv[2])
filename = sys.argv[3]
head(filename, n)
elif len(sys.argv)==2:
head(filename, 5)
else:
help_ = """
Usage:
python head.py -n 5 filename
or
python head.py filename
"""
print(help_)
!python head.py
!python head.py -n 3 poem.txt
with open("numbers.txt", "a") as f:
f.write("\n")
f.write("two\n")
f.write("three\n")
f.write("four\n")
!python cat.py numbers.txt
problems
tables
",".join([str(p) for p in primes_])
def writecsv(data, filename):
with open(filename, "w") as f:
for row in data:
f.write(",".join([str(item) for item in row]))
f.write("\n")
writecsv(tables, "table.csv")
!python cat.py table.csv
def parseCSV(filename):
with open(filename) as f:
d = []
for line in f:
row = line.strip().split(",")
d.append(row)
return d
parseCSV("table.csv")
def parseCSV(filename):
with open(filename) as f:
return [line.strip().split(",") for line in f]
parseCSV("table.csv")
def parseCSV(filename):
with open(filename) as f:
return [[int(i) for i in line.strip().split(",")] for line in f]
parseCSV("table.csv")
%%file wc.py
import sys
def linecount(filename):
with open(filename) as f:
return len(f.readlines())
def wordcount(filename):
with open(filename) as f:
return len(f.read().split())
def charcount(filename):
with open(filename) as f:
return len(f.read())
if __name__ == "__main__":
f = sys.argv[1]
print(linecount(f), wordcount(f), charcount(f), f)
!python wc.py poem.txt
f = open("poem.txt")
f.read().split()
f.close()
"w" -> write
"a" -> append
"b" -> binary
"rb" -> read binary
"wb" -> write binary
keys = ["processor", "os", "memory", "brand"]
values = ["Corei5", "mint", "4GB", "Acer"]
specs = dict(zip(keys, values))
specs
specs['processor']
specs['cache']
specs.get("cache", "2MB")
specs
specs['cache']
specs.get("cache", "2MB")
specs.get("os", "windows")
specs.get("cache", None)
list = [1, 2, 3, 4, 5]
list(reversed(primes_))
del list
list(range(5))
del specs['processor']
specs
specs['processor'] = "corei3"
specs
%%file words.txt
one
one two
one two three
one two three four
one two three four five
one two three four five six
one two three seven six
one two eight seven six
one nine eight seven six
ten nine eight seven
ten nine eight
ten nine
ten
def getwords(filename):
with open(filename) as f:
return f.read().split()
words = getwords("words.txt")
len(words)
def wordfreq(words):
freq = {}
for w in words:
if w in freq:
freq[w] += 1
else:
freq[w] = 1
return freq
wordfreq(words)
def wordfreq(words):
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
return freq
wordfreq(words)
def wordfreq(words):
freq = {}
uniq = set(words)
for w in uniq:
freq[w] = words.count(w)
return freq
wordfreq(words)
freq = wordfreq(words)
freq.get("one")
freq
for item in freq:
print(item)
for item in freq:
print(item, freq[item])
def getfreq(w):
return freq[w]
for item in sorted(freq, key=getfreq):
print(item, freq[item])
for item in sorted(freq, key=getfreq, reverse=True):
print(item, freq[item])
for item in sorted(freq, key=getfreq, reverse=True):
print(item, freq[item], "*"*freq[item])
for item in sorted(freq, key=getfreq, reverse=True):
print(item.rjust(5), freq[item], "*"*freq[item])
dict(zip(keys, values))
freq
freq.keys()
freq.values()
keys= [k for k in freq]
keys
values = [freq[k] for k in keys]
values
[(k, freq[k]) for k in freq]
players = {"Player1":"India","Player2":"USA","PLAYER3":"India", "Player4":"USA", "Player5":"UK"}
players
[p for p in players if players[p]=="India"]
for item in specs:
print(item)
for item in specs.keys():
print(item)
for item in specs.values():
print(item)
for k, v in specs.items():
print(k, v)
%%file bank0.py
balance = 0
def withdraw(amount):
global balance
balance -= amount
def deposit(amount):
global balance
balance += amount
def get_balance():
return balance
import bank0
bank0.get_balance()
bank0.deposit(1000)
bank0.get_balance()
%%file bank1.py
def make_account():
return {"balance":0}
def withdraw(account, amount):
account['balance'] -= amount
def deposit(account, amount):
account['balance'] += amount
def get_balance(account):
return account['balance']
import bank1
a1 = bank1.make_account()
a2 = bank1.make_account()
print("a1 :", bank1.get_balance(a1))
print("a2 :", bank1.get_balance(a2))
bank1.deposit(a1, 20120)
print("a1 :", bank1.get_balance(a1))
print("a2 :", bank1.get_balance(a2))
bank1.deposit(a2, 12320)
print("a1 :", bank1.get_balance(a1))
print("a2 :", bank1.get_balance(a2))
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def get_balance(self):
return self.balance
def foo():
pass
foo
class Foo:
pass
Foo
type(2)
a3 = BankAccount()
type(a3)
a3
BankAccount
a3
a3.get_balance()
a3.deposit(200)
a3.get_balance()
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class RedPoint(Point):
color = "red"
p1 = Point(0, 0)
p1.x
p1.y
r1 = RedPoint(2, 3)
r1.x
r1.y
r1.color
p1.color
Point
RedPoint
RedPoint.color
r2 = RedPoint(2, 3)
RedPoint.color = "RED"
r1.color
r2.color
r1.__dict__
a3.__dict__
a3.__dict__['aadhar'] = 800048882323
a3.aadhar
p1.x
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
p2 = Point(3,4)
p2._x
problem
t = Timer()
t.start()
task()
t.stop()
print("time taken :", t.elapsed_time())
import time
time.time()
def task():
time.sleep(2)
class Timer:
def __init__(self):
self._start = 0
self._end = 0
def start(self):
self._start = time.time()
def stop(self):
self._end = time.time()
def elapsed_time(self):
return self._end - self._start
t = Timer()
t.start()
time.sleep(5)
t.stop()
print("Time taken:", t.elapsed_time())
def timeit(task, args):
t = Timer()
t.start()
task(*args)
t.stop()
return t.elapsed_time()
timeit(time.sleep, (5,))
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Pair(0,1)
p1
l = [1,2]
l
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Pair({},{})".format(self.x, self.y)
def __str__(self):
return "<{},{}>".format(self.x, self.y)
p = Pair(2,3)
p
print(p)
s = "hello"
s
print(s)
str(p)
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Pair({},{})".format(self.x, self.y)
def __str__(self):
return "<{},{}>".format(self.x, self.y)
def __add__(self, p):
return Pair(self.x+p.x, self.y+p.y)
def __eq__(self, p):
return self.x==p.x and self.y==p.y
p1 = Pair(2,3)
p2 = Pair(5,4)
p1 + p2
p1 == p2
2*"*"
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Pair({},{})".format(self.x, self.y)
def __str__(self):
return "<{},{}>".format(self.x, self.y)
def __add__(self, p):
return Pair(self.x+p.x, self.y+p.y)
def __eq__(self, p):
return self.x==p.x and self.y==p.y
def __getitem__(self, name):
if name=="x":
return self.x
elif name=="y":
return self.y
else:
raise KeyError("No such item", name)
p = Pair(5,6)
p['x']
p.x
p['x']
specs
specs['os']
parseCSV("table.csv")
def myint(sn):
try:
return int(sn)
except ValueError as e:
print(e)
return 0
def csvParser(filename):
with open(filename) as f:
return [[myint(i) for i in line.strip().split(",")] for line in f]
csvParser("table.csv")
from functools import reduce
from matplotlib.pyplot import imshow
class Shape:
def contains(self, p):
pass
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle(Shape):
def __init__(self,width, length):
self.w = width
self.l = length
def contains(self, p):
return p.x <= self.w//2 and p.y <= self.l//2
class Circle(Shape):
def __init__(self, radius):
self.r = radius
def contains(self, p):
return (p.x**2 + p.y**2)**0.5 <= self.r
def test_shapes():
c = Circle(5)
assert c.contains(Point(0, 3))
assert not c.contains(Point(6,6))
r = Rectangle(50, 300)
assert r.contains(Point(24, 120))
assert not r.contains(Point(30, 160))
test_shapes()
class Union(Shape):
def __init__(self, shapes):
self.shapes = shapes
def contains(self, p):
conds = [s.contains(p) for s in self.shapes]
return reduce(lambda x, y: x or y, conds, False)
class Intersection(Shape):
def __init__(self, shapes):
self.shapes = shapes
def contains(self, p):
conds = [s.contains(p) for s in self.shapes]
return reduce(lambda x, y: x and y, conds, True)
class Canvas:
def __init__(self, w=1000, l=1000):
self.w = w
self.l = l
self.display = [[False for i in range(w)] for j in range(l)]
def draw(self, shape):
def translate(p):
#return p
return Point(self.w//2 - p.x, self.l//2 - p.y)
self.display = [[shape.contains(translate(Point(i, j))) for i in range(self.w)] for j in range(self.l)]
def plot(self):
imshow(self.display)
reduce(lambda x,y: x and y , [True, True, False, True], True)
reduce(lambda x,y: x and y , [True, True, True, True], True)
%matplotlib inline
from matplotlib.pyplot import imshow
imshow(tables)
c = Circle(50)
canvas = Canvas(100, 100)
canvas.draw(c)
canvas.plot()
c1 = Circle(50)
r1 = Rectangle(10, 120)
u = Union([c1, r1])
inter = Intersection([c1, r1])
canvas = Canvas(100, 100)
canvas.draw(u)
canvas.plot()
canvas = Canvas(100, 100)
canvas.draw(inter)
canvas.plot()
import requests
import requests
url = "https://api.github.com/orgs/google/repos"
repos = requests.get(url).json()
type(repos)
repos[0]
for repo in repos[:5]:
print(repo['full_name'], repo['forks'])
for repo in sorted(repos, reverse=True, key=lambda r: r['forks'])[:5]:
print(repo['full_name'], repo['forks'])
url = "https://www.moneycontrol.com/india/stockpricequote/foodprocessing/apisindia/AI65"
resp = requests.get(url)
resp.status_code
text = resp.content
text = resp.text
print(text[:500])
from bs4 import BeautifulSoup
soup = BeautifulSoup(text, 'html.parser')