Python Foundation Training Day 2

by Vikrant Patil

at MIT Pune, IT Dept. Mar 12-16, 2018

Notes are available online at

https://notes.pipal.in/2018/mit-pune-march/

Magic variable __main__

In [1]:
%%file hello1.py

import sys

def say_hello(name):
    print("Hello", name)
    
say_hello(sys.argv[1])
Writing hello1.py
In [2]:
!python hello1.py MIT
Hello MIT
In [3]:
import hello1
Hello -f
In [9]:
%%file square.py

import sys

def square(x):
    return x*x

print(square(int(sys.argv[1])))
Overwriting square.py
In [10]:
!python square.py 3
9
In [11]:
import square
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-8364e62fdb9b> in <module>()
----> 1 import square

/home/vikrant/trainings/2018/mit-pune-march/square.py in <module>()
      5     return x*x
      6 
----> 7 print(square(int(sys.argv[1])))

ValueError: invalid literal for int() with base 10: '-f'
In [12]:
def f():
    pass
In [15]:
%%file main.py

print(__name__)
Overwriting main.py
In [16]:
!python main.py
__main__
In [17]:
import main
main
In [18]:
%%file module2.py

print(__name__)
Writing module2.py
In [19]:
!python module2.py
__main__
In [20]:
import module2
module2
In [23]:
%%file square1.py
import sys

def square(x):
    return x*x

if __name__ == "__main__":
    print(square(int(sys.argv[1])))
Overwriting square1.py
In [24]:
!python square1.py 5
25
In [25]:
import square1

problem

  • implement python script echo.py which implements unix command echo approximately
In [27]:
!echo hello python training at MIT pune
hello python training at MIT pune
In [28]:
words = ["one", "two", "three", "four"]
In [29]:
"_".join(words)
Out[29]:
'one_two_three_four'
In [30]:
" ".join(words)
Out[30]:
'one two three four'
In [31]:
words = ["one", "two", "three", "four", "five"]
In [32]:
" ".join(words)
Out[32]:
'one two three four five'
In [34]:
import sys
In [35]:
sys.argv
Out[35]:
['/home/vikrant/usr/local/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py',
 '-f',
 '/run/user/1000/jupyter/kernel-9f719cd1-1a6e-478f-87f8-22ee73a33d23.json']
In [36]:
" ".join(sys.argv[1:])
Out[36]:
'-f /run/user/1000/jupyter/kernel-9f719cd1-1a6e-478f-87f8-22ee73a33d23.json'
In [37]:
%%file echo.py
import sys

if __name__ == "__main__":
    print(" ".join(sys.argv[1:]))
Writing echo.py
In [38]:
!python echo.py hello at Python foundation course at MIT pune
hello at Python foundation course at MIT pune

conditions

In [39]:
2 == 3
Out[39]:
False
In [40]:
2 != 3
Out[40]:
True
In [41]:
2 <= 2.0
Out[41]:
True
In [42]:
1.99 > 2
Out[42]:
False
In [43]:
1.99 >= 2
Out[43]:
False
In [44]:
2 < 2.0
Out[44]:
False
In [45]:
book = "Alice in wonderland"
In [46]:
"Alice" in book
Out[46]:
True
In [47]:
"Alex" not in book
Out[47]:
True
In [48]:
book.endswith("land")
Out[48]:
True
In [49]:
book.startswith("Alice")
Out[49]:
True
In [50]:
book.split()[0] is "Alice"
Out[50]:
False
In [51]:
name = "Alice"
In [52]:
name is "Alice"
Out[52]:
True
In [54]:
name == "Alice"
Out[54]:
True
In [55]:
primes = [2,3,5,7]
In [56]:
2 in primes
Out[56]:
True
In [57]:
2 not in primes
Out[57]:
False
In [58]:
2 not in primes or 5 in primes
Out[58]:
True
In [59]:
name is "Alice" and 2 in primes
Out[59]:
True
In [60]:
primes1 = [2,3,5,7]
In [61]:
primes == primes1
Out[61]:
True
In [63]:
primes is primes1
Out[63]:
False
In [64]:
person = {"name":"alice", "email":"alice@wonder.land"}
In [65]:
"name" in person
Out[65]:
True
In [66]:
"alice" in person
Out[66]:
False
In [67]:
"alice" in person.values()
Out[67]:
True
In [69]:
emptylist = []
emptystring = ""
emptydict = {}
nothing = None
In [70]:
#if emptylist: # this is False condition
In [73]:
if "python" > "c++":
    #statemaent
    print("yes..python!")
elif "alice" in book:
    #statements
    pass
elif "python" is "english":
    #statement
    doom
    pass
else:
    #comes here if no condition above is satisfied
    pass
yes..python!
In [74]:
if name is "Alice":
    print("Yes name is alice")
Yes name is alice
In [78]:
2 if name is "Alice" else 3
Out[78]:
2

problems

  • Write a function filetype which identifies type of file based on extension as given in table below
     extention        filetype
     .py              python
     .java            jave
     .hs              haskell
     .lsp             lisp
     .txt             text
  • Write a function minimum2 which returns minimum of given two numbers.(do not use built in min)
  • Write a function minimum3 which returns minimum of given three numbers.
In [79]:
"hello.py".split(".")
Out[79]:
['hello', 'py']
In [80]:
def filetype(filename):
    if filename.endswith(".py"):
        return "python"
    elif filename.endswith(".java"):
        return "java"
    elif filename.endswith(".hs"):
        return "haskell"
    elif filename.endswith(".lsp"):
        return "lisp"
    elif filename.endswith(".txt"):
        return "text"
    
In [81]:
filetype("hello.py")
Out[81]:
'python'
In [82]:
filetype("xyz.tar.gz")
In [83]:
filetype("hello.java.py")
Out[83]:
'python'
In [84]:
def filetype(filename):
    extensions = {"py":"python",
                 "java":"java",
                 "txt":"text",
                 ".hs":"haskell",
                 ".lsp":"lisp"}
    ext = filename.split(".")[-1]
    if ext in extensions:
        return extensions[ext]
    
In [86]:
"xyz.tar.gz".split(".")[-1]
Out[86]:
'gz'
In [87]:
def minimum2(x,y):
    if x<y:
        return x
    else:
        return y
In [88]:
def minimum3(x,y,z):
    return minimum2(minimum2(x,y),z)
In [90]:
minimum3(5,6,1)
Out[90]:
1
In [91]:
x,y = 1,2
In [92]:
x
Out[92]:
1
In [93]:
y
Out[93]:
2

while loop

In [94]:
def print_fibonacci(n):
    """
    print fibonacci numbers less than n
    """
    current, prev = 1, 1
    
    while prev < n:
        current, prev = prev + current, current
        print(prev, end=",")
    
In [95]:
print_fibonacci(100)
1,2,3,5,8,13,21,34,55,89,144,

for loops

In [96]:
for number in [1,2,3,4]:
    print(number)
1
2
3
4
In [97]:
for char in "This is a string":
    print(char)
T
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g
In [98]:
for c in (255,0,230):
    print(c, end=" ")
255 0 230 
In [99]:
for n in range(5):
    print(n)
0
1
2
3
4
In [100]:
for key in person:
    print(key, person[key])
name alice
email alice@wonder.land
In [101]:
for item in set([1,1,2,2,1,43,1,2,3,1,2]):
    print(item, end=",")
3,1,2,43,
In [102]:
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
In [103]:
for i in range(0,10,2):
    print(i, end=",")
0,2,4,6,8,

problems

  • Write ls.py which prints names of files from given directory to standard output
python ls.py /tmp
config-err-7IDenG
mintUpdate
ssh-tBJL6P3COpiT
systemd-private-88ddcccd84d04fb0bfc528826826ab5e-colord.service-7vJkKP
systemd-private-88ddcccd84d04fb0bfc528826826ab5e-rtkit-daemon.service-IEZqa7
In [110]:
%%file ls.py
import sys
import os

def ls(path):
    files = os.listdir(path)
    for file in files:
        print(file)
        
if __name__ == "__main__":
    if len(sys.argv)>1:
        ls(sys.argv[1])
    else:
        ls(os.getcwd())
Overwriting ls.py
In [109]:
!python ls.py /tmp
ssh-tBJL6P3COpiT
.XIM-unix
.font-unix
systemd-private-88ddcccd84d04fb0bfc528826826ab5e-colord.service-7vJkKP
.ICE-unix
.X11-unix
config-err-7IDenG
systemd-private-88ddcccd84d04fb0bfc528826826ab5e-rtkit-daemon.service-IEZqa7
.X0-lock
.Test-unix
mintUpdate

There are break and continue statements for loops. but there is also else block for for loop

In [111]:
def print_primes(n):
    """
    print prime numbers less than n
    """
    for i in range(2, n+1):
        for j in range(2, i):
            if i%j==0:
                break
        else:
            print(i, end=",")
    
In [112]:
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 [113]:
l = [1,1,1,1,0,0]
In [114]:
l.append(1)
In [115]:
l
Out[115]:
[1, 1, 1, 1, 0, 0, 1]
In [116]:
l.insert(0, -1)
In [117]:
l
Out[117]:
[-1, 1, 1, 1, 1, 0, 0, 1]
In [118]:
l.pop()
Out[118]:
1
In [119]:
l
Out[119]:
[-1, 1, 1, 1, 1, 0, 0]
In [120]:
l.pop(0)
Out[120]:
-1
In [121]:
l
Out[121]:
[1, 1, 1, 1, 0, 0]

problems

  • Write a function mysum to sum elements from a list
>>> mysum([1,1,1,1]
4
  • Write a function product to find product of all elements from list
>>> product([1,2,3,4])
24
  • Write a function factorial to find factorial of n
>>> factorial(4)
24
In [122]:
for i in [1,2,3,4,5]:
    print(i)
1
2
3
4
5
In [123]:
def mysum(items):
    s = 0
    for item in items:
        s += item
    return s
In [124]:
mysum([1,2,3,4])
Out[124]:
10
In [125]:
"one" + "_" + "two"
Out[125]:
'one_two'
In [126]:
def mysum(items):
    s = items[0]
    for item in items[1:]:
        s += item
    return s
In [127]:
mysum(["a","b","c","d"])
Out[127]:
'abcd'
In [128]:
mysum(range(10))
Out[128]:
45
In [129]:
def product(numbers):
    p = numbers[0]
    for n in numbers:
        p = p*n
        
    return p
In [130]:
product([1,2,3,4])
Out[130]:
24
In [134]:
def factorial(n):
    return product(range(1,n+1))
In [135]:
factorial(4)
Out[135]:
24
In [136]:
numbers = list(range(1,11))
In [144]:
twice = []
for n in numbers:
    twice.append(2*n)
In [145]:
twice
Out[145]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [146]:
numbers
Out[146]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [147]:
def convert(item):
    return str(item)
    
converted = []
for n in numbers:
    converted.append(convert(n))
In [148]:
converted
Out[148]:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

problem

  • Write a function squarelist which squares every item from a list
  • Write a function evens which will find out even numbers from given list
In [149]:
def squarelist(items):
    sqrl = []
    for n in items:
        sqrl.append(n*n)
    return sqrl
In [150]:
squarelist(range(10))
Out[150]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [151]:
def evens(numbers):
    e = []
    for n in numbers:
        if n%2==0:
            e.append(n)
    return e
In [152]:
evens(range(20))
Out[152]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

list slicing

In [153]:
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
In [154]:
primes[2:7] # start at index 2 end at index 7 (exlude)
Out[154]:
[5, 7, 11, 13, 17]
In [155]:
primes[2:10:3] # start at index 2 end at index 10 (exlude) at step of 3
Out[155]:
[5, 13, 23]
In [156]:
primes[2:10] # if step is not given it is taken as 1
Out[156]:
[5, 7, 11, 13, 17, 19, 23, 29]
In [157]:
primes[:10] # default start is 0
Out[157]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
In [159]:
primes[10:] # default end is at last index
Out[159]:
[31, 37, 41, 43, 47]
In [161]:
primes[:]
Out[161]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [162]:
primes[:-1]
Out[162]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
In [163]:
primes[:-2]
Out[163]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
In [164]:
primes
Out[164]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [165]:
p = primes[:-1]
In [166]:
primes
Out[166]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [167]:
p
Out[167]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
In [168]:
primes[::-1]
Out[168]:
[47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2]
In [169]:
word = "madam"
In [170]:
def is_palindrom(w):
    return w==w[::-1]
In [171]:
is_palindrom(word)
Out[171]:
True
In [172]:
palindrom = lambda w: w==w[::-1]
In [173]:
palindrom("madam")
Out[173]:
True
In [174]:
def f(x):
    return x, 2*x
In [175]:
f(3)
Out[175]:
(3, 6)

problem

  • Write a function split_at which splits given list at given location
>>> split_at([1,2,3,4,5,6,7,8], 3)
([1,2,3],[4,5,6,7,8])
>>> split_at("Alice in wonderland",5)
("Alice"," in wonderland")
In [176]:
def split_at(seq, n):
    return seq[:n],seq[n:]

list comprehensions

In [177]:
[n*n for n in range(10)]
Out[177]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [178]:
[2*n for n in range(10)]
Out[178]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [179]:
words
Out[179]:
['one', 'two', 'three', 'four', 'five']
In [180]:
[w.upper() for w in words]
Out[180]:
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']
In [181]:
s = []
for i in range(10):
    s.append(i*i)
In [182]:
s
Out[182]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [183]:
[i*i for i in range(10)]
Out[183]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [184]:
[i for i in primes]
Out[184]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [185]:
[i for i in range(10) if i%2==0]
Out[185]:
[0, 2, 4, 6, 8]
In [186]:
e = [i for i in range(10) if i%2==0]
In [187]:
e
Out[187]:
[0, 2, 4, 6, 8]
In [188]:
o = [i for i in range(10) if i%2!=0]
In [189]:
o
Out[189]:
[1, 3, 5, 7, 9]
In [190]:
[[i for i in range(1,6)] for j in range(1,11)]
Out[190]:
[[1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5],
 [1, 2, 3, 4, 5]]
In [191]:
[[i*j for i in range(1,6)] for j in range(1,11)]
Out[191]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [192]:
t = [[i*j for i in range(1,6)] for j in range(1,11)]
In [193]:
t
Out[193]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]

problems

  • Write a function listpy to get python files from given directory.
    >>> listpy(os.getcwd())
    ["echo.py","hello.py","main.py"]
  • Write a function factors which finds all factors of given number.
>>> factors(5)
[1,5]
>>> factors(6)
[1,2,3,6]
  • Write a function is_prime which tells if given number is prime or not based on fact that prime number has only 2 factors , 1 and self
  • Write a list comprehension to generate prime numbers less than some n
  • Generate a identity matrix of size 5x5 using list comprehensions.
    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

bonus problem

  • What is sum of all multiples of 7 or 11 below 1000.
  • transpose a 2D matrix
  • rotate 2D matrix by 90 degree in clockwise direction.
In [194]:
sum([1,1,1,1])
Out[194]:
4
In [197]:
import os
def listpy(path):
    files = os.listdir(path)
    return [file for file in files if file.endswith(".py")]
In [198]:
listpy(".")
Out[198]:
['main.py',
 'module.py',
 'echo.py',
 'square.py',
 'hello.py',
 'hello1.py',
 'module1.py',
 'module2.py',
 'ls.py',
 'square1.py']
In [199]:
def factors(n):
    return [i for i in range(1,n+1) if n%i==0]
In [200]:
factors(10)
Out[200]:
[1, 2, 5, 10]
In [201]:
def is_prime(p):
    return factors(p)==[1,p]
In [202]:
def primes(n):
    return [p for p in range(2,n) if is_prime(p)]
In [203]:
primes(50)
Out[203]:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In [204]:
[[i+j for i in range(5)] for j in range(5)]
Out[204]:
[[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 [206]:
[[i==j for i in range(5)] for j in range(5)]
Out[206]:
[[True, False, False, False, False],
 [False, True, False, False, False],
 [False, False, True, False, False],
 [False, False, False, True, False],
 [False, False, False, False, True]]
In [207]:
[[int(i==j) for i in range(5)] for j in range(5)]
Out[207]:
[[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]]
In [208]:
def f(i,j):
    if i==j:
        return 1
    else:
        return 0
In [209]:
[[f(i,j) for i in range(5)] for j in range(5)]
Out[209]:
[[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]]
In [210]:
d = {True:1,False:0}
In [211]:
[[d[i==j] for i in range(5)] for j in range(5)]
Out[211]:
[[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]]
In [212]:
[[1 if i==j else 0 for i in range(5)] for j in range(5)]
Out[212]:
[[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]]
In [213]:
sum([i for i in range(1000) if i%7==0 or i%11==0])
Out[213]:
110110
In [214]:
t
Out[214]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [215]:
t[0]
Out[215]:
[1, 2, 3, 4, 5]
In [216]:
t[-1]
Out[216]:
[10, 20, 30, 40, 50]
In [217]:
t[0][-1]
Out[217]:
5
In [218]:
def column(data, colnum):
    numrows = len(data)
    return [t[r][colnum] for r in range(numrows)]
In [219]:
column(t, 0)
Out[219]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [220]:
t
Out[220]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [221]:
column(t, 1)
Out[221]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
In [222]:
def transpose(data):
    numcols = len(data[0])
    return [column(data, i) for i in range(numcols)]
In [223]:
transpose(t)
Out[223]:
[[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]]
In [224]:
t
Out[224]:
[[1, 2, 3, 4, 5],
 [2, 4, 6, 8, 10],
 [3, 6, 9, 12, 15],
 [4, 8, 12, 16, 20],
 [5, 10, 15, 20, 25],
 [6, 12, 18, 24, 30],
 [7, 14, 21, 28, 35],
 [8, 16, 24, 32, 40],
 [9, 18, 27, 36, 45],
 [10, 20, 30, 40, 50]]
In [225]:
def rotate90clockwise(data):
    numcols = len(data[0])
    return [column(data, i)[::-1] for i in range(numcols)]
In [226]:
rotate90clockwise(t)
Out[226]:
[[10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [20, 18, 16, 14, 12, 10, 8, 6, 4, 2],
 [30, 27, 24, 21, 18, 15, 12, 9, 6, 3],
 [40, 36, 32, 28, 24, 20, 16, 12, 8, 4],
 [50, 45, 40, 35, 30, 25, 20, 15, 10, 5]]

Iteration pattern

In [227]:
words
Out[227]:
['one', 'two', 'three', 'four', 'five']
In [229]:
for word in words:
    print(word)
one
two
three
four
five
In [230]:
for word in reversed(words):
    print(word)
five
four
three
two
one
In [232]:
for index, value in enumerate(words):
    print(index, value)
0 one
1 two
2 three
3 four
4 five
In [234]:
for i in range(len(words)): # not recommanded
    print(i, words[i])
0 one
1 two
2 three
3 four
4 five
In [235]:
first =["Elsa","Elisa","Nurd","David"]
last = ["Frozen", "Hacker", "Beauty", "Beazly"]
In [236]:
for f,l in zip(first, last):
    print(f,l)
Elsa Frozen
Elisa Hacker
Nurd Beauty
David Beazly
In [237]:
for i,j,k in zip(range(5), words, [1,1,1,1,1]):
    print(i,j,k)
0 one 1
1 two 1
2 three 1
3 four 1
4 five 1

problem

  • Write a function vector_add which does vector addition of two lists
In [238]:
a = [1,2,3,4]
b = [3,4,5,6]
In [239]:
def vector_add(v1,v2):
    return [i+j for i,j in zip(v1,v2)]
    
In [240]:
vector_add(a,b)
Out[240]:
[4, 6, 8, 10]

String formatting

In [241]:
for i in range(1,11):
    print(i, i*i, i*i*i)
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 [242]:
for i in range(1,11):
    print(str(i).rjust(2), str(i*i).rjust(3), str(i*i*i).rjust(4))
 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 [243]:
"Wizard of {} is in {}".format("python", "oz")
Out[243]:
'Wizard of python is in oz'
In [244]:
"Wizard of {1} is {0}".format("python","oz")
Out[244]:
'Wizard of oz is python'
In [245]:
"Wizard of {name} is in {place}".format(name="python", place="oz")
Out[245]:
'Wizard of python is in oz'
In [246]:
for i in range(1,11):
    print(" {integer} {square} {cube}".format(integer=i,square=i*i,cube=i*i*i))
 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 [247]:
for i in range(1,11):
    print(" {integer:2d} {square:3d} {cube:4d}".format(integer=i,
                                              square=i*i,
                                              cube=i*i*i))
  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

problem

  • Write a function to generate pascal triangle in list format
>>> pascal(4)
[[1],[1,1],[1,2,1],[1,3,3,1]]
  • Write a function print_pascal which pretty prints pascal triangle as given below
             1
          1      1
       1     2      1
    1     3      3     1
 1     4     6      4     1
In [ ]: