Nov 26-30, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/arcesium-basic-nov/day3.html
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from
%%file foo.py
def bar():
print("foobar!")
bar()
import foo
%%file backup.py
def download_email():
print("downloading email!")
def copy_new_delete_old(new, old):
print("copying new and deleting old ones")
def backup():
download_email()
#....(
#...
src = "src"
dest = "dest"
copy_new_delete_old(src, dest)
print(__name__)
#backup()
import backup
!python backup.py
%%file backup1.py
def download_email():
print("downloading email!")
def copy_new_delete_old(new, old):
print("copying new and deleting old ones")
def backup():
download_email()
#....(
#...
src = "src"
dest = "dest"
copy_new_delete_old(src, dest)
if __name__ == "__main__":
backup()
!python backup1.py
import backup1
def sumofsquares(x,y):
return square(x) + square(y)
sumofsquares(3,4)
def square(x):
return x*x
sumofsquares(4,5)
def square(x):
return x*x
def sumofsquares(x,y):
return square(x) + square(y)
def sumofcubes(x,y):
def cube(x):
return x**3
return cube(x) + cube(y)
sumofcubes(2, 3)
square(4)
cube(4)
sumofcubes(4,5)
%%file square.py
import sys
def square(x):
return x*x
if __name__ == "__main__":
a = float(sys.argv[1])
print(square(a))
!python square.py 6
import square
square.square(34)
%%file square1.py
def square(x):
return x*x
print(square(3))
!python square1.py 5
import square1
%%file square2.py
import sys
def square(x):
return x*x
print(square(float(sys.argv[1])))
!python square2.py 6
import square2
def evens(n):
i = 0
while i <= n:
if i%2 == 0:
print(i)
i = i + 1
#i += 1
evens(10)
def evens(n):
i = 0
while i <= n:
if i%2 == 0:
print(i, end=" ")
i = i + 1
#i +=
evens(20)
def odds(n):
while j <= n:
if j%2 == 1:
print(j, end=" ")
j = j + 1
#i +=
odds(10)
from math import pi
pi
pi = 5
pi
import math
math.pi
a = 3
def fun(x):
return x+a
fun(2)
def foo():
a = 7
foo()
a
a = 42
fun(2)
j = 10
def odds(n):
global j
while j <= n:
if j%2 == 1:
print(j, end=" ")
j = j + 1
#i +=
odds(30)
print(j)
def odds(n):
i = 0
while True:
if i%2 == 1:
print(i)
if i == n:
break
i = i + 1
odds(10)
import time
while True:
time.sleep(2)
print("hello")
numbers = [1,2,3,4,5,6,7]
for num in numbers:
print(num,end=",")
numbers
x in numbers
for x in numbers:
x2 = 2*x
print(x2, end=",")
for word in ["one","two","three","four"]:
print(word)
for c in "This is a string for testing for loop":
print(c, end=",")
for item in {"x":1,"y":2, "z":3}:
print(item)
d = {"x":1,"y":2, "z":3}
for item in d :
print(item, d[item])
s = "This is a string for testing for loop"
for word in s.split():
print(word, end=",")
empty= []
def twicelist(numbers):
twice = []
for n in numbers:
twice.append(2*n)
return twice
twicelist([1,4,2,3,1,2])
def twice_half_list(numbers):
size = len(numbers)
return twicelist(numbers[:size//2])
twice_half_list([1,2,3,4,5,6,7,8])
problem
>>> convert_float(['1','2','3','4'])
[1.0,2.0,3.0,4.0]
s = "2.3"
s
s/2
float(s)/2
problem
%%file add.py
import sys
def convert_float(strnums):
nums = []
for s in strnums:
nums.append(float(s))
return nums
if __name__ == "__main__":
numbers = convert_float(sys.argv[1:])
print(sum(numbers))
!python add.py 1 2 3 4 5 -6
def minimum(x,y):
if x < y:
return x
else:
return y
def minimum3(x,y,z):
m = minimum(x,y)
return minimum(z, m)
minimum3(1,2,5)
def minimum3_(x,y,z):
if x < y:
if x < z:
return x
else:
return z
else:
if y < z:
return y
else:
return z
def even(x):
return x%2==0
def square_evens(numbers):
sqrs = []
for n in numbers:
if even(n):
sqrs.append(n*n)
return sqrs
square_evens(range(20))
for item in seq:
do(item) => [do(item) for item in seq]
for item in seq:
if cond:
do(item) => [do(item) for item in seq if cond]
sq = []
for i in range(10):
sq.append(i*i)
[i*i for i in range(10)]
sq = []
for i in range(10):
if even(i):
sq.append(i*i)
sq
[i*i for i in range(10) if even(i)]
digits = list(range(10))
[i*i for i in digits[::3]]
x = [i*i for i in digits]
x
problems Write lists comprehensions for following
numbers = [1,3,2,5,3,4,8,12,8,10]
[ i for i in numbers if even(i)]
import os
def list_files(dirpath):
files = os.listdir(dirpath)
return [f for f in files if os.path.isfile(os.path.join(dirpath, f))]
binfiles = list_files("/bin/")
len(binfiles)
os.path.isfile("echo")
os.path.isfile("/bin/echo")
binfiles[:3]
sum([i for i in range(1000) if i%7==1 or i%11==1])
bonus problem
>>> factors(10)
[1,2,5,10]
>>> is_prime(5)
True
def factors(n):
return [i for i in range(1, n+1) if n%i==0]
factors(8)
factors(5)
def is_prime(n):
return len(factors(n))==2
is_prime(5)
is_prime(50)
def primes(n):
return [p for p in range(1,n+1) if is_prime(p)]
primes(50)
matrix =[[1,2,3],
[4,5,6],
[7,8,9]]
matrix
matrix[0]
matrix[-1]
matrix[0][0]
oned = [i for i in range(1,50+1) if is_prime(i)]
oned
tables = [[i*j for i in range(1,11)] for j in range(1,6)]
tables
t = []
for j in range(1,6):
tr = []
for i in range(1,11):
tr.append(i*j)
t.append(tr)
t
for row in tables:
print(sum(row), end=" ")
p = primes(50)
p
for i in p:
print(i, end=" ")
for i in reversed(p):
print(i, end=" ")
p[::-1]
x = reversed(p)
for i in x:
print(i, end=",")
for j in x:
print(i, end=",")
p
reversed(p)
for i,x in enumerate(p):
print(i, x)
[i for i in reversed(p)]
[(index, item) for index,item in enumerate(["A","B","C"])]
names = ["Alice", "David", "Elsa", "Oz"]
surnames = ["Wonder", "Beazly", "Frozen", "Wizard"]
for n,s in zip(names, surnames): #join two lists side by side
print(n, s)
[(index, item) for index,item in enumerate(["A","B","C"])]
[(index, item) for index,item in zip(range(3), ["A","B","C"])]
f = open("/home/vikrant/trainings/2018/arcesium-basic-nov/poem.txt")
contents = f.read()
print(contents[:100])
f.close()
with open("poem.txt") as fd:
print(fd.read()[:200])
import os
os.mkdir("txtdata")
with open("x.txt", "w") as txt:
txt.write("one")
txt.write("\n")
txt.write(contents)
with open("x.txt", "r") as txt:
print(txt.read()[:100])
def writefiles(data, folder):
name = "textdata"
for i in range(100):
fname = name + str(i) + ".txt"
fpath = os.path.join(folder, fname)
with open(fpath, "w") as f:
f.write(data)
writefiles(contents, "txtdata")
files = os.listdir("txtdata/")
len(files)
sorted(files)[:10]
with open("numbers.txt", "w") as f:
f.write("one\n")
f.write("two\n")
f.write("three\n")
with open("numbers.txt", "a") as f:
f.write("four\n")
f.write("five\n")
print(open("numbers.txt").read())
with open("binary.bin", "wb") as b:
b.write(b"hello world!")
print(open("binary.bin", "rb").read())
with open("poem.txt") as f:
for line in f:
print(line, end="")
"I have this sentence, with some, commas , in it".split(",")
data = [["A","B","C","D"],
["A1","B1","C1","D1"],
["A2","B2","C2","D2"],
["A3","B3","C3","D3"],
["A4","B4","C4","D4"]]
data[0]
",".join(data[0])
def writecsv(data, filename):
with open(filename, "w") as f:
for row in data:
f.write(",".join(row))
f.write("\n")
writecsv(data, "data.csv")
def cat(filename):
with open(filename) as f:
print(f.read())
cat("data.csv")
def head(filename, n):
with open(filename) as f:
count = 0
while count < n:
line = f.readline()
print(line, end="")
count += 1
head("poem.txt", 4)
head("data.csv", 2)
def head_(filename, n):
with open(filename) as f:
for i in range(n):
print(f.readline(), end="")
f = open("data.csv")
f.read() # reads compete file as single string
f.close()
f = open("data.csv")
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.read()
f.close()
f = open("data.csv")
lines = f.readlines()
lines
def grep(patternstring, filename):
with open(filename) as f:
for line in f:
if patternstring in line:
print(line, end="")
grep("Errors", "poem.txt")
def grep(patternstring, filename):
with open(filename) as f:
for i, line in enumerate(f):
if patternstring in line:
print(i+1, line, end="")
grep("Errors", "poem.txt")
grep("def ", "wc.py")
def head(filename, n):
with open(filename) as f:
count = 0
while count < n:
line = f.readline()
print(line, end="")
count += 1
%%file stocks.csv
name,ticker,value,volume
Infosys,infy,1000,500
Tata,tata,500,50
Reliance,reliance,700,100
Tata Infotech,tatainf,600,60
def readcsv(filename):
with open(filename) as f:
data = []
for line in f:
data.append(line.strip().split(","))
return data
readcsv("stocks.csv")
def readcsv_(filename):
with open(filename) as f:
return [line.strip().split(",") for line in f]
readcsv_("stocks.csv")
def grep1(patternstr, filename):
with open(filename) as f:
return [line for line in f if patternstr in line]
grep1("Errors", "poem.txt")
lines = grep1("Tata", "stocks.csv")
lines
lines[0].strip().split(",")
lines[0].strip().split(",")[0]
lines[0].strip().split(",")[2]
lines
stocks = readcsv_("stocks.csv")
stocks
def get_value(ticker, data):
for row in data:
if row[1] == ticker:
return float(row[2])
get_value("infy", stocks)
def get_volume(ticker, data):
for row in data:
if row[1] == ticker:
return float(row[3])
get_volume("infy", stocks)
import re
pattern = re.compile(r"^A.")
%%file regex1.txt
kjsahdhas
kjsahdkjsa dfh
Asdf
Asjkadhas
Ab
jkshd
skajdh
A
with open("regex1.txt") as f:
for line in f:
if pattern.match(line.strip()):
print(line, end="")
def grep(pattern, filename):
p = re.compile(pattern)
with open(filename) as f:
for line in f:
if p.match(line.strip()):
print(line, end="")
grep("^A.", "regex1.txt")
grep("^A.$", "regex1.txt") # extactly one char
grep("^A.{1,3}$", "regex1.txt") # either 1, 2 or 2 chars
grep("^A.+$", "regex1.txt") # atleast one char
grep("^A{1,3}.+$", "regex1.txt") # A can come 1, 2 or 3 times, and rest one or more (any)
grep("^A{2,3}.+", "regex1.txt") # A can come 2 or 3 times, and rest one or more (any)
grep("^A{1,3}.*", "regex1.txt") # A can come 1, 2 or 3 times, and rest zero or more (any)