Python Training at VMWare - Day 1

Feb 26-28, 2018 Vikrant Patil

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

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

Python distribution

We will be using anaconda (python 3.6) for this training. It can be downloaded at

https://www.anaconda.com/download

In [1]:
2 + 3
Out[1]:
5
In [2]:
print("Hello World!")
Hello World!
In [3]:
name = input()
python
In [4]:
print(name)
python

Basic data types

In [5]:
2 + 3
Out[5]:
5
In [6]:
2 - 3
Out[6]:
-1
In [7]:
5 / 2
Out[7]:
2.5
In [8]:
5 // 2
Out[8]:
2
In [9]:
2 ** 5
Out[9]:
32
In [10]:
2 * 5
Out[10]:
10
In [11]:
2 ** 1000
Out[11]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

It obviously has floats

In [12]:
2.0 ** 3
Out[12]:
8.0
In [13]:
2 - 3.0
Out[13]:
-1.0

It has strings

In [14]:
first = "Rupali"
last = "Rupak"
In [15]:
print(first)
Rupali
In [16]:
single = "have a string with ' qoute inside"
In [17]:
print(single)
have a string with ' qoute inside
In [18]:
double = 'a string with " quote inside'
In [19]:
print
Out[19]:
<function print>
In [ ]:
 
In [20]:
print(double)
a string with " quote inside
In [21]:
"hello \' world!"
Out[21]:
"hello ' world!"
In [22]:
multi = """
this is a 
multi line
string with 
five lines 
in it
"""
In [23]:
print(multi)
this is a 
multi line
string with 
five lines 
in it

In [24]:
multi
Out[24]:
'\nthis is a \nmulti line\nstring with \nfive lines \nin it\n'
In [25]:
regional = "आ क"
In [26]:
regional
Out[26]:
'आ क'
In [27]:
"\u0c85"
Out[27]:
'ಅ'
In [28]:
empty = ""

There is binary data

In [29]:
binary =  b'this is text converted to binary data'
In [30]:
print(binary)
b'this is text converted to binary data'
In [31]:
type(binary)
Out[31]:
bytes
In [36]:
b = b"\x023\x065"
In [39]:
type(b)
Out[39]:
bytes
In [41]:
first + last
Out[41]:
'RupaliRupak'
In [42]:
star = "*"
In [43]:
print(star*20)
********************
In [44]:
first[0]
Out[44]:
'R'
In [45]:
first[1]
Out[45]:
'u'

Lists

In [46]:
x = [1, 2, 3, 4]
In [47]:
x[0]
Out[47]:
1
In [48]:
x[-1]
Out[48]:
4
In [49]:
mixed = [1,1,1,"A","B","C"]
In [50]:
mixed
Out[50]:
[1, 1, 1, 'A', 'B', 'C']
In [51]:
list2d = [[1,1,1],[0,0,0],"A"]
In [52]:
list2d[0]
Out[52]:
[1, 1, 1]
In [53]:
list2d[1]
Out[53]:
[0, 0, 0]
In [54]:
list2d[2]
Out[54]:
'A'
In [55]:
emptylist = []
In [56]:
ones = [1,1,1,1]
In [57]:
moreones = ones + ones
In [58]:
moreones
Out[58]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [59]:
ones * 5
Out[59]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [60]:
ones
Out[60]:
[1, 1, 1, 1]

tuples are siblings of lists

In [61]:
t = (0,0,1)
In [62]:
t[0]
Out[62]:
0
In [63]:
t[-1]
Out[63]:
1
In [64]:
t + t
Out[64]:
(0, 0, 1, 0, 0, 1)
In [65]:
t * 5
Out[65]:
(0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1)
In [66]:
ones[0] = 0
In [67]:
ones
Out[67]:
[0, 1, 1, 1]
In [68]:
t[0] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-0a69537257d5> in <module>()
----> 1 t[0] = 1

TypeError: 'tuple' object does not support item assignment
In [69]:
t
Out[69]:
(0, 0, 1)
In [70]:
t[-1]
Out[70]:
1
In [71]:
empty = []

dictionaries

In [72]:
person = {"name":"alice","email":"alice@wonder.land","country":"UK"}
In [73]:
person["name"]
Out[73]:
'alice'
In [74]:
person["email"]
Out[74]:
'alice@wonder.land'
In [75]:
person["country"]
Out[75]:
'UK'
In [76]:
empty = {}
In [77]:
empty["key1"] = "value1"
empty["key2"] = "value2"
In [ ]:
 
In [78]:
empty
Out[78]:
{'key1': 'value1', 'key2': 'value2'}
In [79]:
data = {1:"one",2:"two",3:"three"}
In [80]:
data[1]
Out[80]:
'one'
In [81]:
data[2]
Out[81]:
'two'
In [82]:
data[3]
Out[82]:
'three'
In [84]:
unhashable = {[1,2,3]:"list",2:"two"}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-84-d3e6fa5e1d25> in <module>()
----> 1 unhashable = {[1,2,3]:"list",2:"two"}

TypeError: unhashable type: 'list'
In [85]:
hashable = {(1,2,3):"t",2:"two"}
In [86]:
hashable
Out[86]:
{(1, 2, 3): 't', 2: 'two'}
In [87]:
hashable[(1,2,3)]
Out[87]:
't'
In [88]:
hashable[3]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-88-1016b9370eb2> in <module>()
----> 1 hashable[3]

KeyError: 3

sets

In [89]:
sentence = """
some words to find out
how many english 
alphabetes are used in this 
sentence
"""
In [90]:
set(sentence)
Out[90]:
{'\n',
 ' ',
 'a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'l',
 'm',
 'n',
 'o',
 'p',
 'r',
 's',
 't',
 'u',
 'w',
 'y'}

Boolean

In [91]:
arr = False
In [92]:
ok = True
In [93]:
data = {True:"True",False:"Error"}
In [94]:
data[True]
Out[94]:
'True'
In [95]:
data[False]
Out[95]:
'Error'
In [96]:
key1 = "mahal"
key2 = "smaraka"
In [97]:
data = {key1:"python training",key2:"other training"}
In [98]:
data
Out[98]:
{'mahal': 'python training', 'smaraka': 'other training'}

Nothing

In [99]:
nothing = None

Try this

In [100]:
"rupali" "rupak"
Out[100]:
'rupalirupak'
In [101]:
pre = "Isac"
post = "Asimov"
In [102]:
pre post
  File "<ipython-input-102-9f3396fba351>", line 1
    pre post
           ^
SyntaxError: invalid syntax

Functions

In [103]:
len(ones)
Out[103]:
4
In [104]:
ones
Out[104]:
[0, 1, 1, 1]
In [105]:
len(sentence)
Out[105]:
80
In [106]:
len(set(sentence))
Out[106]:
22
In [107]:
len(person)
Out[107]:
3
In [108]:
int("5")
Out[108]:
5
In [109]:
int("56")
Out[109]:
56
In [110]:
str(56)
Out[110]:
'56'
In [111]:
str(42.0)
Out[111]:
'42.0'
In [113]:
list(range(10)) 
Out[113]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [114]:
list(range(2,15))
Out[114]:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
In [116]:
list(range(1,10,2)) # start with 1 end before 10 at step of 2
Out[116]:
[1, 3, 5, 7, 9]
In [118]:
list_ = [1,2,3,4] 
In [119]:
list_
Out[119]:
[1, 2, 3, 4]
In [120]:
sum(list_)
Out[120]:
10

problems

  • Using the functionality till now learnt can you find how many digits are there in 2**100
In [121]:
list = [1,2,3]
In [122]:
list(range(10))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-122-fc0d91aa72be> in <module>()
----> 1 list(range(10))

TypeError: 'list' object is not callable
In [123]:
del list
In [124]:
list(range(10))
Out[124]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [125]:
x = 300
In [126]:
len(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-126-e62f33f06233> in <module>()
----> 1 len(x)

TypeError: object of type 'int' has no len()
In [127]:
str(x)
Out[127]:
'300'
In [128]:
len(str(x))
Out[128]:
3
In [129]:
len(str(2**100))
Out[129]:
31
In [130]:
def add(x,y):
    s =  x + y
    return s

def add_(x,y):
    print(x+y)
In [131]:
add(2,3)
Out[131]:
5
In [132]:
add_(2,3)
5
In [133]:
a = add(2,3)
In [134]:
b = add_(2,3)
5
In [135]:
print(a)
5
In [136]:
print(b)
None
In [137]:
def twice(x):
    return 2*x

def twice1(x):
    print(2*x)
In [138]:
twice(twice(5))
Out[138]:
20
In [139]:
twice1(twice1(5))
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-139-15f9e53f7b7f> in <module>()
----> 1 twice1(twice1(5))

<ipython-input-137-3d4ed9845aa2> in twice1(x)
      3 
      4 def twice1(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

problem

  • Write a function count_digits which takes an integer as an argument and returns number of digits in that integer.
    >>> count_digits(300)
    3
    >>> count_digits(2**100)
    31
In [140]:
def count_digits(n):
    return len(str(n))
In [142]:
count_digits(2**1000)
Out[142]:
302

More about functions

In [143]:
def func(x):
    pass
In [144]:
func
Out[144]:
<function __main__.func>
In [145]:
print(func)
<function func at 0x7f563a70e510>
In [146]:
type(func)
Out[146]:
function
In [147]:
def add(x,y):
    return x+y
In [148]:
add
Out[148]:
<function __main__.add>
In [149]:
aliasadd = add
In [150]:
aliasadd
Out[150]:
<function __main__.add>
In [151]:
print(aliasadd)
<function add at 0x7f563a76ef28>
In [152]:
type(aliasadd)
Out[152]:
function
In [153]:
aliasadd(2,3)
Out[153]:
5
In [155]:
def square(x):
    return x*x

def sumofsquares(x,y):
    return square(x) + square(y)

def cube(x):
    return x*x*x

def sumofcubes(x,y):
    return cube(x) + cube(y)

def sumof(f, x, y):
    return f(x) + f(y)
In [156]:
sumofsquares(2,3)
Out[156]:
13
In [157]:
sumof(square, 2, 3)
Out[157]:
13
In [158]:
max([2,5,1,10,300,1,2])
Out[158]:
300
In [159]:
words = ["one","two","three","four","five","six"]
In [160]:
max(words)
Out[160]:
'two'
In [161]:
max(words, key=len)
Out[161]:
'three'
In [162]:
scoresheet = [("A1",2.3),
              ("A2",2.1),
             ("A3",3.0),
             ("A4",2.0),
             ("A5",2.2)]
In [163]:
max(scoresheet)
Out[163]:
('A5', 2.2)
In [164]:
def get_score(record):
    return record[-1]
In [165]:
max(scoresheet, key=get_score)
Out[165]:
('A3', 3.0)
In [166]:
sorted(words)
Out[166]:
['five', 'four', 'one', 'six', 'three', 'two']
In [167]:
max(words)
Out[167]:
'two'
In [168]:
sorted(words, key=len)
Out[168]:
['one', 'two', 'six', 'four', 'five', 'three']
In [169]:
max(words, key=len)
Out[169]:
'three'
In [170]:
sorted(scoresheet)
Out[170]:
[('A1', 2.3), ('A2', 2.1), ('A3', 3.0), ('A4', 2.0), ('A5', 2.2)]
In [171]:
sorted(scoresheet, key=get_score)
Out[171]:
[('A4', 2.0), ('A2', 2.1), ('A5', 2.2), ('A1', 2.3), ('A3', 3.0)]
In [172]:
max(scoresheet, key=get_score)
Out[172]:
('A3', 3.0)
In [173]:
def make_adder(x):
    
    def adder(y):
        return x+y
    
    return adder
In [174]:
adder5 = make_adder(5)
In [175]:
adder5
Out[175]:
<function __main__.make_adder.<locals>.adder>
In [176]:
adder5(6)
Out[176]:
11
In [177]:
adder5(7)
Out[177]:
12
In [178]:
adder4 = make_adder(4)
In [179]:
adder4(10)
Out[179]:
14
In [180]:
f = lambda x,y : x+y
In [181]:
f(2,3)
Out[181]:
5
In [182]:
max(scoresheet, key=lambda r:r[1])
Out[182]:
('A3', 3.0)
In [185]:
def sumof(f, x, y):
    return f(x) + f(y)

sumof(lambda x:x*x, 3,5)
Out[185]:
34
In [184]:
# lambda r:r[1]

def f(r):
    return r[1]

Methods from objects

In [186]:
sentence
Out[186]:
'\nsome words to find out\nhow many english \nalphabetes are used in this \nsentence\n'
In [187]:
sentence.lower()
Out[187]:
'\nsome words to find out\nhow many english \nalphabetes are used in this \nsentence\n'
In [188]:
sentence.upper()
Out[188]:
'\nSOME WORDS TO FIND OUT\nHOW MANY ENGLISH \nALPHABETES ARE USED IN THIS \nSENTENCE\n'
In [189]:
sentence.count("s")
Out[189]:
7
In [190]:
words = sentence.split()
In [191]:
words
Out[191]:
['some',
 'words',
 'to',
 'find',
 'out',
 'how',
 'many',
 'english',
 'alphabetes',
 'are',
 'used',
 'in',
 'this',
 'sentence']
In [192]:
lines = sentence.split("\n")
In [193]:
lines
Out[193]:
['',
 'some words to find out',
 'how many english ',
 'alphabetes are used in this ',
 'sentence',
 '']
In [194]:
book = "Alice in wonderland"
In [195]:
book.split()
Out[195]:
['Alice', 'in', 'wonderland']
In [196]:
"_".join(book.split())
Out[196]:
'Alice_in_wonderland'
In [197]:
"/".join(["","home","vikrant","trainings","2018"])
Out[197]:
'/home/vikrant/trainings/2018'
In [198]:
s = " sdksjkdfh kjdshfkjsdh  kjdhsfkjds \n"
In [199]:
s
Out[199]:
' sdksjkdfh kjdshfkjsdh  kjdhsfkjds \n'
In [200]:
s.strip()
Out[200]:
'sdksjkdfh kjdshfkjsdh  kjdhsfkjds'
In [201]:
book.replace("Alice","Alex")
Out[201]:
'Alex in wonderland'
In [202]:
book.startswith("A")
Out[202]:
True
In [203]:
book.endswith("d")
Out[203]:
True
In [205]:
"hello.py".endswith(".py")
Out[205]:
True
In [206]:
book.center(50)
Out[206]:
'               Alice in wonderland                '
In [207]:
book.rjust(50)
Out[207]:
'                               Alice in wonderland'
In [208]:
book.ljust(50)
Out[208]:
'Alice in wonderland                               '
In [210]:
"3.14".zfill(6)
Out[210]:
'003.14'
In [211]:
"200".zfill(5)
Out[211]:
'00200'
In [212]:
digits = list(range(10))
In [213]:
digits.count(0)
Out[213]:
1
In [214]:
ones
Out[214]:
[0, 1, 1, 1]
In [215]:
ones.count(1)
Out[215]:
3
In [216]:
digits.append(10)
In [217]:
digits
Out[217]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [218]:
digits.pop()
Out[218]:
10
In [219]:
digits
Out[219]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [220]:
digits.insert(0, -1)
In [221]:
digits
Out[221]:
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [222]:
digits.pop(0)
Out[222]:
-1
In [223]:
digits
Out[223]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [224]:
ones.sort()
In [225]:
ones
Out[225]:
[0, 1, 1, 1]
In [226]:
words
Out[226]:
['some',
 'words',
 'to',
 'find',
 'out',
 'how',
 'many',
 'english',
 'alphabetes',
 'are',
 'used',
 'in',
 'this',
 'sentence']
In [227]:
words.sort(key=len)
In [228]:
words
Out[228]:
['to',
 'in',
 'out',
 'how',
 'are',
 'some',
 'find',
 'many',
 'used',
 'this',
 'words',
 'english',
 'sentence',
 'alphabetes']
In [229]:
sorted(words)
Out[229]:
['alphabetes',
 'are',
 'english',
 'find',
 'how',
 'in',
 'many',
 'out',
 'sentence',
 'some',
 'this',
 'to',
 'used',
 'words']
In [230]:
words.reverse()
In [231]:
words
Out[231]:
['alphabetes',
 'sentence',
 'english',
 'words',
 'this',
 'used',
 'many',
 'find',
 'some',
 'are',
 'how',
 'out',
 'in',
 'to']
In [233]:
ones.extend([1,1,1])
In [234]:
ones
Out[234]:
[0, 1, 1, 1, 1, 1, 1]

Tuples

In [235]:
t = (1,2,3)
In [236]:
t.count(1)
Out[236]:
1
In [237]:
t.index(2)
Out[237]:
1
In [238]:
t.append(3)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-238-02e47a15fb03> in <module>()
----> 1 t.append(3)

AttributeError: 'tuple' object has no attribute 'append'

problems

  • Write a function count_zeros which counts zeros from given number
In [239]:
def count_zeros(n):
    return str(n).count("0")
In [240]:
count_zeros(1000)
Out[240]:
3
In [241]:
digits
Out[241]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [242]:
digits[0]
Out[242]:
0
In [243]:
digits[-1]
Out[243]:
9
In [244]:
digits[:2] # take first 2
Out[244]:
[0, 1]
In [245]:
digits[2:] # drop first 2
Out[245]:
[2, 3, 4, 5, 6, 7, 8, 9]

problem

  • Write a function head which takes a sequence and n as an argument. and returns first n elements from the sequence
    >>> head([1,2,3,4,5], 3)
    [1,2,3]
In [246]:
def head(seq, n):
    return seq[:n]

bonus problem

  • Write a function rearrangemax which rearranges digits of given number to from a maximum number of out of it.
    >>> rearrangemax(3472)
    7432
In [247]:
s = "sdsfdsgkdfklhgjf"
In [248]:
s[0]
Out[248]:
's'
In [249]:
len("test")
Out[249]:
4
In [250]:
len([1,2,3])
Out[250]:
3
In [251]:
len((2,3,4,5))
Out[251]:
4
In [252]:
len(b'wetwter')
Out[252]:
7
In [253]:
sorted("hello")
Out[253]:
['e', 'h', 'l', 'l', 'o']
In [254]:
sorted("hello", reverse=True)
Out[254]:
['o', 'l', 'l', 'h', 'e']
In [255]:
n = 3845
In [256]:
strnum = str(n)
In [257]:
sorted(strnum, reverse=True)
Out[257]:
['8', '5', '4', '3']
In [258]:
def rearrangemax(n):
    strnum = str(n)
    sorteddigits = sorted(strnum, reverse=True)
    return int("".join(sorteddigits))
In [259]:
rearrangemax(731894)
Out[259]:
987431
In [260]:
" ".join(["Hello", "world"])
Out[260]:
'Hello world'
In [261]:
"_".join(["Hello", "world"])
Out[261]:
'Hello_world'
In [262]:
"".join(["Hello", "world"])
Out[262]:
'Helloworld'

modules

In [263]:
import os
In [264]:
os
Out[264]:
<module 'os' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/os.py'>
In [265]:
import math
In [266]:
math.pi
Out[266]:
3.141592653589793
In [267]:
math.sin(math.pi/2.0)
Out[267]:
1.0
In [268]:
import math as m
In [269]:
m
Out[269]:
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [270]:
type(m)
Out[270]:
module
In [271]:
type(math)
Out[271]:
module
In [272]:
math.pi
Out[272]:
3.141592653589793
In [273]:
m.pi
Out[273]:
3.141592653589793
In [274]:
m.sin(m.pi/2.0)
Out[274]:
1.0
In [275]:
del math
In [276]:
del m
In [277]:
import math as m
In [278]:
math.pi
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-278-9ee7c101b273> in <module>()
----> 1 math.pi

NameError: name 'math' is not defined
In [279]:
m.pi
Out[279]:
3.141592653589793
In [280]:
from math import sin
In [281]:
sin(m.pi)
Out[281]:
1.2246467991473532e-16
In [282]:
math
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-282-674f3def7873> in <module>()
----> 1 math

NameError: name 'math' is not defined
In [283]:
import os
In [284]:
os.getcwd()
Out[284]:
'/home/vikrant/trainings/2018/vmware-feb-python'
In [286]:
os.listdir(os.getcwd())
Out[286]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'day3.ipynb',
 'day3.html',
 'Makefile',
 'day1.html']
In [288]:
os.getlogin()
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-288-64defab13146> in <module>()
----> 1 os.getlogin()

OSError: [Errno 25] Inappropriate ioctl for device
In [289]:
os.mkdir("/tmp/test")
In [291]:
os.getenv("HOME")
Out[291]:
'/home/vikrant'
In [292]:
os.path.exists("/tmp/test")
Out[292]:
True
In [293]:
os.path.exists("/tmp/test1")
Out[293]:
False
In [294]:
os.path.getsize("day1.html")
Out[294]:
435081

problems

  • Write a function countfiles which counts files in given directory
  • Write a function biggestfile which returns biggest file from given directory.
In [295]:
def countfiles(path):
    return len(os.listdir(path))
In [296]:
countfiles(os.getcwd())
Out[296]:
9
In [297]:
def biggestfile(path):
    files = os.listdir(path)
    return max(files, key=os.path.getsize)
In [298]:
biggestfile(os.getcwd())
Out[298]:
'day1.html'

Custom modules

In [300]:
%%file module.py
"""
This is my first module. and this is
short description of my module
"""

x = 42

def square(x):
    """
    this is description for function square
    """
    return x**2

def say_hello(name):
    """
    this says hello!
    """
    print("Hello", name)
Overwriting module.py
In [301]:
import module
In [302]:
module.x
Out[302]:
42
In [303]:
module.say_hello("Python")
Hello Python
In [304]:
module.square(5)
Out[304]:
25
In [305]:
help(module)
Help on module module:

NAME
    module

DESCRIPTION
    This is my first module. and this is
    short description of my module

FUNCTIONS
    say_hello(name)
        this says hello!
    
    square(x)
        this is description for function square

DATA
    x = 42

FILE
    /home/vikrant/trainings/2018/vmware-feb-python/module.py


In [306]:
!python module.py
In [307]:
%%file module1.py
"""
This is my first module. and this is
short description of my module
"""

import sys

x = 42

def square(x):
    """
    this is description for function square
    """
    return x**2

def say_hello(name):
    """
    this says hello!
    """
    print("Hello", name)
    
print(sys.argv)
Writing module1.py
In [308]:
!python module1.py arg1 argv2 1 2 3 4
['module1.py', 'arg1', 'argv2', '1', '2', '3', '4']

problems

  • Write a python script square.py which squares integer given from commandline
    python square.py 5
    25
  • Write a python script add.py which adds two numbers taken from commandline
    python add.py 2 3
    5
  • Write a python script echo.py which mimics unix command echo
    python echo.py hello this is echo
    hello this is echo
In [309]:
%%file add.py
import sys

def add(x,y):
    return x+y

a = int(sys.argv[1])
b = int(sys.argv[2])
print(add(a,b))
Writing add.py
In [310]:
!python add.py 2 4
6
In [311]:
import add
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-311-3866d3d8e8fb> in <module>()
----> 1 import add

/home/vikrant/trainings/2018/vmware-feb-python/add.py in <module>()
      4     return x+y
      5 
----> 6 a = int(sys.argv[1])
      7 b = int(sys.argv[2])
      8 print(add(a,b))

ValueError: invalid literal for int() with base 10: '-f'
In [314]:
%%file add1.py
import sys

def add(x,y):
    return x+y


print(__name__)
#a = int(sys.argv[1])
#b = int(sys.argv[2])
#print(add(a,b))
Overwriting add1.py
In [315]:
!python add1.py 
__main__
In [316]:
import add1
add1
In [317]:
%%file add2.py
import sys

def add(x,y):
    return x+y


print(__name__)
if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print(add(a,b))
Writing add2.py
In [318]:
!python add2.py 3 4
__main__
7
In [319]:
import add2
add2
In [320]:
add2.add(5,4)
Out[320]:
9
In [321]:
len([1,2,3])
Out[321]:
3
In [322]:
len("hello")
Out[322]:
5
In [323]:
len(4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-323-12bd0409b6df> in <module>()
----> 1 len(4)

TypeError: object of type 'int' has no len()

Conditions

In [324]:
2 == 2
Out[324]:
True
In [325]:
2 != 3
Out[325]:
True
In [326]:
"alice" in "alice in wornderland"
Out[326]:
True
In [327]:
"alice" in "Alice in Wonderland".lower()
Out[327]:
True
In [328]:
person
Out[328]:
{'country': 'UK', 'email': 'alice@wonder.land', 'name': 'alice'}
In [329]:
"email" in person
Out[329]:
True
In [330]:
"lastname" in person
Out[330]:
False
In [331]:
"alice" in person.values()
Out[331]:
True
In [332]:
"alex" in ["alice","elsa","alex"]
Out[332]:
True
In [333]:
"alice" not in "Hello world!"
Out[333]:
True
In [334]:
name = "alice"
In [335]:
name == "alice"
Out[335]:
True
In [336]:
name is "alice"
Out[336]:
True
In [337]:
x = [1,2,3]
y = [1,2,3]
In [338]:
x == y
Out[338]:
True
In [339]:
x is y
Out[339]:
False
In [340]:
a = 2
b = 2
In [341]:
a is a
Out[341]:
True
In [342]:
int('1') == int('1')
Out[342]:
True
In [343]:
int('1') is int('1')
Out[343]:
True
In [344]:
t = (1,2,3)
t2 = (1,2,3)
In [345]:
t is t2
Out[345]:
False
In [346]:
"alice in wonnderland".endswith("land")
Out[346]:
True
In [347]:
emptystr = ""
In [348]:
emptylst = []
In [349]:
nothing = None
In [350]:
emptydict = {}

All these empty collections are False in if condition

In [351]:
if "python" in ["python","java","haskell","ark","lisp"]:
    print("python is there in languages")
elif version > 3.6:
    pass
elif some_cond:
    pass
elif one_more_cond:
    pass
else:
    print("If none is satisfied .. you come here")
python is there in languages
In [352]:
if "python" > "c++":
    print("Its higher level!")
Its higher level!
In [353]:
"python" > "c++"
Out[353]:
True

problem

  • Write a function filetype which returns file types as shown in the table, depending on extension
    extention    filetype
    .py          python
    .java        java
    .txt         text
    .hs          haskell
    otherwise    unknown
  • Write a function minimum2 which find minumum number from given two numbers.(do not use in built function min)
  • Write a function minimum3 which finds minimum of given 3 numbers.
In [354]:
def minimum2(x,y):
    if x < y:
        return x
    else:
        return y
    
def minimum3(x,y,z):
    a = minimum2(x,y)
    b = minimum2(a,z)
    return b

while loop

In [355]:
x , y, = 1,2
In [356]:
x
Out[356]:
1
In [357]:
y
Out[357]:
2
In [364]:
def print_fibonaci(n):
    """
    prints fibionacci numbers less than n
    """
    current, prev = 1, 0
    
    while prev < n:
        print(prev, end=" ")
        current, prev = prev+current, current
       
In [365]:
print_fibonaci(100)
0 1 1 2 3 5 8 13 21 34 55 89 
In [366]:
2 <= 3
Out[366]:
True
In [367]:
2.0 <= 2 or 1==1
Out[367]:
True

Advanced problems problems given below might have different difficulty level. choose whichever to solve depending on your comfort level.

  • Find sum of first 20 fibinacci numbers.

  • Given a number its' digits can be rearranged to form maximum number and minimum number. take difference of maximum and minimum. You get a new number. On this number repeate the procedure for some number of iterations. We call this as kaprekar iteration. Write a function kaprekar which will do kaprekar itaretion for given number iterations on given integer. your function should work something like this

    >>> kaprekar(5674, iterations=50)
    6174
  • In card game we do riffleshuffle. see https://www.wikihow.com/Riffle-and-Bridge-Shuffle for how to do riffleshuffle. Assume that riffleshuffle is perfect. Write a function riffleshuffle which does riffleshuffle similar to card deck on a list. it returns a new list with riffled shuffled. If you repeate riffleshuffle do you see that list comes back to original form after some time. write another function to repeate riffleshuffle as many times as you tell. for example repeat_riffle([1,2,3,4,5,6],5) will riffleshuffle given list five times.

  • A number x is called as fixed point of a function if x satisfies the equation f(x)=x. For some function f we can locate fixed point by beginning initial guess and applying f repeatedly, f(x), f(f(x)), f(f(f(x))), f(f(f(f(x)))).... Write a function to find fixed point of a function. what is fixed point of sin(x) + cos(x)?

  • Write a function to generate all anagrams of a given word. Words are said to be anagrams if they consists of same alphabets but in different order. for example deposit,dopiest,posited,topside are examples of anagrams. hint:use itertools.permutaions

  • Given set of words, classify the words with anagrams in same class.
In [ ]: