Feb 26-28, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-feb-python
© Pipal Academy LLP
We will be using anaconda (python 3.6) for this training. It can be downloaded at
2 + 3
print("Hello World!")
name = input()
print(name)
2 + 3
2 - 3
5 / 2
5 // 2
2 ** 5
2 * 5
2 ** 1000
It obviously has floats
2.0 ** 3
2 - 3.0
It has strings
first = "Rupali"
last = "Rupak"
print(first)
single = "have a string with ' qoute inside"
print(single)
double = 'a string with " quote inside'
print
print(double)
"hello \' world!"
multi = """
this is a
multi line
string with
five lines
in it
"""
print(multi)
multi
regional = "आ क"
regional
"\u0c85"
empty = ""
There is binary data
binary = b'this is text converted to binary data'
print(binary)
type(binary)
b = b"\x023\x065"
type(b)
first + last
star = "*"
print(star*20)
first[0]
first[1]
Lists
x = [1, 2, 3, 4]
x[0]
x[-1]
mixed = [1,1,1,"A","B","C"]
mixed
list2d = [[1,1,1],[0,0,0],"A"]
list2d[0]
list2d[1]
list2d[2]
emptylist = []
ones = [1,1,1,1]
moreones = ones + ones
moreones
ones * 5
ones
tuples are siblings of lists
t = (0,0,1)
t[0]
t[-1]
t + t
t * 5
ones[0] = 0
ones
t[0] = 1
t
t[-1]
empty = []
dictionaries
person = {"name":"alice","email":"alice@wonder.land","country":"UK"}
person["name"]
person["email"]
person["country"]
empty = {}
empty["key1"] = "value1"
empty["key2"] = "value2"
empty
data = {1:"one",2:"two",3:"three"}
data[1]
data[2]
data[3]
unhashable = {[1,2,3]:"list",2:"two"}
hashable = {(1,2,3):"t",2:"two"}
hashable
hashable[(1,2,3)]
hashable[3]
sets
sentence = """
some words to find out
how many english
alphabetes are used in this
sentence
"""
set(sentence)
Boolean
arr = False
ok = True
data = {True:"True",False:"Error"}
data[True]
data[False]
key1 = "mahal"
key2 = "smaraka"
data = {key1:"python training",key2:"other training"}
data
Nothing
nothing = None
"rupali" "rupak"
pre = "Isac"
post = "Asimov"
pre post
len(ones)
ones
len(sentence)
len(set(sentence))
len(person)
int("5")
int("56")
str(56)
str(42.0)
list(range(10))
list(range(2,15))
list(range(1,10,2)) # start with 1 end before 10 at step of 2
list_ = [1,2,3,4]
list_
sum(list_)
problems
list = [1,2,3]
list(range(10))
del list
list(range(10))
x = 300
len(x)
str(x)
len(str(x))
len(str(2**100))
def add(x,y):
s = x + y
return s
def add_(x,y):
print(x+y)
add(2,3)
add_(2,3)
a = add(2,3)
b = add_(2,3)
print(a)
print(b)
def twice(x):
return 2*x
def twice1(x):
print(2*x)
twice(twice(5))
twice1(twice1(5))
problem
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
def count_digits(n):
return len(str(n))
count_digits(2**1000)
def func(x):
pass
func
print(func)
type(func)
def add(x,y):
return x+y
add
aliasadd = add
aliasadd
print(aliasadd)
type(aliasadd)
aliasadd(2,3)
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)
sumofsquares(2,3)
sumof(square, 2, 3)
max([2,5,1,10,300,1,2])
words = ["one","two","three","four","five","six"]
max(words)
max(words, key=len)
scoresheet = [("A1",2.3),
("A2",2.1),
("A3",3.0),
("A4",2.0),
("A5",2.2)]
max(scoresheet)
def get_score(record):
return record[-1]
max(scoresheet, key=get_score)
sorted(words)
max(words)
sorted(words, key=len)
max(words, key=len)
sorted(scoresheet)
sorted(scoresheet, key=get_score)
max(scoresheet, key=get_score)
def make_adder(x):
def adder(y):
return x+y
return adder
adder5 = make_adder(5)
adder5
adder5(6)
adder5(7)
adder4 = make_adder(4)
adder4(10)
f = lambda x,y : x+y
f(2,3)
max(scoresheet, key=lambda r:r[1])
def sumof(f, x, y):
return f(x) + f(y)
sumof(lambda x:x*x, 3,5)
# lambda r:r[1]
def f(r):
return r[1]
sentence
sentence.lower()
sentence.upper()
sentence.count("s")
words = sentence.split()
words
lines = sentence.split("\n")
lines
book = "Alice in wonderland"
book.split()
"_".join(book.split())
"/".join(["","home","vikrant","trainings","2018"])
s = " sdksjkdfh kjdshfkjsdh kjdhsfkjds \n"
s
s.strip()
book.replace("Alice","Alex")
book.startswith("A")
book.endswith("d")
"hello.py".endswith(".py")
book.center(50)
book.rjust(50)
book.ljust(50)
"3.14".zfill(6)
"200".zfill(5)
digits = list(range(10))
digits.count(0)
ones
ones.count(1)
digits.append(10)
digits
digits.pop()
digits
digits.insert(0, -1)
digits
digits.pop(0)
digits
ones.sort()
ones
words
words.sort(key=len)
words
sorted(words)
words.reverse()
words
ones.extend([1,1,1])
ones
Tuples
t = (1,2,3)
t.count(1)
t.index(2)
t.append(3)
problems
count_zeros which counts zeros from given numberdef count_zeros(n):
return str(n).count("0")
count_zeros(1000)
digits
digits[0]
digits[-1]
digits[:2] # take first 2
digits[2:] # drop first 2
problem
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]
def head(seq, n):
return seq[:n]
bonus problem
rearrangemax which rearranges digits of given number to from a maximum number of out of it.
>>> rearrangemax(3472)
7432
s = "sdsfdsgkdfklhgjf"
s[0]
len("test")
len([1,2,3])
len((2,3,4,5))
len(b'wetwter')
sorted("hello")
sorted("hello", reverse=True)
n = 3845
strnum = str(n)
sorted(strnum, reverse=True)
def rearrangemax(n):
strnum = str(n)
sorteddigits = sorted(strnum, reverse=True)
return int("".join(sorteddigits))
rearrangemax(731894)
" ".join(["Hello", "world"])
"_".join(["Hello", "world"])
"".join(["Hello", "world"])
import os
os
import math
math.pi
math.sin(math.pi/2.0)
import math as m
m
type(m)
type(math)
math.pi
m.pi
m.sin(m.pi/2.0)
del math
del m
import math as m
math.pi
m.pi
from math import sin
sin(m.pi)
math
import os
os.getcwd()
os.listdir(os.getcwd())
os.getlogin()
os.mkdir("/tmp/test")
os.getenv("HOME")
os.path.exists("/tmp/test")
os.path.exists("/tmp/test1")
os.path.getsize("day1.html")
problems
countfiles which counts files in given directorybiggestfile which returns biggest file from given directory.def countfiles(path):
return len(os.listdir(path))
countfiles(os.getcwd())
def biggestfile(path):
files = os.listdir(path)
return max(files, key=os.path.getsize)
biggestfile(os.getcwd())
%%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)
import module
module.x
module.say_hello("Python")
module.square(5)
help(module)
!python module.py
%%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)
!python module1.py arg1 argv2 1 2 3 4
problems
square.py which squares integer given from commandline
python square.py 5
25
add.py which adds two numbers taken from commandline
python add.py 2 3
5
echo.py which mimics unix command echo
python echo.py hello this is echo
hello this is echo
%%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))
!python add.py 2 4
import add
%%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))
!python add1.py
import add1
%%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))
!python add2.py 3 4
import add2
add2.add(5,4)
len([1,2,3])
len("hello")
len(4)
2 == 2
2 != 3
"alice" in "alice in wornderland"
"alice" in "Alice in Wonderland".lower()
person
"email" in person
"lastname" in person
"alice" in person.values()
"alex" in ["alice","elsa","alex"]
"alice" not in "Hello world!"
name = "alice"
name == "alice"
name is "alice"
x = [1,2,3]
y = [1,2,3]
x == y
x is y
a = 2
b = 2
a is a
int('1') == int('1')
int('1') is int('1')
t = (1,2,3)
t2 = (1,2,3)
t is t2
"alice in wonnderland".endswith("land")
emptystr = ""
emptylst = []
nothing = None
emptydict = {}
All these empty collections are False in if condition
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")
if "python" > "c++":
print("Its higher level!")
"python" > "c++"
problem
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
minimum2 which find minumum number from given two numbers.(do not use in built function min)minimum3 which finds minimum of given 3 numbers.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
x , y, = 1,2
x
y
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
print_fibonaci(100)
2 <= 3
2.0 <= 2 or 1==1
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