Oct 16-18, 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-oct-python
© Pipal Academy LLP
def print_fibonacci(n):
"""
print fibionacci numbers less than n
"""
prev, current = 1, 1
while current < n:
prev, current = current, prev+current
print(prev, end=",")
print_fibonacci(1000)
Lets print first n natural numbers using while loop!
def print_naturals(n):
k = 1
while k <=n:
print(k, end=",")
k += 1
print_naturals(20)
names = ["Elsa", "David", "Mahesh", "Hari"]
for name in names:
print(name)
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 statement is for testing for loop":
print(c, end=",")
what is I want a usual for loop?
for i in range(5):
print(i, end=",")
for i in range(2, 20, 2):
print(i, end=",")
problem:
ls.py to list files in current directorymysum that sums up numbers from given list.
>>> mysum([1,1,1,1])
4
product that computes product of all elements from a list
>>> product([2,3,4])
24
factorial that computes factorial of a given number
>>> factorial(4)
24
Bonus problem:sumdigits to find sum of digits of a given numberreordermax which rearranges digits of a number to from a max number.def product(numbers):
p = 1
for n in numbers:
p = p * n
return p
product([1,2,3])
def factorial(n):
return product(range(1, n+1))
factorial(5)
There is a break statement as well
def print_primes(n):
"""
prints all 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)
problem :
write a function prime_fibinacci to print fibonacci numbers less than n but are prime numbers also
def prime_fibonacci(n):
"""
prints numbers less than n that are prime and fibinacci numbers
"""
prev, current = 2, 3
while prev < n:
for i in range(2, prev): # test primality
if prev%i == 0:
break
else:
print(prev, end=",")
prev, current = current, prev+current # fibinacci computation
prime_fibonacci(100)
range(5)
list(range(5))
numbers = list(range(10))
numbers
numbers.append(11)
numbers
numbers.insert(0, -1)
numbers
numbers.pop(0)
numbers
numbers.index(4)
emptylist = []
problem:
square which squares in a list
>>> square([2,3,4,5]
[4,9,16,25]
Write a function evens to find out even numbers for a list of numbers
>>> evens([1,2,3,4,6,7,8,9])
[2,4,6,8]
Modify above function prime_fibonacci to return a list of primes fibonacci numbers instead of printing
>>> prime_fibonacci(100)
[2,3,5,13,89]
def double(numbers):
d = []
for n in numbers:
d.append(2*n)
return d
double([2,4,5])
digits = list(range(10))
digits
digits[1:6] # new list containing items from index 1(included) till 6(excluded)
digits[1:] #new list containing items from 1 till end
digits[:5] # from start (0) to index 5(excluded)
digits[-1]
digits[:-1] # all items except last
digits[:] # just copy of list
digits[2:7:2] # start from index 2(included) till index 7(excluded) but at interval of 2
digits[::-1] # reverse of list
word = "madam"
word == word[::-1]
is_palindrome = lambda word: word == word[::-1]
is_palindrome
type(is_palindrome)
is_palindrome("civic")
is_palindrome("hello")
square = lambda x: x*x
square(2)
add = lambda x, y: x+y
add(2, 3)
problem :
split_at which takes a list and index (integer) as argument. It splits given list in two lists , first list is left side of index and second list is right side of index
>>> split_at([0,1,2,3,4,5,6,7,8,9], 2)
([0,1], [2,3,4,5,6,7,8,9])
find_extension which finds extension of a file given file name.
>>> find_extension("python.exe")
exe
>>> s = "Do geese see God?"
>>> s[100]
>>> s[3:100]
numbers = range(10)
nums = [n for n in numbers]
nums
squares = [n*n for n in numbers]
squares
cubes = [n**3 for n in numbers]
cubes
[factorial(n) for n in numbers]
Convert all words to upper case?
sentence = "Some sentence with some words"
[word.upper() for word in sentence.split()]
[word.upper() for word in sentence.split() if word.lower().startswith("s")]
[i for i in range(10) if i%2==0]
[[i*j for j in range(1, 11)] for i in range(1, 6)] # generate multiplication tables
problem :
listpy which will list all ".py" files from given directory
>>> listpy(os.getcwd())
['add.py', 'mymodule.py'...]
factors which will return list of factors of given number including 1 and self
>>> factors(10)
[1,2,5,10]
Bonus problem:
is_prime to test primality of given number
>>> is_prime(7)
True
>>> is_prime(4)
False
is_prime function to generate prime numbers up to n using list comprehensionimport 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(7)
def is_prime(n):
return factors(n) == [1,n]
def primes(n):
return [p for p in range(2, n+1) if is_prime(p)]
primes(30)
[[i+j for i in range(5)] for j in range(5)]
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)]
Iterating over a list, string, sequence
for prime in primes(30):
print(prime)
for n in reversed(range(10)):
print(n)
countdown = reversed([1,2,3,4,5])
countdown
for i in countdown:
print(i)
Iterating with index
for i, item in enumerate(primes(23)):
print(i, item)
Iterating with two sequences at a time
names = ["Elsa", "Alisa", "Exotica", "Beauty"]
surnames = ["Frozen", "Hacker", "Logica", "Nurd"]
for name, surname in zip(names, surnames):
print(name, surname)
z = zip(names, surnames)
z
list(z)
problem:
>>> vector_add([1,2,3], [3,2,1])
[4,4,4]
println that takes sentences as list of strings and prints each statement on new line with lines number.
>>> s = ["This is first line", "This is second line", "This is third line", "This is last line"]
>>> println(s)
1 This is first line
2 This is second line
3 This is third line
4 This is last line
Q: what if you pass lists of different size to zip?
list(zip([1,2,3], ['a','b']))
list(zip([1,2,3], ['a','b','c','d']))
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) # computes x^2 + x + 1
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5
adder5(4)
adder5(3)
def make_plynomial(coeffs):
def poly(x):
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c*x**i
return s
return poly
P2 = make_plynomial([1,1,1]) # X^2 + X + 1
P2
P2(2)
P2(3)
problem:
zip_with which will take function f as argument and returns a function which zips two lists with fdef zip_with(f):
def func(list1, list2):
return [f(x,y) for x,y in zip(list1, list2)]
return func
new_vector_add = zip_with(lambda x,y: x+y)
new_vector_add([1,2,3], [3,4,5])
orlist = zip_with(lambda x,y: x or y)
orlist([True, True, False, False], [False, False, False, True])
%%file functions.py
"""
module functions
this module implements some polynomial functions
This is long description of this module
"""
def usual_way_polynomial(coeffs, x):
"""
computes values of polynomial defined by coeffs 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_plynomial(coeffs):
"""
makes polynomial as function given coeffs
>>> make_plynomial([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
!python -m doctest -v functions.py
%%file functions1.py
def add(x, y):
return x+y
def test_add():
if add(3,4) == 7:
print("Pass")
else:
print("Failed")
def test_add1():
assert add(3,4) == 7
assert add(3,4) != 8
assert add(0,0) == 0
assert add(0,0) == 1
if __name__ == "__main__":
test_add()
!python functions1.py
!py.test functions1.py
def squares_and_cubes_table():
for i in range(1,11):
print(i, i*i, i*i*i)
squares_and_cubes_table()
def squares_and_cubes_table():
for i in range(1, 11):
print(repr(i).rjust(2), repr(i*i).rjust(3), repr(i*i*i).rjust(4))
squares_and_cubes_table()
"python".rjust(10)
"python".ljust(10)
"python".center(10)
"Wizard of oz is {}".format("pyhton")
"Wizard of {} is in {}".format("python", "oz")
"purpose of life is {1}, my computation in {0} says so!".format( "python", 0)
"purpose of life is {purpose}, my computation in {container} says so!".format(purpose=42, container="python")
for i in range(1, 11):
line = "{integers:2d} {squares:3d} {cubes:4d}".format(integers=i, squares=i*i, cubes=i*i*i)
print(line)
"12".zfill(4)
"12.12".zfill(8)
problem:
>>> pascal(3)
[[1],[1,1],[1,2,1]]
print_pascal to prety print pascal triangle as shown below
>>> print_pascal(pascal(5))
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
def pascal(n):
"""
computes pascal triangle with given base
strategy for calulating next row is to
1
1 1
\ /
+
1 2 1 0 1 2 1
\ / \ / 1 2 1 0
1 3 3 1=> ----------
1 3 3 1
"""
triangle = [[1]]
for i in range(n-1):
base = triangle[-1]
l1 = base[:]
l2 = base[:]
l1.insert(0, 0)
l2.append(0)
newbase = [x+y for x,y in zip(l1, l2)]
triangle.append(newbase)
return triangle
pascal(3)
def print_pascal(triangle):
def count_digits(n):
return len(str(n))
base = len(triangle[-1])
d = count_digits(max(triangle[-1]))#number of digits in biggest number
width = d * base + (base -1) #total width of triangle including numbers and 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(pascal(5))
print_pascal(pascal(15))