Sep 18-20 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-python
© Pipal Academy LLP
1 > 2
1.99 <= 2.0
2 != 3
2 == 3
"python" > "c++"
"alice" in "alice in wonderland"
"alice" not in "wizard of oz"
book = "alice in wonderland"
book.startswith("alice")
book.endswith("land")
def is_python_script(filename):
return filename.endswith(".py")
is_python_script("hello.py")
import os
os.listdir(os.getcwd())
is_python_script("hello.java")
python = [3.4, "if"]
if "if" in python:
print("Obviously python also has if")
elif python[0] > 3:
print("Python can have long list of elifs")
elif len(python)>2:
print("one more elif")
else:
print("Finaly you also have else")
def even(n):
if n%2 == 0:
return True
else:
return False
even(10)
even(11)
The conditional after if/elif will be True for
def is_empty(sequence):
if sequence:
print("Not Empty")
else:
print("Empty")
is_empty([1,2,3])
is_empty([])
is_empty("")
is_empty("nonempty")
is_empty(())
is_empty(None)
def even(n):
if n%2 == 0:
return True
else:
return False
def odd(n):
return not even(n)
odd(9)
odd(8)
def odd1(n):
return ! even(n)
filetype which will take filename as argument and return what file type it has. it should following typestype extension
java .java
python .py
c .c
c++ .cpp
text .txt
filetype("hello.java")
java
filetype("sometext.txt")
text
min) which finds minimum from given two numbers>>> minimum(3,4)
3
>>> minimum(42, 1000)
42
minimum3(1,2,3)
1
def minimum(x, y):
if x < y:
return x
else:
return y
primes = [2,3,5,7,11,13,17]
x = 2
(x in primes ) and even(x)
def minimum3(x, y, z):
min1 = minimum(x, y)
return minimum(min1, z)
minimum3(3,4,5)
primes = [2,3,5,7,11,13,17]
5 in primes
6 in primes
primes2 = primes
primes == primes2
primes is primes2
primes3 = [2,3,5,7,11,13,17]
primes == primes3
primes is primes3
person = {"name":"robinson",
"books":["Elements", "Finding your element"],
"TED":"How schools kill creativity"}
person
"robinson" in person
"name" in person
"robinson" in person.values()
person.values()
To write files using jupyter
%%file sample.py
import sys
print(sys.argv)
!python sample.py
conditionals what we learnt earlier can be used for while loop
def print_fibonacci(n):
"""
print fibonacci numbers less than n
"""
prev , current = 1 , 1
while current < n:
prev, current = current, prev + current
print(prev, end=" ")
print_fibonacci(10000)
for loop is slightly different as comapred to c or fortran... for loop in python always runs over some items, items from sequence. list, string, tuple, dictionary
names = ["Elsa", "David", "Mahesh", "Hari"]
for name in names:
print(name)
for prime in primes:
print(prime)
for c in "This random statement for testing for loop":
print(c, end=",")
for i in range(10):
print(i, end=",")
for i in range(2, 10, 2):
print(i, end=",")
python ls.py
anothermodule.py
day1.html
.
.
>>> mysum([1, 2, 3, 4])
10
product([1,2,3,4])
24
>>> factorial(4)
24
%%file ls.py
import os
def listdir(directory):
dirs = os.listdir(directory)
for d in dirs:
print(d)
if __name__ == "__main__":
currentdir = os.getcwd()
listdir(currentdir)
!python ls.py
def mysum(numbers):
s = 0
for n in numbers:
s = s + n
return s
mysum([1,2,3,4])
def product(numbers):
p = 1
for n in numbers:
p = p * n
return p
product([1,2,3,4,6])
def factorial(n):
return product(range(1, n+1))
factorial(10)
factorial(4)
def print_primes(n):
"""
prints prime numbers
"""
for i in range(2,n):
for j in range(2, i): #test primality
if i%j == 0:
break
else:
print(i, end=",")
print_primes(100)
Recap list methods
numbers = list(range(10))
numbers.append(11)
numbers.insert(0, -1)
numbers
numbers.pop()
numbers
numbers.pop(0)
numbers.index(5)
emptylist = []
square([1,2,3])
[1,4,9]
evens([1,2,3,4,5,6,7,8,9])
[2,4,6,8]
digits = list(range(10))
digits[1:6] # list containing items from index 1 (included) t 6 (exluded)
digits[1:] # list from index 1 (included) till end
digits[:5] # list from 0 (start) till index 5(excluded)
digits[-1]
digits[:-1] # all elements excpet last
digits[:] # all
4 in digits
digits[::-1] # reversed list
How do we check if given word is palindrom?
word = "madam"
word == word[::-1]
is_palindrom = lambda word: word == word[::-1]
is_palindrom("madam")
is_palindrom("Hello")
is_palindrom("civic")
palindrom_ignore_case = lambda word: word.lower() == word.lower()[::-1]
palindrom_ignore_case("Madam")
split_at , which splits given list in two lists at given 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 to find extension of a file, given file name.
find_extension("python.exe")
exe
s = "Do geese see God?"
s[100]
s[3:100]
split_at = lambda items, index : ( items[:index],items[index:])
split_at(list(range(10)), 5)
def find_extension(filename):
pieces = filename.split(".")
return pieces[-1]
find_extension("python.tar.gz")
def find_extension(filename):
return filename.split(".")[-1]
s = "Do geese see God?"
s[100]
s[3:100]
numbers = range(10)
numbers
nums = [n for n in numbers]
nums
[n for n in numbers]
[n*n for n in numbers]
[2*n for n in numbers]
[n**3 for n in numbers]
[factorial(n) for n in numbers]
Lets make list of words from a sentence ..but upper case
[ word.upper() for word in "let me make some sentence for testing".split()]
[is_palindrom(word) for word in "some random statement with no palindrom".split()]
[i for i in range(20) if i%2==0]
[ [i*j for j in range(1,11)] for i in range(1, 6) ]
listpy which will return list of all ".py" files from given directory
listpy(os.getcwd())
['add.py', 'arguments.py','square.py']
factors which will return list of factors of given integer including 1 and self.
factors(10)
[1,2,5,10]
is_prime which determines if given number is prime or not
is_prime(4)
False
is_prime(5)
True
primes to generate prime numbers less than or equal to nprimes(23)
[2,3,5,7,11,13,17,19,23]
import os
def listpy():
currentdir = os.getcwd()
files = os.listdir(currentdir)
return [f for f in files if f.endswith(".py")]
listpy()
def factors(n):
return [i for i in range(1, n+1) if n%i == 0]
factors(20)
def is_prime(n):
return factors(n) == [1,n]
is_prime(7)
is_prime(8)
def primes(n):
return [p for p in range(1, n+1) if is_prime(p)]
primes(50)
[[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 list/sequence/string/tuple
for prime in primes(23):
print(prime)
for prime in reversed(primes(23)):
print(prime)
coundown = reversed(range(10))
coundown
Iterating with index
for i,item in enumerate(primes(23)):
print(i, item)
names = ["Elsa", "Alisa", "Exotica", "Beauty"]
surnames = ["Frozen", "Hacker", "Logica", "Nurd"]
for name, surname in zip(names, surnames):
print(name, surname)
zip(['a','b','c'], [1,2,3])
list(zip(['a','b','c', 'd'], [1,2,3]))
def zip3(first, second, third):
return [ (first[i], second[i], third[i]) for i, item in enumerate(second)]
zip3(['a','b','c'], [1,2,3], ["A", "B", "C"])
def vector_add(v1, v2):
return [a+b for a, b in zip(v1, v2)]
vector_add([1,2,3], [2,3,4])
%%file functions.py
"""
module functions
this serves as long descrption for module functions.
it implements some basic arithmatic functions
"""
def add(x, y):
"""
computes addition
>>> add(2,3)
5
"""
return x+y
def mult(x, y):
"""
multiplies x and y
>>> mult(2, 3)
6
"""
return x*y
!pydoc functions
import functions
help(functions)
!python -m doctest -v functions.py
from functions import add, mult
assert add(3,4) == 7
assert add(3,4) == 8
def test_functions():
assert add(3,4) == 7
assert add(3,4) != 8
assert mult(3,4) == 12
test_functions()
%%file functions.py
"""
module functions
this serves as long descrption for module functions.
it implements some basic arithmatic functions
"""
def add(x, y):
"""
computes addition
>>> add(2,3)
5
"""
return x+y
def mult(x, y):
"""
multiplies x and y
>>> mult(2, 3)
6
"""
return x*y
def test_functions():
assert add(3,4) == 7
assert add(3,4) != 8
assert mult(3,4) == 12
assert mult(4,5) == 15
!py.test functions.py
def square_and_cubes_table():
for i in range(1, 11):
print(i, i*i, i**3)
square_and_cubes_table()
def square_and_cubes_table():
for i in range(1, 11):
print(repr(i).rjust(2), repr(i*i).rjust(3), repr(i**3).rjust(4))
square_and_cubes_table()
"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(0, "python")
"purpose of life is {purpose}, my computation in {container} says so".format(purpose=0, container="python")
print("Some formated string with {}".format("argument"), 42, [1,2,3])
for i in range(1, 11):
line = "{integers:2d} {squares:3d} {cubes:4d}".format(integers=i, squares=i*i, cubes=i**3)
print(line)
"12".zfill(4)
"12.12".zfill(8)
>>> pascal(3)
[[1],[1,1],[1,2,1]]
Write a functions print_pascal to prety print pascal triangle as shown below
>>> print_pascal(5)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
def pascal(base):
"""
computes pascal triangle with given base
strategy for calculating 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(base-1):
prev = triangle[-1]
pre = prev[:]
pre.insert(0,0)
post = prev[:]
post.append(0)
triangle.append([x+y for x,y in zip(pre, post)])
return triangle
pascal(3)
def pascal(base):
"""
computes pascal triangle with given base
strategy for calculating 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
"""
def insert_zero_at(numbers, location):
copy = numbers[:]
copy.insert(location, 0)
return copy
triangle = [[1]]
for i in range(base-1):
prev = triangle[-1]
pre = insert_zero_at(prev, 0)
post = insert_zero_at(prev, len(prev))
triangle.append([x+y for x,y in zip(pre, post)])
return triangle