Jan 29-31, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-pune-jan-python
© Pipal Academy LLP
for i in range(10):
print(i, end=",")
def print_primes(n):
"""
print primes less than n
"""
for i in range(2,n):
for j in range(2,i):
if i%j==0:
break
else:
print(i, end=",")
print_primes(20)
for i in range(1,20):
flag = True
for j in range(2,i):
if i%j==0:
flag = False
break
if flag:
print(i, end=",")
list(range(2,1))
list(range(10)) #starts at 0 and ends at 9 at step of 1
list(range(2,10)) #starts at 2 ends at 9 at step of 1
list(range(1,10,2)) # starts at 1 ends at 9 at step of 2
def print_fibonacci(n):
"""
prints fibonnaci numbers less than n
"""
prev, current = 1, 1
while current < n:
print(current, end=",")
prev, current = current, prev+current
problem
def is_prime(n):
for j in range(2,n):
if n%j==0:
return False
return True
def print_prime_fibonacci(n):
"""
prints fibonnaci numbers less than n
"""
prev, current = 1, 1
while current < n:
if is_prime(current):
print(current, end=",")
prev, current = current, prev+current
print_prime_fibonacci(100)
digits = list(range(10))
digits
digits.append(10)
digits.insert(0, -1)
digits.pop()
digits.pop(0)
empty = []
digits[0]
digits
twice = []
for number in digits:
twice.append(2*number)
twice
problems
squarelist which returns a new list which is square of every item of original list evens which returns only even numbers from given listsdef squarelist(items):
squares = []
for item in items:
squares.append(item**2)
return squares
def evens(items):
def even(n):
return n%2==0
e = []
for item in items:
if even(item):
e.append(item)
return e
squarelist(digits)
evens(digits)
p = []
for item in seq:
newitem = do_some_processing(item)
p.append(newitem)
[do_some_processing(item) for item in seq]
[item for item in seq if condition(item)]
[do_some_processing(item) for item in seq if condition(item)]
[x*x for x in digits]
def cube(x):
return x*x*x
[cube(item) for item in digits]
[cube(item) for item in digits if item%2==0]
problems
factors which finds all factors of given number (include 1 and self)is_prime which checks if given number is prime based on fact that prime number has only two factors 1 and self.bonus problem
def say_hello(name):
return "hello " + name
persons = ["kavya","kavita","kavi","krishna"]
[say_hello(p) for p in persons if p.endswith("i")]
[p for p in persons if p.endswith("a")]
import os
def listpy(path):
return [file for file in os.listdir(path) if file.endswith(".py")]
listpy(os.getcwd())
def factors(n):
return [i for i in range(1,n+1) if n%i==0]
factors(5)
factors(25)
def is_prime(n):
return factors(n)==[1,n]
is_prime(5)
[p for p in range(50) if is_prime(p)]
t = [[i*j for i in range(1,10)] for j in range(1,6)]
t
t[0]
t[-1]
problem
def equal(x,y):
if x==y:
return 1
else:
return 0
[[equal(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)]
[[{True:1,False:0}[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])
t
t[0] # 0th row
t[0][0] # 0th row , 0th col
rowcount = len(t)
[t[i][0] for i in range(rowcount)] # 0th column
def column(data, n):
rowcount = len(data)
return [data[i][n] for i in range(rowcount)]
column(t, 0)
column(t, 1)
t
def transpose(data):
columncount = len(data[0])
return [column(data, i) for i in range(columncount)]
transpose(t)
t
problem
list(range(10))
[i for i in range(10)]
[10-i for i in range(10)]
list(range(0,10,-1))
def reverse(seq):
n = len(seq)
return [seq[n-i-1] for i in range(n)]
def rotateclockwise(data):
colcount = len(data[0])
return [reverse(column(data, i)) for i in range(colcount)]
list(range(10,-1,-1))
rotateclockwise(t)
t
def rotateanticlockwise(data):
colcount = len(data[0])
return [column(data, i) for i in range(colcount-1, -1, -1)]
rotateanticlockwise(t)
[reverse(column(t,i)) for i in range(len(t[0]))]
Quicksort
[3,6,1,2,8,9]
p = 3 less = [1,2] greater = [6,8,9]
quick(less) + [p] + quick(greater)
def quick(items):
if not items:
return []
pivot = items[0]
less_ = [i for i in items[1:] if i < pivot]
greater_ = [i for i in items[1:] if i >= pivot]
return quick(less_) + [pivot] + quick(greater_)
quick([2,3,4,1,1,2,37,1,2,1])
import matplotlib.pyplot as plt
%matplotlib inline
def imshow(img):
plt.imshow(img, cmap=plt.cm.gray)
plt.show()
imshow(t)
imshow(rotateanticlockwise(t))
imshow(rotateclockwise(t))
problem
def rearrangemax(n):
strn = str(n)
return int("".join(sorted(strn, reverse=True)))
def rearrangemin(n):
strn = str(n)
return int("".join(sorted(strn)))
def kaprekar(n, iters=50):
for i in range(iters):
min_ = rearrangemin(n)
max_ = rearrangemax(n)
n = max_ - min_
return n
kaprekar(2345)
slicing works on lists, string, tuples
digits = list(range(10))
digits
digits[2:5:1] # start at 2nd index , end at 5th index(excluding) at interval of 1
digits
digits[:5] #first five
digits[5:] # drop frist five
digits[:] # copy
digits[:-1] # all except last.. drop last one
digits[:-3]# drop last 3
digits[::-1] # reverse
word = "madam"
f = lambda x: x*x
f(3)
is_palindrom = lambda w: w==w[::-1]
is_palindrom(word)
even = lambda x : x%2==0
even(4)
odd = lambda x: not even(x)
odd(3)
problem
split_at which splits given list in two lists at given indexfind_extension to find extension of given file.def pair(x,y):
return 2*x, 2*y # function can return multiple values
pair(1,2)
add = lambda x,y:x+y # lambda can take multiple parameters
add(2,3)
f = lambda x: (x,x**2,x**3)
f(2)
def split_at(seq, index):
return seq[:n],seq[n:]
def find_extension(filename):
return filename.split(".")[-1]
"hello.tar.gz".split(".")
s = "do gees see god"
s[100]
s[:100]
for n in digits:
print(n, end=",")
for n in reversed(digits):
print(n, end=",")
r = reversed(digits)
for i in r:
print(i, end=",")
for i in r:
print(i, end=",")
r = list(reversed(digits))
r
range(10)
for index, item in enumerate(r):
print(index, item)
r = range(5)
for i in r:
print(i)
for i in r:
print(i)
r
digits = [1,2,3,4,5]
letter = ["A","B","C","D","E"]
for d,l in zip(digits, letter):
print(d, l)
digits = [1,2,3]
letter = ["A","B","C","D","E"]
list(zip([1,2],['a','b'],['x','y']))
for d,l in zip(digits, letter):
print(d, l)
problem
bonus problem
zip_with which zips two lists with given operation?def vector_add(vector1, vector2):
return [x+y for x,y in zip(vector1, vector2)]
def zip_with(f, v1, v2):
return [f(x,y) for x,y in zip(v1, v2)]
vector_add(range(5), range(5))
zip_with(lambda x,y:x+y, range(5), range(5))
zip_with(lambda x,y:x*y, range(5), range(5))
%%file functions.py
def eval_poly(coeffs, x):
s = 0
n = len(coeffs)-1
for i, c in enumerate(coeffs):
s += c* x**(n-i)
return s
def eval_poly1(coeffs, x):
s = 0
for i,c in enumerate(reversed(coeffs)):
s += c*x**i
return s
def test_poly():
### [1,1,1] => x^2 + x + 1
coeffs = [1,1,1]
assert eval_poly(coeffs, 0)==1
assert eval_poly(coeffs, 1)==3
assert eval_poly([1,0,1], 2)==5
!py.test -v functions.py
0**1
0**0
for i in range(1,11):
print(i, i**2, i**3)
for i in range(1,11):
print(str(i).rjust(2), str(i**2).rjust(3), str(i**3).rjust(4))
"wizard of {} is {}".format("oz","python")
"wizard of {1} is {0}".format("oz","python")
"purpose of life is {answer}, my computation in {who} says so!".format(answer=42, who="python")
for i in range(1,11):
print("{num:2d} {sqr:3d} {cube:4d}".format(num=i, sqr=i*i, cube=i**3))
"{num:{digits}d}".format(num=200,digits=3)
problem
1
1 1
1 2 1
1 3 3 1
[[1],[1,1],[1,2,1],[1,3,3,1]
```
"hello".center(50)
"hello".ljust(10)
"23".zfill(10)
base = [1,2,1]
[1] + [base[i]+base[i+1] for i in range(len(base)-1)] + [1]
def pascal(n):
t = [[1]]
for i in range(1,n):
base = t[-1]
pre = [0] + base
post = base + [0]
newbase = [x+y for x,y in zip(pre,post)]
t.append(newbase)
return t
pascal(4)
def pascal(n):
t = [[1]]
for i in range(1,n):
base = t[-1]
newbase = [1] + [base[i]+base[i+1] for i in range(len(base)-1)] + [1]
t.append(newbase)
return t
pascal(4)
def print_pascal(t):
def format_row(row):
s = ""
for n in row:
s += "{num:{digits}d} ".format(num=n, digits=maxdigits)
return s
maxdigits = len(str(max(t[-1])))
basesize = len(t[-1])
width = maxdigits*basesize + basesize-1
for row in t:
r = format_row(row)
print(r.center(width))
trianlge = pascal(12)
print_pascal(trianlge)
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!
filehandle = open("data.txt")
filehandle.read()
filehandle.read()
filehandle.close()
f = open("data.txt")
f.readline() #read only one line ...line is by default appended with \n
f.readline()
f.readline()
line = f.readline()
while line:
line = f.readline()
print(line, end="")
f = open("data.txt")
f.readline()
f.readline() ##this is empty line...
line = f.readline()
while line:
line = f.readline()
print(line)
f = open("data.txt")
for line in f.readlines():
print(line, end="")
f = open("data.txt")
for index,line in enumerate(f.readlines()):
print(index+1 , line, end="")
for line in open("data.txt"):
print(line, end="")
problem
cat approximately.head approximately.wc%%file cat.py
import sys
def cat(file):
print(open(file).read())
if __name__=="__main__":
for file in sys.argv[1:]:
cat(file)
!python cat.py hello.py functions.py data.txt
%%file head.py
import sys
def head(filename, n):
f = open(filename)
for i in range(n):
print(f.readline(),end="")
if __name__ == "__main__":
head(sys.argv[2], int(sys.argv[1]))
!python head.py 5 data.txt
%%file wc.py
import sys
def count_words(file):
return len(open(file).read().split())
def count_chars(file):
return len(open(file).read())
def count_lines(file):
return len(open(file).readlines())
if __name__ == "__main__":
file = sys.argv[1]
print(count_lines(file), count_words(file), count_chars(file), file)
!python wc.py data.txt
problem
!python wc.py day1.html
!python wc.py day1.ipynb
!python wc.py day2.html
import os
[filename for filename in os.listdir(os.getcwd()) if os.path.isfile(filename)]
files = [f for f in os.listdir(os.getcwd()) if os.path.isfile(f)]
import wc
max(files, key=wc.count_lines)
max(files, key=wc.count_words)
def add(x,y):
return x+y
def debug_add(x,y):
print("before add", x, y)
r = add(x,y)
print("after add", r)
return r
def debug(f, *args):
print("before ", f, *args)
r = f(*args)
print("after ",f, r)
return r
debug(add, 2,3)
def debug(f):
def wrapper(*args):
print("before ", f, *args)
r = f(*args)
print("after ",f, r)
return r
return wrapper
add = debug(add)
add(2,3)