Python Training at VMWare Bangalore - Day

Sep 18-20 2017 Vikrant Patil

These notes are available online at http://notes.pipal.in/2017/vmware-python

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

In [1]:
1 > 2
Out[1]:
False
In [2]:
1.99 <= 2.0
Out[2]:
True
In [3]:
2 != 3
Out[3]:
True
In [4]:
2 == 3
Out[4]:
False
In [5]:
"python" > "c++"
Out[5]:
True
In [6]:
"alice" in "alice in wonderland"
Out[6]:
True
In [8]:
"alice" not in "wizard of oz"
Out[8]:
True
In [9]:
book = "alice in wonderland"
In [10]:
book.startswith("alice")
Out[10]:
True
In [11]:
book.endswith("land")
Out[11]:
True
In [12]:
def is_python_script(filename):
    return filename.endswith(".py")
In [13]:
is_python_script("hello.py")
Out[13]:
True
In [14]:
import os
In [15]:
os.listdir(os.getcwd())
Out[15]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'anothermodule.py',
 'mymodule.pyc',
 'day2.ipynb',
 'echo.py',
 'day2.html',
 'square.py',
 'mymodule.py',
 'day3.ipynb',
 'day3.html',
 'Makefile',
 '__pycache__',
 'day1.html']
In [16]:
is_python_script("hello.java")
Out[16]:
False

if statement

In [17]:
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")
Obviously python also has if
In [18]:
def even(n):
    if n%2 == 0:
        return True
    else:
        return False
In [19]:
even(10)
Out[19]:
True
In [20]:
even(11)
Out[20]:
False

The conditional after if/elif will be True for

  • nonzero integer value
  • any object that is not None
  • any sequence that is not empty
In [25]:
def is_empty(sequence):
    if sequence:
        print("Not Empty")
    else:
        print("Empty")
In [26]:
is_empty([1,2,3])
Not Empty
In [27]:
is_empty([])
Empty
In [28]:
is_empty("")
Empty
In [29]:
is_empty("nonempty")
Not Empty
In [30]:
is_empty(())
Empty
In [31]:
is_empty(None)
Empty
In [35]:
def even(n):
    if n%2 == 0:
        return True
    else:
        return False
In [36]:
def odd(n):
    return not even(n)
In [33]:
odd(9)
Out[33]:
True
In [34]:
odd(8)
Out[34]:
False
In [37]:
def odd1(n):
    return ! even(n)
  File "<ipython-input-37-e495294c075d>", line 2
    return ! even(n)
           ^
SyntaxError: invalid syntax

Do it yourself

  • write a function filetype which will take filename as argument and return what file type it has. it should following types
type      extension
java      .java
python    .py
c         .c
c++       .cpp
text      .txt

filetype("hello.java")
java
filetype("sometext.txt")
text
  • write a function minimum (without using built in function min) which finds minimum from given two numbers
>>> minimum(3,4)
3
>>> minimum(42, 1000)
42
  • Write minimum3 which takes 3 integers and returns minimum of it
    minimum3(1,2,3)
    1
In [38]:
def minimum(x, y):
    if x < y:
        return x
    else:
        return y
In [39]:
primes = [2,3,5,7,11,13,17]
In [40]:
x = 2
(x in primes ) and even(x)
Out[40]:
True
In [41]:
def minimum3(x, y, z):
    min1 = minimum(x, y)
    return minimum(min1, z)
In [42]:
minimum3(3,4,5)
Out[42]:
3
In [43]:
primes = [2,3,5,7,11,13,17]
In [44]:
5 in primes
Out[44]:
True
In [45]:
6 in primes
Out[45]:
False
In [47]:
primes2 = primes
In [48]:
primes == primes2
Out[48]:
True
In [49]:
primes is primes2
Out[49]:
True
In [50]:
primes3 = [2,3,5,7,11,13,17]
In [51]:
primes == primes3
Out[51]:
True
In [52]:
primes is primes3
Out[52]:
False
In [53]:
person = {"name":"robinson",
         "books":["Elements", "Finding your element"],
         "TED":"How schools kill creativity"}
In [54]:
person
Out[54]:
{'TED': 'How schools kill creativity',
 'books': ['Elements', 'Finding your element'],
 'name': 'robinson'}
In [55]:
"robinson" in person
Out[55]:
False
In [56]:
"name" in person
Out[56]:
True
In [57]:
"robinson" in person.values()
Out[57]:
True
In [58]:
person.values()
Out[58]:
dict_values([['Elements', 'Finding your element'], 'How schools kill creativity', 'robinson'])

To write files using jupyter

In [59]:
%%file sample.py
import sys
print(sys.argv)
Writing sample.py
In [60]:
!python sample.py
['sample.py']

while loop

conditionals what we learnt earlier can be used for while loop

In [67]:
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=" ")
    
In [68]:
print_fibonacci(10000)
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 

for loop

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

In [69]:
names = ["Elsa", "David", "Mahesh", "Hari"]
In [70]:
for name in names:
    print(name)
Elsa
David
Mahesh
Hari
In [71]:
for prime in primes:
    print(prime)
2
3
5
7
11
13
17
In [73]:
for c in "This random statement for testing for loop":
    print(c, end=",")
T,h,i,s, ,r,a,n,d,o,m, ,s,t,a,t,e,m,e,n,t, ,f,o,r, ,t,e,s,t,i,n,g, ,f,o,r, ,l,o,o,p,
In [74]:
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
In [77]:
for i in range(2, 10, 2):
    print(i, end=",")
2,4,6,8,

Do it yourself

  • Write a python script ls.py, to files in current directory.
    python ls.py
    anothermodule.py
    day1.html
    .
    .
  • Write a function mysum that sums up elements in a given list
    >>> mysum([1, 2, 3, 4])
    10
  • Write a function to compute product of all elements from a list
    product([1,2,3,4])
    24
  • Write a function to compute factorial of a number
    >>> factorial(4)
    24
In [84]:
%%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)
Overwriting ls.py
In [85]:
!python ls.py
.ipynb_checkpoints
push
day1.ipynb
anothermodule.py
mymodule.pyc
sample.py
Untitled.ipynb
day2.ipynb
echo.py
day2.html
Untitled.html
square.py
mymodule.py
day3.ipynb
day3.html
Makefile
__pycache__
day1.html
ls.py
In [86]:
def mysum(numbers):
    s = 0
    for n in numbers:
        s = s + n
    
    return s
In [87]:
mysum([1,2,3,4])
Out[87]:
10
In [88]:
def product(numbers):
    p = 1
    for n in numbers:
        p = p * n
    
    return p
In [89]:
product([1,2,3,4,6])
Out[89]:
144
In [90]:
def factorial(n):
    return product(range(1, n+1))
In [91]:
factorial(10)
Out[91]:
3628800
In [92]:
factorial(4)
Out[92]:
24
In [93]:
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=",")
            
In [94]:
print_primes(100)
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,

Recap list methods

In [95]:
numbers = list(range(10))
In [96]:
numbers.append(11)
In [97]:
numbers.insert(0, -1)
In [98]:
numbers
Out[98]:
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
In [99]:
numbers.pop()
Out[99]:
11
In [100]:
numbers
Out[100]:
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [101]:
numbers.pop(0)
Out[101]:
-1
In [102]:
numbers.index(5)
Out[102]:
5
In [103]:
emptylist = []
  • Write a function to sqaure items in a given list
    square([1,2,3])
    [1,4,9]
  • write a function to find out even numbers from a list
    evens([1,2,3,4,5,6,7,8,9])
    [2,4,6,8]

List slicing recap

In [105]:
digits = list(range(10))
In [107]:
digits[1:6] # list containing items from index 1 (included) t 6 (exluded)
Out[107]:
[1, 2, 3, 4, 5]
In [108]:
digits[1:] # list from index 1 (included) till end
Out[108]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [109]:
digits[:5] # list from 0 (start) till index 5(excluded)
Out[109]:
[0, 1, 2, 3, 4]
In [110]:
digits[-1]
Out[110]:
9
In [111]:
digits[:-1] # all elements excpet last
Out[111]:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
In [112]:
digits[:] # all
Out[112]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [113]:
4 in digits
Out[113]:
True
In [114]:
digits[::-1] # reversed list
Out[114]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

How do we check if given word is palindrom?

In [115]:
word = "madam"
In [116]:
word == word[::-1]
Out[116]:
True
In [117]:
is_palindrom = lambda word: word == word[::-1]
In [118]:
is_palindrom("madam")
Out[118]:
True
In [119]:
is_palindrom("Hello")
Out[119]:
False
In [120]:
is_palindrom("civic")
Out[120]:
True
In [121]:
palindrom_ignore_case = lambda word: word.lower() == word.lower()[::-1]
In [122]:
palindrom_ignore_case("Madam")
Out[122]:
True
  • Write a function 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])
  • Write a function find_extension to find extension of a file, given file name.
    find_extension("python.exe")
    exe
  • What might be output of this?
s = "Do geese see God?"
s[100]
s[3:100]
In [127]:
split_at = lambda items, index : ( items[:index],items[index:])
In [128]:
split_at(list(range(10)), 5)
Out[128]:
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
In [129]:
def find_extension(filename):
    pieces = filename.split(".")
    return pieces[-1]
In [130]:
find_extension("python.tar.gz")
Out[130]:
'gz'
In [131]:
def find_extension(filename):
    return filename.split(".")[-1]
In [132]:
s = "Do geese see God?"
In [133]:
s[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-133-4868bd16d438> in <module>()
----> 1 s[100]

IndexError: string index out of range
In [134]:
s[3:100]
Out[134]:
'geese see God?'

List comprehensions

In [135]:
numbers = range(10)
In [136]:
numbers
Out[136]:
range(0, 10)
In [137]:
nums = [n for n in numbers]
In [138]:
nums
Out[138]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [139]:
[n for n in numbers]
Out[139]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [140]:
[n*n for n in numbers]
Out[140]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [141]:
[2*n for n in numbers]
Out[141]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [142]:
[n**3 for n in numbers]
Out[142]:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
In [ ]:
[factorial(n) for n in numbers]

Lets make list of words from a sentence ..but upper case

In [144]:
[ word.upper() for word in "let me make some sentence for testing".split()]
Out[144]:
['LET', 'ME', 'MAKE', 'SOME', 'SENTENCE', 'FOR', 'TESTING']
In [146]:
[is_palindrom(word) for word in "some random statement with no palindrom".split()]
Out[146]:
[False, False, False, False, False, False]
In [147]:
[i for i in range(20) if i%2==0]
Out[147]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [148]:
[ [i*j for j in range(1,11)] for i in range(1, 6) ]
Out[148]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
 [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
 [4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
 [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]]

Do it yourself

  • Write a function listpy which will return list of all ".py" files from given directory
    listpy(os.getcwd())
    ['add.py', 'arguments.py','square.py']
  • Write a function factors which will return list of factors of given integer including 1 and self.
    factors(10)
    [1,2,5,10]
  • Given that prime number has only two factors 1 and self, write a function is_prime which determines if given number is prime or not
    is_prime(4)
    False
    is_prime(5)
    True
  • Write a function primes to generate prime numbers less than or equal to n
primes(23)
[2,3,5,7,11,13,17,19,23]
In [149]:
import os
def listpy():
    currentdir = os.getcwd()
    files = os.listdir(currentdir)
    return [f for f in files if f.endswith(".py")]
In [150]:
listpy()
Out[150]:
['anothermodule.py',
 'sample.py',
 'echo.py',
 'square.py',
 'mymodule.py',
 'ls.py']
In [151]:
def factors(n):
    return [i for i in range(1, n+1) if n%i == 0]
In [152]:
factors(20)
Out[152]:
[1, 2, 4, 5, 10, 20]
In [153]:
def is_prime(n):
    return factors(n) == [1,n]
In [154]:
is_prime(7)
Out[154]:
True
In [155]:
is_prime(8)
Out[155]:
False
In [156]:
def primes(n):
    return [p for p in range(1, n+1) if is_prime(p)]
In [158]:
primes(50)
Out[158]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [159]:
[[i+j for i in range(5)] for j in range(5)]
Out[159]:
[[0, 1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [2, 3, 4, 5, 6],
 [3, 4, 5, 6, 7],
 [4, 5, 6, 7, 8]]
In [160]:
def f(x,y):
    if x == y:
        return 1
    else:
        return 0
In [161]:
[[f(i,j) for i in range(5)] for j in range(5)]
Out[161]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]

Iteration patterns

Iterating over list/sequence/string/tuple

In [162]:
for prime in primes(23):
    print(prime)
2
3
5
7
11
13
17
19
23
In [164]:
for prime in reversed(primes(23)):
    print(prime)
23
19
17
13
11
7
5
3
2
In [165]:
coundown = reversed(range(10))
In [166]:
coundown
Out[166]:
<range_iterator at 0x7f05a5b82540>

Iterating with index

In [167]:
for i,item in enumerate(primes(23)):
    print(i, item)
0 2
1 3
2 5
3 7
4 11
5 13
6 17
7 19
8 23
In [168]:
names = ["Elsa", "Alisa", "Exotica", "Beauty"]
surnames = ["Frozen", "Hacker", "Logica", "Nurd"]
In [170]:
for name, surname in zip(names, surnames):
    print(name, surname)
Elsa Frozen
Alisa Hacker
Exotica Logica
Beauty Nurd
In [171]:
zip(['a','b','c'], [1,2,3])
Out[171]:
<zip at 0x7f05a6593b08>
In [173]:
list(zip(['a','b','c', 'd'], [1,2,3]))
Out[173]:
[('a', 1), ('b', 2), ('c', 3)]
In [178]:
def zip3(first, second, third):
    return [ (first[i], second[i], third[i]) for i, item in enumerate(second)]
In [179]:
zip3(['a','b','c'], [1,2,3], ["A", "B", "C"])
Out[179]:
[('a', 1, 'A'), ('b', 2, 'B'), ('c', 3, 'C')]
In [176]:
def vector_add(v1, v2):
    return [a+b for a, b in zip(v1, v2)]
In [177]:
vector_add([1,2,3], [2,3,4])
Out[177]:
[3, 5, 7]

Docstrings

In [180]:
%%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
Writing functions.py
In [181]:
!pydoc functions
Help on module functions:

NNAAMMEE
    functions

FFIILLEE
    /home/vikrant/trainings/2017/vmware-python/functions.py

DDEESSCCRRIIPPTTIIOONN
    module functions
    this serves as long descrption for module functions.
    it implements some basic arithmatic functions

FFUUNNCCTTIIOONNSS
    aadddd(x, y)
        computes addition
        >>> add(2,3)
        5
    
    mmuulltt(x, y)
        multiplies x and y
        >>> mult(2, 3)
        6


In [182]:
import functions
In [183]:
help(functions)
Help on module functions:

NAME
    functions

DESCRIPTION
    module functions
    this serves as long descrption for module functions.
    it implements some basic arithmatic functions

FUNCTIONS
    add(x, y)
        computes addition
        >>> add(2,3)
        5
    
    mult(x, y)
        multiplies x and y
        >>> mult(2, 3)
        6

FILE
    /home/vikrant/trainings/2017/vmware-python/functions.py


In [184]:
!python -m doctest -v functions.py
Trying:
    add(2,3)
Expecting:
    5
ok
Trying:
    mult(2, 3)
Expecting:
    6
ok
1 items had no tests:
    functions
2 items passed all tests:
   1 tests in functions.add
   1 tests in functions.mult
2 tests in 3 items.
2 passed and 0 failed.
Test passed.

Testing

In [185]:
from functions import add, mult
In [186]:
assert add(3,4) == 7
In [187]:
assert add(3,4) == 8
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-187-a0d60c2ab3d0> in <module>()
----> 1 assert add(3,4) == 8

AssertionError: 
In [192]:
def test_functions():
    assert add(3,4) == 7
    assert add(3,4) != 8
    assert mult(3,4) == 12
In [193]:
test_functions()
In [196]:
%%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
Overwriting functions.py
In [197]:
!py.test functions.py
============================= test session starts ==============================
platform linux -- Python 3.5.2, pytest-3.2.2, py-1.4.34, pluggy-0.4.0
rootdir: /home/vikrant/trainings/2017/vmware-python, inifile:
collected 1 item                                                                

functions.py F

=================================== FAILURES ===================================
________________________________ test_functions ________________________________

    def test_functions():
        assert add(3,4) == 7
        assert add(3,4) != 8
        assert mult(3,4) == 12
>       assert mult(4,5) == 15
E       assert 20 == 15
E        +  where 20 = mult(4, 5)

functions.py:27: AssertionError
=========================== 1 failed in 0.03 seconds ===========================

string formating

In [198]:
def square_and_cubes_table():
    for i in range(1, 11):
        print(i, i*i, i**3)
In [199]:
square_and_cubes_table()
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
In [203]:
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))
In [204]:
square_and_cubes_table()
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [205]:
"Wizard of oz is {}".format("python")
Out[205]:
'Wizard of oz is python'
In [206]:
"wizard of {} is in {}".format("python", "oz")
Out[206]:
'wizard of python is in oz'
In [208]:
"purpose of life is {0}, my computation in {1} says so".format(0, "python")
Out[208]:
'purpose of life is 0, my computation in python says so'
In [209]:
"purpose of life is {purpose}, my computation in {container} says so".format(purpose=0, container="python")
Out[209]:
'purpose of life is 0, my computation in python says so'
In [210]:
print("Some formated string with {}".format("argument"), 42, [1,2,3])
Some formated string with argument 42 [1, 2, 3]
In [211]:
for i in range(1, 11):
    line = "{integers:2d} {squares:3d} {cubes:4d}".format(integers=i, squares=i*i, cubes=i**3)
    print(line)
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
In [212]:
"12".zfill(4)
Out[212]:
'0012'
In [213]:
"12.12".zfill(8)
Out[213]:
'00012.12'

Do it yourself

  • Write a fucntion pascal to generate pascal triangle of base n.
    >>> 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
In [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
In [2]:
pascal(3)
Out[2]:
[[1], [1, 1], [1, 2, 1]]
In [ ]:
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