Oct 25-27, 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/arcesium-oct-python/day2.html
© Pipal Academy LLP
def print_fibonacci(n):
"""
print fibonacci numbers less than using while loop
"""
prev, current = 1, 1
while current < n:
prev, current = current, prev + current
print(prev, end=",")
print_fibonacci(1000)
for loops in python are different as compared c/java. for loop in python gives you handle to iterate over collection
names = ["Elsa", "David", "Mahesh", "Hari"]
for person in names:
print("hello", person)
for f in [1,2,3,5,8,13,21,34,55,89,144,233,377,610,987]:
print(f, end=",")
for c in "This is a sentence to demo for loop":
print(c, end=",")
for word in "This sentence is to demo words in for loop".split():
print(word, end=",")
range(5)
for num in range(5):
print(num, end=",")
for num in range(2, 10, 2): #range(start, end, step)
print(num, end=",")
problem
ls.py to list files in current directory.
python ls.py
day1.html
.
.
mysum that sums up elements from a list>>> mysum([1,1,1,1])
4
product that computes product of all numbers from a list
>>> product([1,2,3,4])
24
%%file ls.py
import os
def ls(location):
for file in os.listdir(location):
print(file)
if __name__ == "__main__":
ls(os.getcwd())
!python ls.py
from ls import ls
ls(".")
def mysum(numbers):
s = 0
for num in numbers:
s += num
return s
def product(numbers):
p = 1
for num in numbers:
p = p *num
return p
def factorial(n):
return product(range(1,n+1))
mysum(range(10))
factorial(4)
There is break statement, which stops at current iteration and breaks from loop. There is also optional else block for for loop which is to be used with break statement.
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(100)
list(range(2,2))
list(range(2,3))
list(range(2,4))
def prime_fibonacci(n):
"""
prints fibonacci less than n but are also prime
"""
prev, current = 1, 2
while prev < n:
for i in range(2, prev):
if prev%i==0:
break
else:
print(prev, end=",")
prev, current = current, prev+current
prime_fibonacci(50)
numbers = list(range(10))
numbers
numbers.append(11)
numbers
numbers.insert(0, -1)
numbers
numbers.pop()
numbers.pop(0)
emptylist = []
problem
square which takes a list of numbers as argument and returns a new list with squared numbers
>>> square([1,2,3.4])
[1,4,9,16]
evens to find out even numbers from a given list
>>> evens([1,2,3,4,5,6,7])
[2,4,6]
def square(numbers):
s = []
for num in numbers:
s.append(num*num)
return s
def evens(numbers):
def even(n):
return not n%2
e = []
for num in numbers:
if even(num):
e.append(num)
return e
evens(range(10))
digits = list(range(10))
digits
digits[1:6] #new list from index 1(included) to index 6(exluded)
digits[2:5]
digits[1:]#list containing itesm from index 1 till end
digits[:4] #from start till index 4(exlcuded)
digits[4:] #from index 4 till end
digits[-1]
digits[:-1] # all elements except last
digits[:] # all ..copy
digits[2:7:2]
digits[::-1] # reverse
word = "madam"
word == word[::-1]
is_palindrom = lambda word: word==word[::-1]
is_palindrom
is_palindrom("civic")
problems
split_at which splits given list in two lists. First list is items from start till the index and second list is items from index till end of list.
>>> split_at([0,1,2,3,4,5,6,7,8], 2)
([0,1], [2,3,4,5,6,7,8])
find_extension to find extension of a file, given file name.
>>> find_extension("python.exe")
exe
>>> s = "Do geese see God?"
>>> s[100]
>>> s[3:100]
def split_at(items, index):
return intems[:index], items[index:]
def find_extension(filename):
return filename.split(".")[-1]
s = "Do geese see God?"
s[100]
s[3:100]
sq = []
for n in [1,2,3,4]:
sq.append(n*n)
print(sq)
numbers = range(10)
print(numbers)
nums = [n for n in numbers]
nums
squares = [n*n for n in numbers]
[n*n*n for n in numbers]
[factorial(n) for n in numbers]
[word.upper() for word in ["these", "are", "few", "words"]]
words = ["Some", "sentence", "that", "contains", "some", "s"]
[word for word in words if word.lower().startswith("s")]
[i for i in range(20) if i%2==0]
problems
>>> listpy(os.getcwd())
['add.py', 'module.py', 'main.py'...]
>>> factors(10)
[1,2,,5,10]
is_prime which determines if given number is prime or not
>>> is_prime(23)
True
>>> primes(23)
[2,3,5,7,11,13,19,23]
import os
def listpy(dirpath):
files = os.listdir(dirpath)
return [file for file in files if file.endswith(".py")]
def factors(n):
return [i for i in range(1, n+1) if n%i ==0]
is_prime = lambda n: factors(n)==[1,n]
def primes(n):
return [p for p in range(2,n+1) if is_prime(p)]
listpy(os.getcwd())
factors(13)
is_prime(13)
primes(50)
[[i*j for i in range(1,11)] for j in range(1, 6)]
Can you generate unit matrix of dimension 5x5 which has only diagonal element as 1 , other lements are 0..using list comprehension
def f(x,y):
if x==y:
return 1
else:
return 0
[[f(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)]
x = 2
y = 3
a = 5 if x==y else 4
a
Iterating over a list/string/sequence
for prime in primes(23):
print(prime, end=",")
for prime in reversed(primes(23)):
print(prime, end=",")
countdown = reversed(list(range(10)))
countdown
Iterating with index and item
primenums = primes(23)
for i, item in enumerate(primenums):
print(i, item)
iterating over two lists together
names = ["Elsa", "Alisa", "Exotica", "Beauty"]
surnames = ["Frozen", "Hacker", "Logica", "Nurd"]
for name, surname in zip(names, surnames):
print(name, surname)
problems
>>> vector_add([1,2,3],[3,2,1])
[4,4,4]
>>> zip3([1,2,3],["one","two","three"],['x','y','z'])
[(1,"one",'x'), (2,"two","y"), (3,"three", "z")]
def vector_add(vector1, vector2):
return [x+y for x,y in zip(vector1, vector2)]
def zip3(first, second, third):
return [(first[i],second[i],third[i]) for i in range(len(first))]
vector_add([1,1,1],[2,2,2])
zip3([1,2,3],["one","two","three"],['x','y','z'])
def usual_way_polynomial(coeffs, x):
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
usual_way_polynomial([1,1,1], 2)
def make_polynomial(coeffs):
def poly(x):
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
return poly
P2 = make_polynomial([1,1,1])
P2
P2(2)
problem
compose which takes two functions f and g as argument and return a fucntion which will compute f(g(x))
>>> f = lambda x: x**2
>>> g = lambda x: x-1
>>> fg = compose(f,g)
>>> fg(3) ## (3-1)**2
4
>>> gf = compose(g,f)
>>> gf(3) # (3**2)-1
8
zip_with which takes function as argument, two lists as argument and returns a single list which is formed by combining items from two lists using given functiondef compose(f,g):
return lambda x: f(g(x))
def zip_with(f):
return lambda first, second: [f(x,y) for x,y in zip(first, second)]
vector_adder = zip_with(lambda x,y: x+y)
vector_adder([1,1,1],[2,2,2])
vector_multiplier = zip_with(lambda x,y: x*y)
vector_multiplier([1,1,1],[2,2,2])
%%file functions.py
"""
module functions
this serves as long description of module functions
"""
def usual_way_polynomial(coeffs, x):
"""
computes values of polynomial given coefficients and x
>>> usual_way_polynomial([1,1,1], 2)
7
"""
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
def make_polynomial(coeffs):
"""
makes a polynomial function given coefficients. the returned function can be used
to compute value of polynomial if x is given
>>> make_polynomial([1,1,1])(2)
7
"""
def poly(x):
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
return poly
!pydoc functions
import functions
help(functions)
!python -m doctest -v functions.py
py.test is a third party tool for doing testing. to install it use following command
pip3 install pytest
from functions import usual_way_polynomial, make_polynomial
if usual_way_polynomial([1,1,1],2) == 7:
print("pass")
assert usual_way_polynomial([1,1,1],2) == 1
def test_polynomial():
assert usual_way_polynomial([],2) == 0
assert usual_way_polynomial([1,1,1],1) == 3
%%file function1.py
"""
module functions
this serves as long description of module functions
"""
def usual_way_polynomial(coeffs, x):
"""
computes values of polynomial given coefficients and x
>>> usual_way_polynomial([1,1,1], 2)
7
"""
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
def make_polynomial(coeffs):
"""
makes a polynomial function given coefficients. the returned function can be used
to compute value of polynomial if x is given
>>> make_polynomial([1,1,1])(2)
7
"""
def poly(x):
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
return poly
def test_usual():
assert usual_way_polynomial([1,1,1],0) == 1
assert usual_way_polynomial([1,1,1], 2) == 7
assert usual_way_polynomial([],0) == 0
assert usual_way_polynomial([],2) == 3
def test_make_poly():
coeff0 = []
poly0 = make_polynomial(coeff0)
assert poly0(1) == usual_way_polynomial(coeff0, 1)
coeff2 = [1,1,1]
poly2 = make_polynomial(coeff2)
assert poly2(2) == 5
!py.test function1.py
for i in range(1,11):
print(i, i**2, i**3)
for i in range(1,11):
print(repr(i).rjust(2), repr(i*i).rjust(3), repr(i*i*i).rjust(4))
"Wizard of oz is {}".format("python")
"wizard of {} is in {}".format("python", "oz")
"purpose of life is {0} , my computation in {1} says so".format(42, "python")
for i in range(1,11):
line = "{integer:2d} {square:3d} {cube:4d}".format(integer=i, square=i**2, cube=i**3)
print(line)
"12".zfill(4)
"12.24".zfill(8)
"{0:.4f} {1:.2f}".format(3.14, 1.3)
problem
pascal to generate pascal triangle of base n
>>> pascal(3)
[[1],[1,1],[1,2,1]]
>>> print_pascal(5)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
def pascal(base):
triangle = [[1]]
for i in range(base-1):
prev = triangle[-1]
pre = prev[:]
pre.insert(0, 0)
post = prev[:]
post.append(0)
row = [x+y for x,y in zip(pre, post)]
triangle.append(row)
return triangle
pascal(3)
pascal(5)
pascal(6)
def print_pascal(base):
def count_digits(n):
return len(str(n))
triangle = pascal(base)
d = count_digits(max(triangle[-1]))#digits in biggest number
width = d*base + base-1 #total width of triangle including spaces
for row in triangle:
line = ""
for number in row:
line += "{number:{spaces}} ".format(number=number, spaces=d)
line = line.center(width)
print(line)
print_pascal(12)
import this
%%file three.txt
one
two
three
fhandle = open("three.txt")
fhandle.read() #complete contents of file
fhandle.read()
fhandle.close()
%%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!
fhandle = open("data.txt")
fhandle.readline()
fhandle.readline()
fhandle.readlines()
fhandle = open("data.txt")
for line in fhandle.readlines():
print(line, end="")
for i, line in enumerate(open("data.txt")):
print(i+1, line, end="")
for line in open("data.txt"):
print(len(line.strip().split()))
cat.py which is equivalent of unix command cat. it prints contents of file to standard output
python cat.py three.txt
one
two
three
head.py which takes number lines to be shown as first argument and filename as second argument of and prints first n lines of file.python head.py 5 data.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
%%file cat.py
import sys
def cat(file):
for line in open(file):
print(line, end="")
if __name__ == "__main__":
cat(sys.argv[1])
!python cat.py three.txt
%%file head.py
import sys
def head(n, file):
f = open(file)
for i in range(n):
print(f.readline(), end="")
if __name__ == "__main__":
n = int(sys.argv[1])
file = sys.argv[2]
head(n, file)
!python head.py 5 data.txt