Jan 17-19, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-jan-python
© Pipal Academy LLP
problem
filetype which will tell us type of file , given file name. it shoould support following file types.
filetype extension
java .java
text .txt
python .py
haskell .hs
lisp .lsp
configuration .conf
>>> filetype("Quicksort.py")
"python"
>>> filetype("QuickSort.java")
"java"
def filetype(filename):
if filename.lower().endswith(".java"):
return "java"
elif filename.lower().endswith(".txt"):
return "text"
elif filename.lower().endswith(".py"):
return "python"
elif filename.lower().endswith(".hs"):
return "haskell"
elif filename.lower().endswith(".lsp"):
return "lisp"
else:
return None
def minimum(x,y):
if x<y:
return x
else:
return y
def minimum3(x,y,z):
min1 = minimum(x,y)
return minimum3(min1, z)
def print_fib(n):
"""
prints fibonacci numbers less than n
"""
prev, current = 1,1
while prev<n:
print(prev, end=",")
prev, current = current, prev+current
print_fib(50)
numbers = [1,1,2,3,5,8,13,21,34]
for number in numbers:
print(number)
for c in "This statement is random string for testing for loops":
print(c, end=",")
persons ={"Anand":"C", "Alex":"Beaz","David":"Beazly"}
for name in persons:
print(name, persons[name])
problem
python ls.py
add.py
day2.ipynb
hello1.py
module1.py
push
mysum which sums up all elements from a list (using loops!)
mysum([1,1,1,1,1])
5
product which finds product all numbers from given list
product([1,2,3,3])
18
factorial(4)
24
%%file ls.py
import os
import sys
def listfiles(dirname):
files = os.listdir(dirname)
for file in files:
print(file)
if __name__ == "__main__":
if len(sys.argv)>1:
listfiles(sys.argv[1])
else:
listfiles(os.getcwd())
!python ls.py
!python ls.py /tmp/
def mysum(numbers):
s = 0
for n in numbers:
s += n
return s
mysum([1,1,1,1,1])
def product(numbers):
p = 1
for n in numbers:
p *= n
return p
product([1,2,3,4])
def factorial(n):
return product(range(1,n+1))
factorial(5)
for i in range(1,10):
print(i,end=" ")
add = lambda x,y: x+y
add(2,3)
factorial = lambda n: product(range(1,n+1))
factorial(10)
factorial(5)
def print_primes(n):
"""
prints prime numbers 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(50)
primes = [2,3,5,7,11,13,17,19,23,29,31,37]
primes.append(41)
primes.insert(0, 1)
primes.pop(0)
problem
def square(numbers):
squares = []
for n in numbers:
squares.append(n*n)
return squares
square(primes)
square([1,2,3,4])
square(range(1,11))
mysum(square(range(1,11)))
def evens(numbers):
e = []
for n in numbers:
if n%2 ==0:
e.append(n)
return e
evens(range(1,20))
primes
primes[2:7:2] # start at index 2 , end at 7 (excluding) at step of 2
primes[2:7] # start at 2 , and at 7 at step of 1
primes[:2] # take first 2
primes[2:] # drop first two
primes[-1]
primes[:-1] # all items except last
primes[:-2]
primes[:-5]
primes[:] # just a copy
primes[::-1]
word = "madam"
is_palindrome = lambda word : word==word[::-1]
is_palindrome(word)
is_palindrome("121")
problems
split_at which splits given list in two lists at given indexfind_extension which finds extension of a files = "do geese see god"
s[100]
s[3:100]
def split_at(items, index):
return items[:index], items[index:]
book = "Alice in wonderland"
book.split(" ")
path = "/usr/local/lib/python3/"
path.split("/")
filenane = "anaconda.tar.gz"
tokens = filenane.split(".")
tokens.pop()
tokens
filenane.split(".")[-1]
def find_extension(filename):
return filename.split(".").pop()
find_extension = lambda f: f.split(".").pop()
find_extension("day1.ipynb")
s = "do geese see god"
len(s)
s[3:100]
for p in primes:
#do something(p)
pass
[p*p for p in primes]
[2*p for p in primes]
squares = [i*i for i in range(1,11)]
squares
[factorial(i) for i in range(1,11)]
[word.upper() for word in "Let me create some words from this statement".split()]
[i for i in range(10)]
[i for i in range(10) if i%2 ==0]
words = "Let me create some words from this statement".split()
[word.upper() for word in words]
[word.upper() for word in words if word.startswith("s")]
import os
[[i*j for i in range(1,6)] for j in range(1,11)]
tables = []
for j in range(1,11):
e = []
for i in range(1,6):
e.append(i*j)
tables.append(e)
tables
problems
listpy which lists only python files from given directory.factors which finds factors of given number, include 1 and self also.is_prime which determines if given number is prime or notprimes which generates prime numbers less than given numberimport os
def listpy(directory):
files = os.listdir(directory)
return [file for file in files if file.endswith(".py")]
listpy(os.getcwd())
def factors(n):
return [f for f in range(1,n+1) if n%f==0]
factors(10)
factors(7)
def is_prime(n):
return factors(n)==[1,n]
def is_prime(n):
return len(factors(n))==2
primes = lambda n: [p for p in range(1,n) if is_prime(p)]
primes(50)
bonus problems
[i for i in range(5)]
[[i for i in range(5)] for j in range(5)]
[[i+j for i in range(5)] for j in range(5)]
def f(x,y):
return x+y
[[ f(i,j) for i in range(5)] for j in range(5)]
def diagonal(x,y):
if x==y:
return 1
else:
return 0
[[ diagonal(i,j) for i in range(5)] for j in range(5)]
data = [[i*j for i in range(5)] for j in range(5)]
for i in range(5):
data[i][0] = i
data
data[0]
data[0][0]
numrows = 5
[data[i][0] for i in range(numrows)]
data
[data[i][2] for i in range(numrows)]
def column(data, colnum):
rowcount = len(data)
return [data[i][colnum] for i in range(rowcount)]
column(data,0)
colcount = len(data[0])
[column(data,i) for i in range(colcount)]
def transpose(data):
columncount = len(data[0])
return [column(data, i) for i in range(columncount)]
transpose(data)
data
sum([i for i in range(1000) if i%7==0 or i%11==0])
data
row = list(range(5))
row
[i for i in row]
[row[i] for i in range(len(row))]
l = len(row)
[row[l-i-1] for i in range(l)]
for i in range(5):
print(i)
for i in reversed(range(5)):
print(i)
for c in reversed("some string"):
print(c,end=",")
lines = """
one
two
three
four
five
"""
lines = lines.strip().split("\n")
lines
for index,line in enumerate(lines):
print(index, line)
s = " hello "
s.strip()
first = ["Elsa", "Alisa","Beauty"]
last = ["Frozen","Hacker","Nurd"]
for name, surname in zip(first, last):
print(name, surname)
zipped = zip([1,2,3,4],["one","two","three","four"])
zipped
list(zipped)
zipped = zip([1,2,3,4],["one","two","three","four"])
for item1, item2 in zipped:
print(item1, item2)
def vectoradd(v1, v2):
return [i+j for i,j in zip(v1,v2)]
vectoradd(range(4),range(4))
%%file functions.py
"""
implements few basic function with its test cases
"""
def add(x,y):
"""
this function adds two numbers
>>> add(0,1)
1
>>> add(-1,1)
0
"""
return x+y
def square(x):
"""
>>> square(-1)
1
>>> square(2)
4
"""
return x*x
def mult(x,y):
"""
>>> mult(1,2)
2
"""
return x+y
!python -m doctest functions.py
!pydoc functions
%%file functions.py
"""
implements few basic function with its test cases
"""
def add(x,y):
"""
this function adds two numbers
>>> add(0,1)
1
>>> add(-1,1)
0
"""
return x+y
def square(x):
"""
>>> square(-1)
1
>>> square(2)
4
"""
return x*x
def mult(x,y):
"""
>>> mult(1,2)
2
"""
return x+y
def test_add():
if add(1,-1)==0:
print("passed")
if add(0,1)==1:
print("passed")
def test_add1():
assert add(1,-1) == 0
assert add(1,0) == 1
def test_square():
assert square(-1) == 1
!py.test -v functions.py
if you don't have pytest on your machine you can install it using
pip3 install pytest
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))
name = "Alice"
name.ljust(10)
name.rjust(10)
name.center(10)
"wizard of oz is {}".format("python")
"wizard of {} is in {}".format("python", "oz")
"wizard of {1} is in {0}".format("oz", "python")
"purpose of life is {0}, my computation in {1} says so!".format(42, "python")
for i in range(1,11):
print("{0:2d} {1:3d} {2:4d}".format(i, i*i, i*i*i))
for i in range(1,11):
print("{integer:2d} {square:3d} {cube:4d}".format(integer=i, square=i*i, cube=i**3))
"12".zfill(5)
problem
pascal to generate pascal triangle of base n.>>> pascal(3)
[[1],[1,1],[1,2,1]]
print_pascal to prety print pascal tringle.
>>> t = pascal(5)
>>> print_pascal(t)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
def pascal(n):
triangle = [[1]]
for i in range(1,n):
lastrow = triangle[-1]
pre = [0] + lastrow
post = lastrow + [0]
newrow = [i+j for i,j in zip(pre, post)]
triangle.append(newrow)
return triangle
pascal(3)
pascal(6)
def print_pascal(triangle):
def formatrow(row):
s = ""
for item in row:
s += ("{item:{digits}d} ".format(item=item, digits=maxdigits))
return s
lastrow = triangle[-1]
maxnum = max(lastrow)
maxdigits = len(str(maxnum))
width = len(lastrow)*maxdigits + len(lastrow)-1
for row in triangle:
print(formatrow(row).center(width))
t = pascal(6)
print_pascal(t)
print_pascal(pascal(12))