Feb 26-28, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-feb-python
© Pipal Academy LLP
def fibseries(n):
"""
generates list of fibonacci numbers less than n
"""
prev, current = 1,1
series = []
while prev < n:
series.append(prev)
prev, current = current, current+prev
return series
fibseries(100)
fibs = fibseries(100)
fibs
sqrfib = []
for f in fibs:
print(f,end=",")
sqrfib = []
for f in fibs:
sqr = f*f
sqrfib.append(sqr)
sqrfib
names = ["Alice","Elsa","Harry","Alex"]
for name in names:
print(name.upper())
person = {"name":"Alice","email":"alice@example.com","website":"http://alice.example.com"}
for key in person:
print(key)
for key in person:
print(person[key])
for key in person:
print(key, person[key])
for char in "just for checking for loops over string":
print(char, end=",")
for color in (256,256,0):
print(color)
for i in range(10):
print(i, end=",")
for p in [2,3,5,7,11,13]:
print(p, end=",")
for item in set("just for checking for loops over sets"):
print(item, end=",")
problems
python ls.py .
day1.ipynb
day1.html
module.py
module1.py
product which finds proudct of all items from given collection of numbers.factorial which computes factorial of given numberlist(range(5))
list(range(2,6))
n= 5
list(range(1,n+1))
%%file ls.py
import sys
import os
def ls(dirpath):
files = os.listdir(dirpath)
for file in files:
print(file)
if __name__=="__main__":
if len(sys.argv)==1:
ls(os.getcwd())
else:
ls(sys.argv[1])
!python ls.py
!python ls.py /tmp
def product(numbers):
p = 1
for n in numbers:
p *= n
return p
def factorial(n):
return product(range(1,n+1))
product([3,4,5,6])
factorial(5)
def print_primes(n):
"""
print all primes less than or equal to n
"""
for i in range(1,n+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i,end=",")
print_primes(20)
def squares(numbers):
sqrs = []
for n in numbers:
sqrs.append(n*n)
return sqrs
def evens(numbers):
def even(x):
return x%2==0
e = []
for n in numbers:
if even(n):
e.append(n)
return e
squares([2,3,4,5])
evens(range(10))
fibs
fibs[:2] # take first two
fibs[2:] # drop first two
fibs[2:5] # start at 2nd index end at 5th index(excluding)
fibs[1:6:2] ## start at 1st index end at 6th index(excluding) at step of 2
fibs[:]
fibs[:-1] #drop last one
fibs[:-2] # drop last two
fibs[::-1]
def is_palindrom(word):
return word == word[::-1]
is_palindrom("madam")
is_palindrom("hello")
problems
split_at which splits given list in two parts breaking original list at given indexdef split_at(items, n):
return items[:n],items[n:]
split_at(list(range(10)), 3)
problem
find_extension to find extension of given file.
>>> find_extension("xyz.tar.gz")
"gz"
s = "do geese see god"
s[100]
s[:100]
[i*i for i in range(7)]
[i*i*i for i in range(7)]
[w.upper() for w in names]
[i for i in range(7)]
[i for i in range(7) if i%2==0]
[i for i in range(1,6)]
t = [[i*j for i in range(1,6)] for j in range(1,11)]
t
t[0]
t[-1]
t[0][-1] # last item from 0th row
problems
>>> listpy(os.getcwd())
['module.py','module1.py','add.py']
factors which finds all factors of given number.
>>> factors(5)
[1,5]
>>> factors(6)
[1,2,3,6]
is_prime which determines if given number is prime or not.def listpy(path):
return [f for f in os.listdir(path) if f.endswith(".py")]
import os
listpy(os.getcwd())
def factors(n):
return [i for i in range(1,n+1) if n%i==0]
factors(5)
def is_prime(n):
return factors(n)==[1,n]
def primes(n):
return [p for p in range(1,n+1) if is_prime(p)]
primes(20)
problem
[[i*j for i in range(5)] for j in range(5)]
[[i==j for i in range(5)] for j in range(5)]
[[int(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)]
[[{True:1,False:0}[i==j] for i in range(5)] for j in range(5)]
t
t[0]
t[0][0]
t[0][:]
def column(data, n):
rows = len(data)
return [data[i][n] for i in range(rows)]
column(t, 0)
t
column(t, 1)
def transpose(data):
cols = len(data[0])
return [column(data, i) for i in range(cols)]
transpose(t)
def reverse(item):
return item[::-1]
def rotate90clockwise(data):
cols = len(data[0])
return [reverse(column(data, i)) for i in range(cols)]
rotate90clockwise(t)
for i in primes(20):
print(i, end=",")
for i in reversed(primes(20)):
print(i, end=",")
reversedprimes = reversed(primes(20))
for p in reversedprimes:
print(p, end=",")
for p in reversedprimes:
print(p, end=",")
multiline = """
one
two
three
four
five
"""
lines = multiline.strip().split()
lines
for index,line in enumerate(lines):
print(index, line)
for ind,value in enumerate(lines):
print(ind, value)
names = ["Elsa","Elisa","Alex","David"]
surnames = ["Frozen","Hacker","Lion","Beazley"]
for n, s in zip(names, surnames):
print(n,s)
lines1 = [[l,l,l] for l in lines]
lines1
list(enumerate(lines1))
ids = range(len(names))
for id_,n,s in zip(ids,names, surnames):
print(id_, n, s)
for id_,n in zip(ids,names, surnames):
print(id_, n, s)
for id_,n,s,a in zip(ids,names, surnames):
print(id_, n, s)
problem
def vector_add(v1, v2):
return sum(x+y for x,y in zip(v1, v2))
vector_add(range(10),range(10))
problem
[1,23] + [23,45]
[1,2,3] + [3] + [4,5,6]
[1,2,3] + [3]
def quick(items):
if items==[]:
return []
p = items[0]
less = [i for i in items[1:] if i<=p]
more = [i for i in items[1:] if i>p]
return quick(less) + [p] + quick(more)
quick([23,2,12,56,1,2,3,9,1,8,2])
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))
"wizard of {} is {}".format("oz", "python")
"wizard of {1} is {0}".format("python","oz")
"wizard of {wiz} is in {place}".format(wiz="python", place="oz")
for i in range(1,11):
print("{num:2d} {sqr:3d} {cube:4d}".format(num=i,sqr=i*i,cube=i**3))
problem
pascal which generates pascal triangle as list of list as shon below. the triangle shown below should be generated as a list [[1],[1,1],[1,2,1]]
1
1 1
1 2 1
def pascal(base):
t = [[1]]
for i in range(base-1):
prevbase = t[-1]
pre = [0] + prevbase
post = prevbase + [0]
newbase = [x+y for x,y in zip(pre, post)]
t.append(newbase)
return t
def pascal_(base):
t = [[1]]
for i in range(base-1):
prevbase = t[-1]
baseln = len(prevbase)
newbase = [1] + [prevbase[i]+prevbase[i+1] for i in range(baseln-1)] + [1]
t.append(newbase)
return t
pascal(5)
pascal_(5)
def print_pascal(t):
def formatrow(row):
s = ""
for item in row:
s = s + "{item:{maxdigits}d}".format(item=item, maxdigits=maxdigits+1)
return s
maxdigits = len(str(max(t[-1])))
basesize = len(t[-1])
maxwidth = basesize*maxdigits + basesize -1
for row in t:
strrow = formatrow(row)
print(strrow.center(maxwidth))
print_pascal(pascal(16))
%matplotlib inline
import matplotlib.pyplot as plt
def imshow(img):
plt.imshow(img,cmap=plt.cm.gray)
plt.show()
imshow(t)
imshow(transpose(t))
imshow(rotate90clockwise(t))
%%file functions.py
def square(x):
"""
>>> square(-1)
1
>>> square(1)
1
"""
return x*x
def sumofsquares(x,y):
"""
>>> sumofsquares(2,3)
13
>>> sumofsquares(-1,-1)
2
"""
return square(x) + square(y)
def add(x,y):
"""
>>> add(1,2)
1
"""
return x+y
!python -m doctest -v functions.py
%%file functions.py
def square(x):
"""
>>> square(-1)
1
>>> square(1)
1
"""
return x*x
def sumofsquares(x,y):
"""
>>> sumofsquares(2,3)
13
>>> sumofsquares(-1,-1)
2
"""
return square(x) + square(y)
def add(x,y):
"""
>>> add(1,2)
1
"""
return x+y
def test_square():
assert square(-1) == 1
assert square(2)== 4
assert square(4) == 15
def test_sumofsquares():
assert sumofsquares(2,3)==13
assert sumofsquares(-1,-1)==2
def hello_test():
assert 1 == 2
def test123():
assert 2==3
def testsum():
print(sum(range(10)))
!py.test -v functions.py
To install pytest use following command
pip3 install pytest
import this
%%file data.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!
f = open("data.txt")
f.read()
f.read()
f.close()
f = open("data.txt")
f.readline()
f.readline()
f.readline()
f = open("data.txt")
line = f.readline()
while line:
print(line, end="")
line = f.readline()
f = open("data.txt")
lines = f.readlines()
lines
for line in open("data.txt"):
print(line, end="")
list(open("data.txt"))