March 5-7, 2019 Vikrant Patil
These notes are available online at http://notes.pipal.in/2019/pccoe_basic/day3.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
print_triangle which will print a triangle of * of base n.
>>> print_triangle(5)
*
* *
* * *
* * * *
* * * * *
Take home assignment
pascal to generate pascal traingle as a 2D list.
>>> pascal(4)
[[1],[1,1],[1,2,1],[1,3,3,1]]
print_pascal to print pascal triangle of base n.
>>> print_pascal(4)
1
1 1
1 2 1
1 3 3 1
`
dirtree to generate tree structure of directory
>>> dirtree(os.getcwd())
.
├── day1.html
├── day1.ipynb
├── day2.html
├── day2.ipynb
├── hello.py
├── helloworld.py
├── Makefile
├── push
├── __pycache__
│ ├── square1.cpython-37.pyc
│ ├── square2.cpython-37.pyc
│ └── square.cpython-37.pyc
├── python_basic
│ └── Untitled.ipynb
├── square1.py
├── square2.py
└── square.py
def mtable(n):
return [n*i for i in range(1,11)]
mtable("*")
def triangle(base, char="*"):
return [char*i for i in range(1, base+1)]
triangle(3)
triangle(5, "@")
def print_triangle(tr):
for line in tr:
print(line)
t10 = triangle(10)
print_triangle(t10)
def print_triangle1(tr):
width = len(tr[-1])
for line in tr:
print(line.center(width))
print_triangle1(t10)
" ".join(["x","y","z"])
" ".join("xyz")
def print_triangle2(tr):
width = len(tr[-1])
width = width + width -1
for line in tr:
line = " ".join(line)
print(line.center(width))
print_triangle2(t10)
print_triangle2(triangle(25))
print_triangle2(triangle(25, "@"))
How do we add two vectors?
x = [1,2,3,4]
y = [1,1,1,1]
z = []
for i in range(4):
z.append(x[i] + y[i])
z
[x[i]+ y[i] for i in range(4)]
z = []
for a, b in zip(x,y):
z.append(a+b)
z
[a+b for a,b in zip(x,y)]
z = [a+b for a,b in zip(x,y)]
def pascal(base):
t = [[1]]
for i in range(base-1):
last = t[-1]
x = last[:] + [0]
y = [0] + last[:]
z = [a+b for a,b in zip(x,y)]
t.append(z)
return t
pascal(5)
print_triangle2(pascal(5))
def to_text(data):
return [[str(item) for item in row] for row in data]
to_text(pascal(5))
print_triangle2(to_text(pascal(5)))
print_triangle2(to_text(pascal(6)))
print_triangle2(to_text(pascal(10)))
def print_triangle3(tr):
def linelength(line):
return len(" ".join(line))
width = linelength(tr[-1])
for line in tr:
line = " ".join(line)
print(line.center(width))
print_triangle3(to_text(pascal(10)))
for i in range(1,11):
print(i,i*i,i*i*i)
for i in range(1,11):
print("{:2} {:3} {:4}".format(i,i*i,i*i*i))
for i in range(1,11):
print("{n:2} {sqr:3} {cube:4}".format(n=i,sqr=i*i,cube=i*i*i))
def print_triangle4(tr):
def linewidth(line):
return maxdigits*len(line) + len(line)-1
def format_line(line):
s = ""
for item in line:
s = s+ " {n:{maxdigits}}".format(n=item, maxdigits=maxdigits)
return s
maxdigits = len(max(tr[-1], key=len))
width = linewidth(tr[-1])
for line in tr:
line = format_line(line)
print(line.center(width))
print_triangle4(to_text(pascal(10)))
print_triangle4(to_text(pascal(15)))
import this
%%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 file:
print(file.read()) # read complete file
with open("poem.txt") as file:
for i in range(5):
print(file.readline(), end="")
with open("poem.txt") as file:
lines = file.readlines() # this reads all lines and gives it as list of lines
for i, l in enumerate(lines):
print(i+1, l, end="")
!head -n 3 poem.txt
def head(filename, n=5):
with open(filename) as f:
for i in range(n):
print(f.readline(), end="")
head("poem.txt")
!cat poem.txt
f = open("poem.txt")
help(f.readlines)
f.readlines(10)
f.close()
f = open("poem.txt")
print(f.readlines(3))
f.readline()
print(f.readlines(0))
f.close()
f = open("poem.txt")
f.readlines(100)
f.close()
f = open("poem.txt")
f.readlines(-1)
f.close()
f = open("poem.txt")
f.readlines(0)
!grep "def " square2.py
problem
%%file cat.py
import sys
def cat(filename):
with open(filename) as file:
print(file.read())
if __name__ == "__main__":
cat(sys.argv[1])
!python cat.py poem.txt
%%file head.py
import sys
def head(file, n):
with open(file) as f:
for i in range(n):
print(f.readline(), end="")
if __name__ == "__main__":
head(sys.argv[1], int(sys.argv[2]))
!python head.py poem.txt 4
!grep "Zen" poem.txt
!grep "than" poem.txt
%%file grep.py
import sys
def grep(filename, pattern):
with open(filename) as f:
for line in f:
if pattern in line:
print(line, end="")
if __name__ == "__main__":
grep(sys.argv[1], sys.argv[2])
!python grep.py poem.txt than
problem
wc as a script wc.py. it prints line count, word count and charecter count.!wc poem.txt
%%file wc.py
"""
This module implements unix command wc
usage:
python wc FILENAME
"""
import sys
def linecount(filename):
"""
returns number of lines in given file
"""
with open(filename) as f:
return len(f.readlines())
def wordcount(filename):
"""
counts number of words in given file
"""
with open(filename) as f:
return len(f.read().split())
def charcount(filename):
"""
returns number of charecters in given file
"""
with open(filename) as f:
return len(f.read())
if __name__ == "__main__":
filename = sys.argv[1]
print(linecount(filename), wordcount(filename), charcount(filename), filename)
!python wc.py poem.txt
import wc
help(wc)
"asas asdad sadsdsd sdsdds".split(" ")
"asas asdad sadsdsd sdsdds".split()
with open("data.txt", "w") as f:
f.write("one\n")
f.write("two\n")
f.write("three\n")
!python cat.py data.txt
with open("data.txt", "w") as f:
f.write("four\n")
f.write("five\n")
f.write("six\n")
!python cat.py data.txt
with open("data.txt", "a") as f:
f.write("one\n")
f.write("two\n")
f.write("three\n")
!python cat.py data.txt
with open("data.bin", "wb") as b:
b.write(b"hello world!")
with open("data.bin", "rb") as b:
print(b.read())
"hello".encode()
binary = b"hello"
binary.decode()
machine = {
"name":"mozart",
"cpu":"corei3",
"memory":"4GB",
"os":"mint"
}
for key in machine:
print(key, end=",")
for key in machine:
print(key, machine[key])
for key, value in machine.items():
print(key, value)
for value in machine.values():
print(value, end=",")
machine['manufacturer']
machine.get('manufacturer',"Acer")
machine.get('cpu',"corei5")
a = ['name','cpu','memory','os']
b = ['mozart','corei3','4GB','mint']
dict(zip(a,b))
%%file words.txt
one
one two
one two three
one two three four
one two three four five
one two three four six
one two six seven
six seven eight
nine eight
ten
def get_words(filename):
with open(filename) as f:
return f.read().split()
words = get_words("words.txt")
uniquewords = set(words)
uniquewords
uniquewords.add('five')
uniquewords
for w in uniquewords:
print(w)
for w in uniquewords:
print(w, words.count(w))
def wordfreq(words):
uniquewords = set(words)
freq = {}
for w in uniquewords:
freq[w] = words.count(w)
return freq
wordfreq(words)
freq = wordfreq(words)
sorted(freq)
for word, f in freq.items():
print(word, f)
def print_freq(freq):
def get_freq(key):
return freq[key]
for word in sorted(freq, key=get_freq):
print(word, freq[word])
print_freq(freq)
def print_freq(freq):
def get_freq(key):
return freq[key]
for word in sorted(freq, reverse=True, key=get_freq):
print(word, freq[word])
print_freq(freq)
def print_freq(freq):
def get_freq(key):
return freq[key]
for word in sorted(freq, reverse=True, key=get_freq):
print(word.rjust(5), freq[word], "*"*freq[word])
print_freq(freq)
%%file bank0.py
balance = 0
def get_balance():
return balance
def deposite(amount):
global balance
balance += amount
def withdraw(amount):
global balance
balance -= amount
if __name__ == "__main__":
pass
import bank0 as account
account.get_balance()
account.deposite(100)
account.get_balance()
account.withdraw(20)
account.get_balance()
%%file bank1.py
def create_account():
return {"balance":0}
def get_balance(account):
return account['balance']
def deposite(account, amount):
account['balance'] += amount
def withdraw(account, amount):
account['balance'] -= amount
if __name__ == "__main__":
pass
import bank1 as bank
a1 = bank.create_account()
a2 = bank.create_account()
bank.deposite(a1, 1000)
bank.deposite(a2, 100)
bank.get_balance(a1)
bank.get_balance(a2)
bank.withdraw(a1, 200)
bank.get_balance(a1)
class BankAccount:
def __init__(self):
self.balance = 0
def get_balace(self):
return self.balance
def deposite(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
a1 = BankAccount()
a2 = BankAccount()
a1.deposite(1000)
a2.deposite(200)
a1.get_balace()
a2.get_balace()
def add():
pass
add
class Foo:
pass
Foo
f = Foo()
f
x = [1,2,3,4]
x
type(x)
type(f)
type(Foo)
type(1)
isinstance(1, int)
isinstance(f, Foo)
isinstance(a1, BankAccount)
isinstance(a1, Foo)
problem
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def distance(self):
return (self.x**2 + self.y**2)**0.5
p1 = Point(1,1)
p1.getX()
p1.
problem
Timer which has methods start, stop and time_taken. When you call start, it should note time at that instance and store it. when you call stop method, it notes time and stores it. when you call time_taken method it returns difference between start time and stop time.>>> t = Timer()
>>> t.start()
>>> func()
>>> t.stop()
>>> print(t.time_taken())
3.00
import time
time.time()
p1
print(__name__)
add
add = 2
add
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 time_taken(self):
return self._end - self._start
def reset(self):
self._start = 0
self._end = 0
import math
def foo():
s = 0
for i in range(100000000):
s = s + math.sqrt(i+100)
return s
from math import sqrt
def bar():
s = 0
for i in range(100000000):
s = s + sqrt(i+100)
return
t = Timer()
t.start()
foo()
t.stop()
print("Time taken by foo:", t.time_taken())
t.reset()
t.start()
bar()
t.stop()
print("Time taken by bar:", t.time_taken())