Jan 29-31, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-pune-jan-python
© Pipal Academy LLP
f = open("numbers.txt", "w")
f.write("ones\n")
f.write("two\n")
f.write("three\n")
f.close()
!python cat.py numbers.txt
with open("primes.txt", "w") as f:
f.write("two\n")
f.write("three\n")
f.write("five\n")
print("Here ends with block")
!python cat.py primes.txt
with open("primes.txt", "a") as f:
f.write("seven\n")
f.write("eleven\n")
!python cat.py primes.txt
with open("binary.bin", "wb") as f:
f.write(b"\x23\x2a")
f.write(b"string as binary data\n")
with open("binary.bin", "rb") as f:
print(f.read())
with open("regional.txt", "w", encoding="utf-8") as f:
f.write("आआडढ\n")
f.write("\u0c65")
with open("regional.txt", encoding="utf-8") as f:
print(f.read())
Writing a csv file
t = [[i*j for i in range(1,11)] for j in range(1,5)]
t
def writecsv(data, filename):
with open(filename, "w") as csv:
for row in data:
csv.write(",".join([str(item) for item in row]))
csv.write("\n")
writecsv(t, "tables.csv")
!python cat.py tables.csv
problem
l = []
l[0] = 3
numbers = ["1","2","3","4","5","6"]
[int(item) for item in numbers]
def csvparser(filename):
data = []
with open(filename) as f:
for line in f:
row_ = line.strip().split(",")
row = [int(i) for i in row_]
data.append(row)
return data
csvparser("tables.csv")
[[int(i) for i in line.strip().split(",")] for line in open("tables.csv")]
def csvparser(filename):
return [[int(i) for i in line.strip().split(",")] for line in open(filename)]
def csvparser(filename):
return [[int(i) for i in line.strip().split(",")] for line in open(filename)]
csvparser("tables.csv")
def csvparser(filename):
data = []
with open(filename) as f:
line = f.readline()
while line:
row_ = line.strip().split(",")
row = [int(i) for i in row_]
data.append(row)
line = f.readline()
return data
csvparser("tables.csv")
import sys
sys.stderr.write("Something went wrong!")
sys.stdout.write("Just a print")
author = {"name":"Lewis carol",
"books":["Alice in wonderland","Looking through the glass"],
"language":"english"}
author['name']
author['books']
author['language']="english-uk"
author
del author["language"]
author
author['books'][1]
"name" in author
"lagguage" in author
author['xyz']
author.get("key",[])
author.get("key",2)
author
author['key'] = "hello"
type(author)
isinstance(author,dict)
author.get("xyz",None)
delattr(author ,"Lewis carol")
author
help(delattr)
d = {}
names = ["Anand","Naufal","David","Alice"]
countries = ["India","India","USA","UK"]
for name,country in zip(names, countries):
d[name] = country
d
items = [1,2,3,4]
item[4]= 5
d["Alex"] = "USA"
d
dict(zip(names, countries))
load grub conf as dictinary
!python cat.py /etc/default/grub
def load_grubconf(filename):
conf = {}
for line in open(filename):
if line.startswith("#") or line.strip()=="" or ("=" not in line):
continue
tokens = line.strip().split("=",1)
conf[tokens[0]] = tokens[1]
return conf
load_grubconf("/etc/default/grub")
problem
%%file words.txt
one
one two
one two three
one two three four
one two three four five
one two three four five six
one two three four five
one two three four
one two three
one two
one
"a:".split(":")
def wordfreq(filename):
words = open(filename).read().strip().split()
freq = {}
for word in words:
freq[word] = freq.get(word,0) + 1
return freq
wordfreq("words.txt")
def wordfreq(filename):
words = open(filename).read().strip().split()
uniq = set(words)
freq = {}
for w in uniq:
freq[w] = words.count(w)
return freq
freq = wordfreq("words.txt")
for item in freq:
print(item, freq[item])
for item in freq:
print(item)
for key,value in freq.items():
print(key, value)
for value in freq.values():
print(value)
for item in freq.keys():
print(item)
for key,value in freq.items():
print(key.rjust(5), str(value).ljust(2))
for key,value in sorted(freq.items()):
print(key.rjust(5), str(value).ljust(2))
for key in sorted(freq, key=lambda x:freq[x]):
print(key.rjust(5), str(freq[key]).ljust(2))
for key in sorted(freq, key=lambda x:freq[x], reverse=True):
print(key.rjust(5), str(freq[key]).ljust(2))
sorted(freq, key=lambda x:freq[x], reverse=True)
for key in sorted(freq, key=lambda x:freq[x], reverse=True):
print(key.rjust(5), str(freq[key]).ljust(2), "*"*freq[key])
d
v = set(d.values())
[key for key in d if d[key]=="India"] #group all keys based on values
[key for key in d if d[key]=="USA"]
for item in v:
print([key for key in d if d[key]==item])
x = [1,2,3]
y = x
y.append(4)
x
x
y
x = [1,2,3]
y = x
x = [1,1]
y
y = x[:]
y
x = [1,2,3]
y = x[:]
y.append(4)
x
%%file module1.py
x = 5
y = 3
def addx(z):
return x+z
def addy(z):
return y+z
import module1
module1.x
module1.y
module1.x = 0
module1.x
%%file bank0.py
balance = 0
def getbalnce():
return balance
def deposite(amount):
global balance
balance += amount
def withdraw(amount):
global balance
balance -= amount
if __name__ == "__main__":
print(getbalnce())
deposite(100)
print(getbalnce())
withdraw(23)
print(getbalnce())
!python bank0.py
%%file bank1.py
def make_account():
return {"balance":0}
def get_balance(account):
return account['balance']
def deposite(account, amount):
account['balance'] += amount
def withdraw(account, amount):
account['balance'] -= amount
if __name__ == "__main__":
def print_(a1, a2):
print("a1: ",get_balance(a1))
print("a2: ",get_balance(a2))
a1 = make_account()
a2 = make_account()
print_(a1, a2)
deposite(a1, 1000)
deposite(a2, 1100)
print_(a1,a2)
withdraw(a1, 244)
withdraw(a2, 300)
print_(a1, a2)
!python bank1.py
module1.z = 3
%%file bank2.py
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def get_balance(self):
return self.balance
def deposite(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def hello():
print("Hello")
if __name__ == "__main__":
a1 = BankAccount()
a2 = BankAccount(300)
print("a1: ", a1.get_balance())
print("a2: ", a2.get_balance())
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1,2)
p.x
p.y
def add(x,y):
return x+y
class Foo:
pass
Foo
type(Foo)
type(p)
p.__dict__
p.z = 3
p.z
p.__dict__
Foo.__dict__
def f():
pass
f()
p.newfunc = f
del p.x
p.x
problem
t = Timer()
t.start()
s = 0
for i in range(1000):
for j in range(10000):
s += i*j*1.0
t.stop()
print(t.get_time_taken())
import time
time.time()
class Complex:
def __init__(self, real, img):
self.real = real
self.img = img
def add(self, c):
return Complex(self.real+c.real, self.img+c.img)
def _display(self):
return "{r}+{i}j".format(r=self.real, i=self.img)
def __repr__(self):
return "Complex({r},{i})".format(r=self.real, i=self.img)
def __str__(self):
return self._display()
c = Complex(2,3)
help(Complex)
c._display()
c1 = Complex(3,4)
c2 = c.add(c1)
c2._display()
print(c) ## coming from __str__
c # coming from __repr__
class Timer:
def start(self):
self._start = time.time()
def stop(self):
self._stop = time.time()
def get_time_taken(self):
return self._stop - self._start
t = Timer()
t.start()
time.sleep(2)
t.stop()
t.get_time_taken()
t
class Foo:
pass
class Foo(object):
pass
class ColoredPoint(Point):
def __init__(self, x, y, color=(0,0,0)):
Point.__init__(self, x, y)
self.color = color
item = [1,2,3,4]
item
import this
a
c
import math
import matplotlib.pyplot as plt
%matplotlib inline
def imshow(img):
plt.imshow(img, cmap=plt.cm.gray)
plt.show()
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Shape:
position = Point(0,0)
def contains(self, point):
pass
def distance(p1, p2):
dx = p2.x - p1.x
dy = p2.y - p1.y
return math.sqrt(dx**2 + dy**2)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def contains(self, p):
return distance(p, self.position)<=self.radius
class Recangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def contains(self, point):
dx = point.x - self.position.x
dy = point.y - self.position.y
return dx<=self.width and dy<=self.length
class Intersect(Shape):
def __init__(self, shapes):
self.shapes = shapes
def contains(self, point):
flag = True
for s in self.shapes:
flag = flag and s.contains(point)
return flag
class Union(Shape):
def __init__(self, shapes):
self.shapes = shapes
def contains(self, point):
flag = False
for s in self.shapes:
flag = flag or s.contains(point)
return flag
class Canvas:
def __init__(self, x=200, y=200):
self.x = x
self.y = y
self.data = [[False for i in range(x)] for j in range(y)]
def paint(self, shape):
for i in range(self.y):
for j in range(self.x):
self.data[i][j] = shape.contains(Point(i,j))
def display(self):
imshow(self.data)
c = Circle(20)
canvas = Canvas()
canvas.paint(c)
canvas.display()
r = Recangle(100,50)
canvas.paint(r)
canvas.display()
s = [Circle(50),Recangle(,100)]
intersect = Intersect(s)
c = Canvas()
c.paint(intersect)
c.display()
s = [Circle(50),Recangle(20,100)]
u = Union(s)
c = Canvas()
c.paint(u)
c.display()
%%file missing.txt
1,2,3,4,5,6,,8,9,10
2,4,6,8,10,Nan,14,16,18,20
3,6,9,12,15,18,21,24,27,30
4,8,12,16,20,24,,32,36,40
csvparser("missing.txt")
import sys
def parseint(strnm):
try:
return int(strnm)
except ValueError as v:
sys.stderr.write(str(v))
return 0
def csvparser(filename):
return [[parseint(v) for v in line.strip().split(",")] for line in open(filename)]
csvparser("missing.txt")
%%file head.py
import argparse
def head(filename, lines=5):
f = open(filename)
for i in range(lines):
print(f.readline().strip())
def parse_arguments():
parser = argparse.ArgumentParser(
description="head command shows first few lines of file")
# if only one name given it is
parser.add_argument("filename", type=str,
help="File whose contents are to be shown")
#if long and short name is given then this is optional
parser.add_argument("-n", "--lines", type=int,
help="number of lines to show")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
print(args)
if args.lines:
head(args.filename, args.lines)
else:
head(args.filename)
!python head.py
!python head.py -h
!python head.py data.txt
!python head.py -n 10 data.txt
!python head.py -n xsx data.txt
%%file grep.py
import argparse
def grep(pattern, filename):
for line in open(filename):
if pattern in line:
print(line, end="")
def invertgrep(pattern, filename):
for line in open(filename):
if pattern not in line:
print(line, end="")
def parse_arguments():
parser = argparse.ArgumentParser(
description="grep command greps for given patters in a file")
# if only one name given it is
parser.add_argument("pattern", type=str,
help="pattern to search")
parser.add_argument("filename", type=str,
help="File in which to look for pattern")
#if long and short name is given then this is optional
parser.add_argument("-v", "--invert",
help="Invert the match",
action="store_true")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
if args.invert:
invertgrep(args.pattern, args.filename)
else:
grep(args.pattern, args.filename)
!python grep.py "def" head.py
!python grep.py -v "def" head.py
import requests
install requests using
pip3 install requests
resp = requests.get("http://httpbin.org/html")
print(resp.text[:100])
resp.status_code
resp = requests.get("http://httpbin.org/get", params={"param1":"python",
"param2":"xyz"})
print(resp.text)
resp = requests.post("http://httpbin.org/post", data={"name":"python",
"email":"xyz@xyz.com"})
print(resp.text)
resp = requests.post("http://httpbin.org/post", data=open("numbers.txt"))
print(resp.text)
resp.json()
Find popular repositories of vmware on github
url = "https://api.github.com/orgs/vmware/repos"
repos = requests.get(url).json()
type(repos)
len(repos)
print(repos[0])
def get_forks(r):
return r['forks']
for r in sorted(repos, key=get_forks, reverse=True):
print(r['name'], r['forks'])
for r in sorted(repos, key=get_forks, reverse=True)[:5]:
print(r['full_name'], r['forks'])
def get_top_contributors(name):
url = "https://api.github.com/repos/{}/stats/contributors".format(name)
resp = requests.get(url)
print(resp.status_code)
contributors = resp.json()
return contributors
contribs = get_top_contributors("vmware/pyvmomi")
type(contribs)
c = contribs[0]['author']
print(c['login'], contribs[0]['total'])
for c in sorted(contribs, key=lambda x:x['total'], reverse=True)[:5]:
print(c['author']['login'], c['total'])
problem find distance between two cities using google api.
origins
destinations
units - metric
def distance(source, dest):
url = "https://maps.googleapis.com/maps/api/distancematrix/json/"
resp = requests.get(url, params={"origins":source,
"destinations":dest,
"units":"metric"})
data = resp.json()
return data
distance("pune", "mumbai")
Suggested mini projects.