Dec 13-15, 2017 Vikrant Patil
These notes are available online at http://notes.pipal.in/2017/vmware-nov-python
© Pipal Academy LLP
def rearrangemax(n):
strnum = str(n)
digits = sorted(strnum, reverse=True)
return int("".join(digits))
rearrangemax(232343)
def rearrange(n, reverse=True):
strnum = str(n)
digits = sorted(strnum, reverse=reverse)
return int("".join(digits))
rmax = lambda n: rearrange(n)
rmin = lambda n: rearrange(n, reverse=False)
rmax(232434)
rmin(2343)
def kaprekar(n, numiter):
while numiter>0:
ma = rmax(n)
mi = rmin(n)
n = ma - mi
numiter -= 1
return n
# this will fail in case number of digits get reduced during iteration
def kaprekar(n, numiter=100):
def rearrange(n, numdigits, reverse=True):
strnum = str(n).zfill(numdigits)
digits = sorted(strnum, reverse=reverse)
return int("".join(digits))
ndigits = len(str(n))
rmax = lambda n: rearrange(n, ndigits)
rmin = lambda n: rearrange(n, ndigits, reverse=False)
while numiter>0:
ma = rmax(n)
mi = rmin(n)
n = ma - mi
numiter -= 1
return n
kaprekar(2445)
kaprekar(4546)
kaprekar(343)
kaprekar(657)
[x*x for x in range(1,11)]
[x*x*x for x in range(1,11)]
[rmax(n) for n in range(11, 100, 10)]
even = lambda x: x%2==0
[x for x in range(1,11) if even(x)]
setence = "Some sentence for testing list comprehensions"
words = setence.split()
[word.rjust(10) for word in words]
[word.upper() for word in words]
[word.startswith("s") for word in words]
[word for word in words if word.lower().startswith("s")]
tables = [[i*j for i in range(1,11)] for j in range(1,6)]
tables[0]
tables[1]
tables[:]
tables[0][:]
[row[0] for row in tables] #0th column
[row[1] for row in tables] #1st column
problem:
listpy which will list all py files from given directoryfactors which will create list all factors of given numberis_prime which can tell if given number is prime or not?def listpy(path):
files = os.listdir(path)
return [file for file in files if file.endswith(".py")]
import os
listpy(os.getcwd())
def factors(n):
return [i for i in range(1, n+1) if n%i ==0]
factors(10)
factors(5)
def is_prime(n):
return factors(n)==[1,n]
def primes(n):
return [p for p in range(1, n+1) if is_prime(p)]
primes(25)
def print_primes(n):
for i in range(1, n+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i, end=",")
Generate a unit matrix(identity matrix..diagonal elements 1 every other element is 0). of size 5
def element(i,j):
if i==j: return 1
else: return 0
[[element(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)]
sum(primes(25))
sum([1]*10)
for p in primes(25):
print(p, end=",")
for p in reversed(primes(25)):
print(p, end=",")
reversed(primes(25))
pnumbers = primes(25)
for index, prime in enumerate(pnumbers):
print(index, prime)
first = ["Elsa", "Alisa", "Exotica", "Beauty"]
last = ["Frozen", "Hacker", "Logica", "Nurd"]
for f,s in zip(first, last):
print(f, s)
zip(first, last)
numbers = [1,2,3,4,5,6]
dstrings = ["one", "two", "three", "four", "five"]
for first, second in zip(numbers, dstrings):
print(first, second)
for i, p in reversed(reversed(pnumbers)):
print(i, p)
list(reversed(pnumbers))
reversed(reversed(pnumbers))
problem:
vector_add to add elements from two lists
>>> vector_add([1,1,1,1], [1,2,3,4])
[2,3,4,5]
sum(first)
sum(last, "")
def vector_add(v1, v2):
return [i+j for i,j in zip(v1, v2)]
vector_add([1,1,1,1],[1,1,1,1])
sum([i for i in range(1, 1000) if i%3==0 or i%5==0])
def usual_way_polynomial(coeff, x):
s = 0
for i, c in enumerate(reversed(coeff)):
s += c * x**i
return s
usual_way_polynomial([1,1,1], 2)
make a generic polynomial generator!
def make_polynomial(coeffs):
def poly(x):
s = 0
for i, c in enumerate(reversed(coeffs)):
s += c * x**i
return s
return poly
P2 = make_polynomial([1,1,1])
P2
P2(2)
P2(3)
%%file functions.py
"""
This is long deccription of module functions
functions module contains some functions to demonstrate
docstrings and doctest
"""
def add(x,y):
"""
adds integers
>>> add(0,1)
1
>>> add(1,-1)
0
"""
return x+y
def square(x):
"""
calculates square of a number
>>> square(-1)
1
>>> square(0)
0
"""
return x*x
import functions
help(functions)
def mysum(*args):
print(args)
s = 0
for i in args:
s += i
return s
mysum(1,2)
mysum(1,2,3,4,5)
!python -m doctest -v functions.py
Third party module pytest is very handy automated testing you can install it using
pip3 install pytest
from functions import add
def test_add():
if add(1,0) == 1:
print("success")
test_add()
%%file functions1.py
"""
This is long deccription of module functions
functions module contains some functions to demonstrate
docstrings and doctest
"""
def add(x,y):
"""
adds integers
>>> add(0,1)
1
>>> add(1,-1)
0
"""
return x+y
def square(x):
"""
calculates square of a number
>>> square(-1)
1
>>> square(0)
0
"""
return x*x
def test_add():
assert add(1,0) == 1
assert add(1,-1)==0
def test_square():
assert square(-1) == 1
assert square(3) == 5
if __name__ == "__main__":
test_add()
test_square()
!python functions1.py
!py.test functions1.py
def squares_and_cubes():
for i in range(11):
print(i, i*i, i*i*i)
squares_and_cubes()
def squares_and_cubes():
for i in range(11):
print("{0:2d} {1:3d} {2:4d}".format(i, i*i, i*i*i))
squares_and_cubes()
"Wizard of oz if {}".format("python")
"Wizard of {} is in {}".format("python", "oz")
"Purpose of life is {0} , compuation in {1} says so!".format(42, "python")
"Wizard of {wizardname} is in {place}".format(wizardname="python", place="oz")
"23".zfill(5)
"name".rjust(10)
"name".ljust(10)
"name".center(10)
problem:
def pascal(n):
tr = [[1]]
for i in range(1,n):
last = tr[-1]
pre = [0] + last
post = last + [0]
row = [x+y for x,y in zip(pre, post)]
tr.append(row)
return tr
pascal(3)
def print_pascal(triangle):
last = triangle[-1]
biggestnum = max(last)
digits = len(str(biggestnum))
totalspace = len(last)*digits + len(last)-1
def format_row(row, digits):
s = ""
for i in row:
s = s + " {item:{digits}}".format(item=i, digits=digits)
return s
for row in triangle:
print(format_row(row, digits).center(totalspace))
print_pascal(pascal(15))
%%file three.txt
one
two
three
fhandle = open("three.txt")
fhandle.read()
fhandle.read()
fhandle.close()
import this
%%file data.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
f = open("data.txt")
f.readline()
f.readline()
f = open("data.txt")
for line in f.readlines():
print(line.strip())
for i, line in enumerate(open("data.txt")):
print(i, line.strip())
for line in open("data.txt"):
print(len(line.strip().split()))
problem:
python cat.py data.txt three.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
.
.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
one
two
three
python head.py data.txt
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
%%file cat.py
import sys
def cat(files):
for file in files:
f = open(file)
print(f.read())
def cat_(*files):
for file in files:
f = open(file)
print(f.read())
if __name__=="__main__":
#cat(sys.argv[1:])
cat_(*sys.argv[1:])
!python cat.py data.txt three.txt
%%file head.py
import sys
def head(file, n=3):
for i, line in enumerate(open(file)):
print(line.strip())
if (i+1)==n:
return
if __name__ == "__main__":
head(sys.argv[2], int(sys.argv[1]))
!python head.py 4 data.txt
problem:
%%file wc.py
import sys
def line_count(file):
lines = open(file).readlines()
return len(lines)
def word_count(file):
words = open(file).read().split()
return len(words)
def char_count(file):
chars = open(file).read()
return len(chars)
def test_line():
assert line_count("three.txt") == 3
def test_word():
assert word_count("three.txt") == 3
def test_char():
assert char_count("three.txt") == 14
if __name__ == "__main__":
f = sys.argv[1]
print(line_count(f), word_count(f), char_count(f), f)
!py.test wc.py
!python wc.py data.txt
import os, wc
def filewithmaxlines(path):
files = [f for f in os.listdir(path) if os.path.isfile(f)]
return max(files, key=wc.line_count)
filewithmaxlines(".")
import os, wc
def file_with_maxword_count(path):
files = [f for f in os.listdir(path) if os.path.isfile(f)]
return max(files, key=wc.word_count)
Writing files
f = open("numbers.txt", "w")
f.write("one\n")
f.write("two\n")
f.write("three\n")
f.write("four\n")
f.close()
!python cat.py numbers.txt
f = open("numbers.txt", "a")
f.write("five\n")
f.write("six\n")
f.close()
!python cat.py numbers.txt
f = open("binary.bin", "wb")
f.write(b"\x45\x56")
f.close()
f = open("binary.bin", "rb")
f.read()
f.close()
f = open("binary.bin", "ab")
f.write(b"Hello as binary")
f.close()
f = open("binary.bin", "rb")
print(f.read())
f.close()
b'Hello python'.decode()
f = open("regional.txt","w", encoding="utf-8")
f.write("आ आ ॐ")
f.close()
f = open("regional.txt", encoding="utf-8")
f.read()
data = [["A1", "B1", "C1"],
["A2", "B2", "C2"],
["A3", "B3", "C3"],
["A4", "B4", "C4"]
]
%%file data1.txt
A1,B1,C1
A2,B2,C2
.
.
",".join(data[0])
problem:
Write a function writecsv to write above 2 dimensional data into a csv file.
def writecsv(data, file):
f = open(file, "w")
for row in data:
f.write(",".join(row) + "\n")
f.close()
writecsv(data, "data1.csv")
!python cat.py data1.csv