by Vikrant Patil
at MIT Pune, IT Dept. Mar 12-16, 2018
Notes are available online at
__main__¶%%file hello1.py
import sys
def say_hello(name):
print("Hello", name)
say_hello(sys.argv[1])
!python hello1.py MIT
import hello1
%%file square.py
import sys
def square(x):
return x*x
print(square(int(sys.argv[1])))
!python square.py 3
import square
def f():
pass
%%file main.py
print(__name__)
!python main.py
import main
%%file module2.py
print(__name__)
!python module2.py
import module2
%%file square1.py
import sys
def square(x):
return x*x
if __name__ == "__main__":
print(square(int(sys.argv[1])))
!python square1.py 5
import square1
problem
!echo hello python training at MIT pune
words = ["one", "two", "three", "four"]
"_".join(words)
" ".join(words)
words = ["one", "two", "three", "four", "five"]
" ".join(words)
import sys
sys.argv
" ".join(sys.argv[1:])
%%file echo.py
import sys
if __name__ == "__main__":
print(" ".join(sys.argv[1:]))
!python echo.py hello at Python foundation course at MIT pune
2 == 3
2 != 3
2 <= 2.0
1.99 > 2
1.99 >= 2
2 < 2.0
book = "Alice in wonderland"
"Alice" in book
"Alex" not in book
book.endswith("land")
book.startswith("Alice")
book.split()[0] is "Alice"
name = "Alice"
name is "Alice"
name == "Alice"
primes = [2,3,5,7]
2 in primes
2 not in primes
2 not in primes or 5 in primes
name is "Alice" and 2 in primes
primes1 = [2,3,5,7]
primes == primes1
primes is primes1
person = {"name":"alice", "email":"alice@wonder.land"}
"name" in person
"alice" in person
"alice" in person.values()
emptylist = []
emptystring = ""
emptydict = {}
nothing = None
#if emptylist: # this is False condition
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
if name is "Alice":
print("Yes name is alice")
2 if name is "Alice" else 3
problems
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
minimum2 which returns minimum of given two numbers.(do not use built in min)minimum3 which returns minimum of given three numbers."hello.py".split(".")
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"
filetype("hello.py")
filetype("xyz.tar.gz")
filetype("hello.java.py")
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]
"xyz.tar.gz".split(".")[-1]
def minimum2(x,y):
if x<y:
return x
else:
return y
def minimum3(x,y,z):
return minimum2(minimum2(x,y),z)
minimum3(5,6,1)
x,y = 1,2
x
y
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=",")
print_fibonacci(100)
for number in [1,2,3,4]:
print(number)
for char in "This is a string":
print(char)
for c in (255,0,230):
print(c, end=" ")
for n in range(5):
print(n)
for key in person:
print(key, person[key])
for item in set([1,1,2,2,1,43,1,2,3,1,2]):
print(item, end=",")
for i in range(10):
print(i, end=",")
for i in range(0,10,2):
print(i, end=",")
problems
python ls.py /tmp
config-err-7IDenG
mintUpdate
ssh-tBJL6P3COpiT
systemd-private-88ddcccd84d04fb0bfc528826826ab5e-colord.service-7vJkKP
systemd-private-88ddcccd84d04fb0bfc528826826ab5e-rtkit-daemon.service-IEZqa7
%%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())
!python ls.py /tmp
There are break and continue statements for loops.
but there is also else block for for loop
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=",")
print_primes(100)
Recap list methods
l = [1,1,1,1,0,0]
l.append(1)
l
l.insert(0, -1)
l
l.pop()
l
l.pop(0)
l
problems
mysum to sum elements from a list>>> mysum([1,1,1,1]
4
product to find product of all elements from list>>> product([1,2,3,4])
24
factorial to find factorial of n>>> factorial(4)
24
for i in [1,2,3,4,5]:
print(i)
def mysum(items):
s = 0
for item in items:
s += item
return s
mysum([1,2,3,4])
"one" + "_" + "two"
def mysum(items):
s = items[0]
for item in items[1:]:
s += item
return s
mysum(["a","b","c","d"])
mysum(range(10))
def product(numbers):
p = numbers[0]
for n in numbers:
p = p*n
return p
product([1,2,3,4])
def factorial(n):
return product(range(1,n+1))
factorial(4)
numbers = list(range(1,11))
twice = []
for n in numbers:
twice.append(2*n)
twice
numbers
def convert(item):
return str(item)
converted = []
for n in numbers:
converted.append(convert(n))
converted
problem
squarelist which squares every item from a listevens which will find out even numbers from given listdef squarelist(items):
sqrl = []
for n in items:
sqrl.append(n*n)
return sqrl
squarelist(range(10))
def evens(numbers):
e = []
for n in numbers:
if n%2==0:
e.append(n)
return e
evens(range(20))
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
primes[2:7] # start at index 2 end at index 7 (exlude)
primes[2:10:3] # start at index 2 end at index 10 (exlude) at step of 3
primes[2:10] # if step is not given it is taken as 1
primes[:10] # default start is 0
primes[10:] # default end is at last index
primes[:]
primes[:-1]
primes[:-2]
primes
p = primes[:-1]
primes
p
primes[::-1]
word = "madam"
def is_palindrom(w):
return w==w[::-1]
is_palindrom(word)
palindrom = lambda w: w==w[::-1]
palindrom("madam")
def f(x):
return x, 2*x
f(3)
problem
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")
def split_at(seq, n):
return seq[:n],seq[n:]
[n*n for n in range(10)]
[2*n for n in range(10)]
words
[w.upper() for w in words]
s = []
for i in range(10):
s.append(i*i)
s
[i*i for i in range(10)]
[i for i in primes]
[i for i in range(10) if i%2==0]
e = [i for i in range(10) if i%2==0]
e
o = [i for i in range(10) if i%2!=0]
o
[[i for i in range(1,6)] for j in range(1,11)]
[[i*j for i in range(1,6)] for j in range(1,11)]
t = [[i*j for i in range(1,6)] for j in range(1,11)]
t
problems
listpy to get python files from given directory.
>>> listpy(os.getcwd())
["echo.py","hello.py","main.py"]
factors which finds all factors of given number.>>> factors(5)
[1,5]
>>> factors(6)
[1,2,3,6]
is_prime which tells if given number is prime or not based on fact that prime number has only 2 factors , 1 and self1 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
sum([1,1,1,1])
import os
def listpy(path):
files = os.listdir(path)
return [file for file in files if file.endswith(".py")]
listpy(".")
def factors(n):
return [i for i in range(1,n+1) if n%i==0]
factors(10)
def is_prime(p):
return factors(p)==[1,p]
def primes(n):
return [p for p in range(2,n) if is_prime(p)]
primes(50)
[[i+j for i in range(5)] for j in range(5)]
[[i==j for i in range(5)] for j in range(5)]
[[int(i==j) for i in range(5)] for j in range(5)]
def f(i,j):
if i==j:
return 1
else:
return 0
[[f(i,j) for i in range(5)] for j in range(5)]
d = {True:1,False:0}
[[d[i==j] for i in range(5)] for j in range(5)]
[[1 if i==j else 0 for i in range(5)] for j in range(5)]
sum([i for i in range(1000) if i%7==0 or i%11==0])
t
t[0]
t[-1]
t[0][-1]
def column(data, colnum):
numrows = len(data)
return [t[r][colnum] for r in range(numrows)]
column(t, 0)
t
column(t, 1)
def transpose(data):
numcols = len(data[0])
return [column(data, i) for i in range(numcols)]
transpose(t)
t
def rotate90clockwise(data):
numcols = len(data[0])
return [column(data, i)[::-1] for i in range(numcols)]
rotate90clockwise(t)
words
for word in words:
print(word)
for word in reversed(words):
print(word)
for index, value in enumerate(words):
print(index, value)
for i in range(len(words)): # not recommanded
print(i, words[i])
first =["Elsa","Elisa","Nurd","David"]
last = ["Frozen", "Hacker", "Beauty", "Beazly"]
for f,l in zip(first, last):
print(f,l)
for i,j,k in zip(range(5), words, [1,1,1,1,1]):
print(i,j,k)
problem
vector_add which does vector addition of two listsa = [1,2,3,4]
b = [3,4,5,6]
def vector_add(v1,v2):
return [i+j for i,j in zip(v1,v2)]
vector_add(a,b)
for i in range(1,11):
print(i, i*i, i*i*i)
for i in range(1,11):
print(str(i).rjust(2), str(i*i).rjust(3), str(i*i*i).rjust(4))
"Wizard of {} is in {}".format("python", "oz")
"Wizard of {1} is {0}".format("python","oz")
"Wizard of {name} is in {place}".format(name="python", place="oz")
for i in range(1,11):
print(" {integer} {square} {cube}".format(integer=i,square=i*i,cube=i*i*i))
for i in range(1,11):
print(" {integer:2d} {square:3d} {cube:4d}".format(integer=i,
square=i*i,
cube=i*i*i))
problem
>>> pascal(4)
[[1],[1,1],[1,2,1],[1,3,3,1]]
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