Dec 17-23, 2020 Vikrant Patil
These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch3/module2-day4.html
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using jupyter hub from http://lab.pipal.in for this training. Create a notebook with name module2-day4.ipynb for today's session. Before you start shutdown all kernels except today's notebook.
Problem
Implement a class for Stock which should have methods and data encapsulation as given below
``` Stock +--------------------+ | name |----------> update_value | value | | high | | low | +--------------------+ | | | | | | | +-------- get_name | | +------------- get_value | +----------------- get_high +--------------------- get_low
class Stock:
def __init__(self, name, value, high, low):
self.name = name
self.value = value
self.high = high
self.low = low
def update_value(self, value):
self.value = value
if value < self.low:
self.low = value
if value > self.high:
self.high = value
def get_name(self):
return self.name
def get_value(self):
return self.value
def get_high(self):
return self.high
def get_low(self):
return self.low
hcl = Stock("HCL", 250.0, 255.4, 200.0)
hcl
hcl
print(hcl)
class Stock:
def __init__(self, name, value, high, low):
self.name = name
self.value = value
self.high = high
self.low = low
def update_value(self, value):
self.value = value
if value < self.low:
self.low = value
if value > self.high:
self.high = value
def get_name(self):
return self.name
def get_value(self):
return self.value
def get_high(self):
return self.high
def get_low(self):
return self.low
def __repr__(self):
return "Stock(" + self.name + ")"
infy = Stock("Infy", 1500.5, 1500, 1499.0)
infy # this will whatever __repr__ returns
print(infy)
class Stock:
def __init__(self, name, value, high, low):
self.name = name
self.value = value
self.high = high
self.low = low
def update_value(self, value):
self.value = value
if value < self.low:
self.low = value
if value > self.high:
self.high = value
def get_name(self):
return self.name
def get_value(self):
return self.value
def get_high(self):
return self.high
def get_low(self):
return self.low
def __repr__(self): ## methods that start with __ and ends with __ , are special methods and they are predefined
return "Stock(" + self.name + ")"
def __str__(self):
return "Stock<" + ",".join([self.name , str(self.value), str(self.high), str(self.low)]) + ">"
s = Stock("TATA", 150.4, 155.3, 149.0)
s
print(s)
Stock("HCL", 1, 2, 1)
numbers = [1, 2, 3]
numbers
str(3)
str(s)
"Stock({})".format("HCL")
class WellFormattedStock(Stock):
def __repr__(self):
return "Stock({})".format(self.name)
WellFormattedStock("XYZ", 2, 3, 2)
class WellFormattedStock(Stock):
def __repr__(self):
return "Stock({})".format(self.name)
def __str__(self):
return "Stock<{}, {}, {}, {}>".format(self.name, self.value, self.high, self.low)
j = WellFormattedStock("JHJH", 2, 3, 2)
j
print(j)
"I can define a string with variable like this {}, which can be filled programticaly using format {}".format("python", 42)
"I can also control the order like this {1}, {2}, {0}".format("zeroth", "first", "second")
variable = "Arcesium"
"This is fixed sentence with a name in it!".replace("name", variable)
"One can give variables in format method {} {} {}".format(1, 2, 3)
"{0} One can give {2} ordered variables {1}".format("one", "two", "three")
def add(x, y):
return x+y
add(3, 4)
add(x=3, y=4)
add(y=4, x=3)
max(["one", "two", "three"], key=len)
for i in range(1, 11):
print("{unit} {sqr} {cube}".format(unit=i, sqr=i*i, cube=i*i*i))
for i in range(1, 11):
print(str(i).rjust(2), str(i*i).rjust(3), str(i**3).rjust(4))
for i in range(1, 11):
print("{unit:2d} {sqr:3d} {cube:4d}".format(unit=i, sqr=i*i, cube=i*i*i))
for i in range(1, 11):
print("{x:2d} {sqrx:3d} {cubex:4d}".format(x=i, sqrx=i*i, cubex=i*i*i))
for i in range(1, 101):
print(str(i).ljust(3), str(i*i).ljust(5), str(i**3).ljust(7))
problem
print_triangle which prints a traigle as given below *
* *
* * *
* * * *
* * * * *
2 * 4
str(*)
"*"
str(2)
str(+)
"+" # made this string
'*'
"""multi"""
def print_triangle(n):
for i in range(n):
line = " ".join(list("*"*i))
print(line.center(2*n-1))
print_triangle(10)
def print_triangle(triangle):
lastline = triangle[-1]
w = 2*len(lastline)-1
for line in triangle:
print(" ".join(line).center(w))
def triangle(n):
return [list("*"*i) for i in range(1, n+1)]
triangle(5)
t = triangle(5)
print_triangle(t)
print_triangle(triangle(20))
list("*"*5)
def print_triangle(triangle):
lastline = triangle[-1]
w = 2*len(lastline)-1
for line in triangle:
print(" ".join(list(line)).center(w))
def triangle(n):
return ["*"*i for i in range(1, n+1)]
triangle(5)
print_triangle(triangle(10))
Bonus problem
>>> pascal(5)
[[1],[1,1], [1,2,1],[1,3,3,1],[1,4,6,4,1]]
Write a function print_pascal which prints pascal triangle
>>> print_pascal(pascal(6))
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
"hello".center(20).index("hello")
"hello".center(21).index("hello")
"iiiiiiiiii".center(20)
"iiiiiiiiii".center(20).index("i")
"iiiiiiiiii".center(19)
names = ["APPLE", "IBM", "AT&T", "AGILENT"]
values = [700.5, 300.1, 355.4, 600.2]
stocks = {}
for name, value in zip(names, values):
stocks[name] = value
stocks
nums = [1, 2, 34]
nums = [1, 2, 3, 4,5 ,6, 7, 8, 90]
sqr = []
for n in nums:
sqr.append(n*n)
sqr
[n*n for n in nums]
names = ["APPLE", "IBM", "AT&T", "AGILENT"]
values = [700.5, 300.1, 355.4, 600.2]
stocks = {}
for name, value in zip(names, values):
stocks[name] = value
{name:value for name, value in zip(names, values)}
dict(zip(names, values))
currency_rate = 1.2
{name:value*currency_rate for name, value in zip(names, values)}
dict(zip(names, values))
stocks
stocks['APPLE']
for key in stocks:
print(key)
for key in stocks:
print(key, stocks[key])
[value for value in stocks.values()]
for value in stocks.values():
print(value)
for key, value in stocks.items():
print(key, value)
stocks['MIRCROSOFT']
stocks.get('MICROSOFT', 0)
stocks
stocks.get("APPLE", 0)
stocks
stocks.setdefault("MICROSOFT", 0)
stocks
stocks
len(stocks)
{key:value for key,value in stocks.items() if value>400} # get stocks with value > 400
handpicked_stocks = {"APPLE", "IBM"}
{key:value for key, value in stocks.items() if key in handpicked_stocks}
{key:stocks[key] for key in handpicked_stocks} # this will fail if key in handpicked in not there in stocks
%%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 seven
one two three four eight seven
one two three nine eight seven
one two ten nine eight seven
one ten nine eight seven
ten nine eight seven
ten nine eight
ten nine
ten
def get_words(filename):
with open(filename) as f:
return f.read().split()
def word_freq(words):
freq = {}
for w in words:
if w in freq:
freq[w] += 1
else:
freq[w] = 1
return freq
words= get_words("words.txt")
word_freq(words)
def word_freq1(words):
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
return freq
word_freq1(words)
def word_freq2(words):
freq = {}
unique = set(words)
for w in unique:
freq[w] = words.count(w)
return freq
word_freq2(words)
freq = word_freq(words)
for w, count in freq.items():
print(w, count)
def get_value(t):
return t[1]
for w, count in sorted(freq.items(), key=get_value):
print(w, count)
def get_value(t):
return t[1]
for w, count in sorted(freq.items(), key=get_value, reverse=True):
print(w, count)
for w, count in sorted(freq.items(), key=get_value, reverse=True):
print(w.rjust(5), count)
for w, count in sorted(freq.items(), key=get_value, reverse=True):
print(w.rjust(5), str(count).rjust(2), "*"*count)