March 5-7, 2019 Vikrant Patil
These notes are available online at http://notes.pipal.in/2019/pccoe_basic/day2.html
© Pipal Academy LLP
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
yes = True
filename = "hello.py"
filename.endswith(".py")
if filename.endswith(".py"):
print("Python file")
else:
print("other")
def filetype(filename):
if filename.endswith(".py"):
return "python"
else:
return "Unknown"
filetype("square.py")
filetype("windows.exe")
def filetype_(filename):
if filename.endswith(".py"):
return "python"
elif filename.endswith(".exe"):
return "executable"
elif filename.endswith(".hs"):
return "haskell"
elif filename.endswith(".doc"):
return "word"
elif filename.endswith(".xls"):
return "excel"
else:
return "Unknown"
filetype_("test.xls")
languages = ["python", "c", "c++", "lisp", "javascript"]
"python" in languages
"english" in languages
person = {"name":"Alice","age":13,"country":"wonderland"}
"name" in person
"language" in person
"country" in person
s = "Answer to every question of life is 42"
"Answer" in s
"42" in s
"Question" in s
"42" in s and "haskell" in languages
"english" in languages or "life" in s
2 == 2
2 ==3
2 <= 3
2 < 3
2 != 3
def even(n):
return n%2==0
even(4)
even(7)
def odd(n):
return not even(n)
problem
Write a function minimum2 which finds minimum of given two numbers x,y.
Write a function minimum3 which finds minimum of given three number x, y, z
def minimum2(x,y):
if x < y:
return x
else:
return y
def minimum3(x,y,z):
t = minimum2(x,y)
return minimum2(t, z)
%%file square.py
import sys
def square(x):
return x*x
x = float(sys.argv[1])
print(square(x))
!python square.py 5.6
import square
%%file square1.py
import sys
def square(x):
return x*x
if __name__=="__main__":
x = float(sys.argv[1])
print(square(x))
!python square1.py 4.4
import square1
square1.square(4.5)
%%file square2.py
import sys
def square(x):
return x*x
print(__name__)
if __name__=="__main__":
x = float(sys.argv[1])
print(square(x))
!python square2.py 5.6
import square2
import time
x = 10
while x > 0:
print("T-", x)
x = x -1 # x -= 1
time.sleep(1)
x, y = 2, 3
x
y
def print_fibonacci(n):
curr , prev = 1, 0
while curr <= n:
print(curr, end=",")
curr, prev = prev+curr, curr
print_fibonacci(100)
fibs = [1,1,2,3,5,8,13,21,34,55,89]
for number in fibs:
print(number, end=",")
for number in fibs:
print(number**2, end=",")
for c in "this is some string":
print(c, end=" ")
points = [(0,0), (2,3), (1,1), (3,4)]
for p in points:
print(p)
classroom = {"ankit":12, "ankita":34, "anshul":2, "akash":5}
for student in classroom:
print(student, classroom[student])
for student, num in classroom.items():
print(student, num)
for num in classroom.values():
print(num)
for i in range(10):
print(i, end=",")
for i in range(3, 20, 3):
print(i, end=",")
problems
mysum to find sum of all numbers from given listproduct to find product of all numbers from given listfactorial to find factorial of given number.def mysum(numbers):
s = 0
for i in numbers:
s = s + i
return s
mysum([1,2,3,4])
nums = [1,1,4,9,25,64,169,441,1156,3025,7921]
mysum(nums)
def product(nums):
p = 1
for item in nums:
p = p*item
return p
product([2,3,4,5])
def factorial(n):
return product(range(1, n+1))
factorial(5)
fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
fibs
fibs[0]
fibs[-1]
fibs[2:4] #from 2nd index till 4th (excluding)
fibs[1:5]
fibs[1:] # drop 1
fibs[2:] # drop 2
fibs[:2]
fibs[:6]
fibs
fibs[2:7:2]
x = [1,1,1]
y = x
x.append(0)
x
y
z = fibs[:]
z
fibs
z.append(-1)
z
fibs
x = [1,1,1]
y = [1,1,1]
x == y
x is y
z = x
z is x
filename
filename = "hello.py"
xlsfile = "hello.xls"
xlsfile.split(".")
targz = "data.tar.gz"
targz.split(".")
def findextension(filename):
return filename.split(".")[-1]
findextension(targz)
findextension(xlsfile)
findextension("hello.py")
fibs[:]
fibs[::2]
fibs[::-1]
word = "madam"
def isPalindrome(w):
return w == w[::-1]
isPalindrome("madam")
isPalindrome("hello")
isPalindrome("121")
len(fibs)
fibs[100]
fibs[1:100]
empty = []
empty.append(1)
empty
square every item in a list
def squarelist(numbers):
sqr = []
for n in numbers:
s = n*n
sqr.append(s)
return sqr
squarelist(fibs)
squarelist(range(10))
fibs
def even(n):
return n%2==0
def evens(numbers):
e = []
for item in numbers:
if even(item):
e.append(item)
return e
evens(fibs)
import random
help(random.random)
random.random()
numbers = [ random.random() for i in range(10)]
numbers
sqr = [n*n for n in numbers]
sqr
randomints = [int(10*random.random()) for i in range(10)]
randomints
[n*n for n in randomints]
[n for n in randomints if n%2==0]
[n for n in randomints if n%2==1]
[n for n in randomints if even(n)]
def func(x):
return x*x + 2*x + 1
from matplotlib.pyplot import plot
plot([func(i) for i in range(100)])
%matplotlib inline
problems
listpy to find list of all python files from given directory
>>> listpy(os.getcwd())
['square.py', 'square1.py'...]
mtable to generate multiplication table of n
>>> mtable(3)
[3,6,9,....30]
[i for i in randomints if i%2==0]
words = ["Hello", "Hi", "How", "When", "Why", "What"]
[w for w in words if w.startswith("H")] ##words starting with "H"
words = ["Hello", "Hi", "How", "hoooo", "When", "Why", "What"]
[w for w in words if w.lower().startswith("h")]
#words starting with h , case insensitive
def listpy(path):
files = os.listdir(path)
return [f for f in files if f.endswith(".py")]
def mtable(n):
return [i*n for i in range(1, 11)]
mtable(5)
for n in mtable(5):
print(n)
tables = [mtable(i) for i in range(1,6)]
tables
x = [[1,2], ["a","b"]]
len(x)
x[0]
x[1]
x[0][0]
x[1][0]
tables
tables[0]
tables[1]
tables[4]
tables[1][0]
tables[1][1]
tables[1][2]
tables[0][1]
tables[1][1]
tables[2][1]
[tables[i][3] for i in range(5)]
def column(data, n):
return [data[i][n] for i in range(len(data))]
column(tables, 0)
column(tables, 4)
tables
def transpose(data):
cols = len(data[0])
return [column(data, i) for i in range(cols)]
transpose(tables)
problems
factors to find all factors of given number.
>>> factors(6)
[1,2,3,6]
>>> factors(5)
[1,5]
is_prime to find if given number is prime number or not. make use of fact that a prime number has only two factors, itself and 1!def factors(n):
return [i for i in range(1, n+1) if n%i==0]
def is_prime(n):
return factors(n)==[1,n]
def primes(n):
return [p for p in range(1,n) if is_prime(p)]
primes(50)
p = primes(20)
p
for i in p:
print(i, end=",")
for i in reversed(p): #should be used only in for loop
print(i, end=",")
p[::-1]
for index, num in enumerate(p): #should be used only in loop
print(index, num)
first = ["Elsa", "David", "Alice"]
lastname = ["Frozen", "Hacker", "Wonder"]
for name, surname in zip(first, lastname):
print(name, surname)
z = zip(first, lastname)
z
rp = reversed(p)
for i in p:
print(i, end=",")
for i in rp:
print(i, end=",")
for i in p:
print(i, end=",")
for i in rp:
print(i, end=",")
x,y = (2,3)
x
y
x,y = [4,5]
x
y
for x,y,z in zip(range(10), range(10), range(10)):
print(x,y,z)
list(zip(range(5), ["one","two","three","four","five"]))
s = "Wizard of oz is {} and can do {}"
s.format("python", "computation")
"Wizard of oz is {1} and can do {0}".format("python", "pccoe student")
"Wizard of oz is {person} and can do {task}".format(person="python", task="computation")
for i in range(1,11):
print(i, i*i, i*i*i)
for i in range(1,11):
line = "{:2d} {:3d} {:4d}".format(i, i*i, i*i*i)
print(line)
ans = "Answer is 42"
ans.ljust(30)
ans.rjust(30)
ans.center(30)
problem
print_triangle which will print a triangle of * of base n.
>>> print_triangle(5)
*
* *
* * *
* * * *
* * * * *
Take home assignment
pascal to generate pascal traingle as a 2D list.
>>> pascal(4)
[[1],[1,1],[1,2,1],[1,3,3,1]]
print_pascal to print pascal triangle of base n.
>>> print_pascal(4)
1
1 1
1 2 1
1 3 3 1
`
dirtree to generate tree structure of directory
>>> dirtree(os.getcwd())
.
├── day1.html
├── day1.ipynb
├── day2.html
├── day2.ipynb
├── hello.py
├── helloworld.py
├── Makefile
├── push
├── __pycache__
│ ├── square1.cpython-37.pyc
│ ├── square2.cpython-37.pyc
│ └── square.cpython-37.pyc
├── python_basic
│ └── Untitled.ipynb
├── square1.py
├── square2.py
└── square.py
"*"*5
mtable("*")