Thursday, May 18, 2023
State Design Pattern in C++ using boost's pointer...
Saturday, April 22, 2023
The concept of an Orthodox Canonical class in C++
Wednesday, March 15, 2023
Pi Day and the genius mathematician from Bharat - Ramanujan
The genius mathematician who used to dream Maths formulas
Monday, March 13, 2023
A new journey restarted - the beginner's step - Monte Carlo Methpd
Monte Carlo Simulation, also known as the Monte Carlo Method or a multiple probability simulation, is a mathematical technique, which is used to estimate the possible outcomes of an uncertain event. The Monte Carlo Method was invented by John von Neumann and Stanislaw Ulam during World War II to improve decision-making under uncertain conditions.
Unlike a normal forecasting model, Monte Carlo Simulation predicts a set of outcomes based on an estimated range of values versus a set of fixed input values.
Example 1
Problem: the probability of three heads and two tails for a coin tossed five times (assuming a fair coin)
# Answer (from Maths Probability theory) : binomial(3 + 2, 3) 2^(-(3 + 2)) = ((3 + 2)!)/(3! 2! 2^(3 + 2))= 5/16 ≈ 0.3125
Example 2
Problem: The probability of getting three consecutive Heads at the beginning if a coin is tossed 5 times
# Answer (Using Probability theory): ½ X ½ X 1/2 = ⅛ = 0.125
The Mathematical model of Monte Carlo written in Python
Problem 1
success = 0
for i in range(0, attempts):
if (random.randint(0, 1) + random.randint(0, 1) +
random.randint(0, 1) + random.randint(0, 1)
+ random.randint(
0, 1)) != 3:
pass
else:
success += 1
print("Number of attempts = ", attempts)
print("Number of success = ", success)
return success / attempts
Problem 2
success = 0
for i in range(0, attempts):
if (random.randint(0, 1) == 1 and random.randint(0, 1) == 1
and random.randint(0, 1) == 1):
success += 1
else:
pass
print("Number of attempts = ", attempts)
print("Number of success = ", success)
return success / attempts
The Monte Carlo examples implemented in Python...
Thursday, March 9, 2023
Factory Pattern in Python...
I used to get the utmost satisfaction by deciphering framework code. I remember, initially, I used to study the MFC framework code and came to know about observer patterns, about the chain of responsibility design patterns being used there.
Later, I used to study the Symbian S60 framework code - and studied in detail their Active Object design principles and ECom plugins.
Yes, I am talking about 2006-2007 just before the arrival of the iPhone and Android when NOKIA was the undisputed leader in the mobile world.
Please have a look at the following blog post where I deciphered the basic Active Object of the Symbian framework and why a long-running task does not freeze the UI.
So the point is, don't blindly follow anything. Keep your inquisitive mind always ready for new stuff. For example, my inquisition about the two-phase constructor in Symbian led me to study the Boost library in 2007 in Japan which ultimately became part of the C++ standard library in the 2009 release of C++.
Symbian Active Object framework...
Then when i switched over to Android, I started studying the Android framework code.
Asynstask Framework...
Android Service internals...
So, here we go - an implementation of Factory Pattern in Python.
from abc import ABC,abstractmethod
class Food(ABC):
pass
class Chocolate(Food):
def __init__(self):
print("chocolate is made")
class Biscuit(Food):
def __init__(self):
print("biscuit is made")
class Factory:
def makefood(self,type):
if(type == "ch"):
return Chocolate()
if(type == "bi"):
return Biscuit()
if __name__ == '__main__':
fact = Factory()
chocolate = fact.makefood("ch")
biscuit = fact.makefood("bi")
Friends... Enjoy...
Observer Pattern in Python...
The observer design pattern is a very popular design pattern in the Object Oriented world. I must admit, I first saw the utilities of this design pattern while studying the document view architecture of the MFC source code.
Later on, I used this pattern in many places.
There is a lot of similarity between the Observer Pattern, the Callback mechanism, and the Event Handler process in Java. Usually, the callback method is used when there is only one observer who awaits the signal from the observee.
So, let me put it in this fashion.
Suppose, there is a central document that is viewed by a few applications - someone is viewing it in a spreadsheet, someone as a Pie chart, and so on.
Now if the data in the document is updated, all the viewers must be updated and they should synchronize their views with the latest data set. So basically all the viewers were observing the central data. The moment it changes, all the observers get their respective views updated.
Here goes the Python code for this observer pattern
from __future__ import annotations
from abc import ABC,abstractmethod
from typing import List
class Subject(ABC):
@abstractmethod
def addObserver(self,observer):
pass
@abstractmethod
def removeObserver(self,observer):
pass
@abstractmethod
def notifyObservers(self):
pass
class ConcreteSubject(Subject):
_observers = []
_state = "my current state"
def addObserver(self,observer):
self._observers.append(observer)
def removeObserver(self,observer):
self._observers.remove(observer)
def notifyObservers(self):
for observer in self._observers:
observer.update()
def dosomething(self):
print("I am doing something which will change my state.Notifying observers")
self._state = "subject state has been changed"
self.notifyObservers()
class Observer(ABC):
@abstractmethod
def update(self):
pass
class ConcreteObserver(Observer):
def __init__(self,subject):
self._subject = subject
def update(self):
print(self._subject._state)
if __name__ == '__main__':
concretesubject = ConcreteSubject()
observer1 = ConcreteObserver(concretesubject)
observer2 = ConcreteObserver(concretesubject)
concretesubject.addObserver(observer1)
concretesubject.addObserver(observer2)
concretesubject.dosomething()
For all other inquisitive student communities, here goes my training on Observer Pattern in Java
Observer Pattern in Bengali...
Wednesday, March 8, 2023
The Proxy Pattern in Python...
Proxy pattern - as the name suggests - creates a proxy in place of a real heavy-duty object.
Let me give you a real-life example taken from computer science.
In case a document contains many huge-sized images, it does not load all the images when the doc gets loaded into the memory. Because it might take a very long time.
The proxy pattern comes as a rescue.
The document, instead of the actual mega images, gets loaded with very lightweight proxies of those images. And then when needed - in actual run time, i.e., when we need to see an image, the images get loaded by the proxy. This kind of proxy is called a virtual proxy.
Now let us talk from our example.
We are a family of three. Now my son does all the lightweight jobs - like, if there is a guest, he opens the door. So, he is the initial interface for the guests. However, in case, a guest wants to have lunch or dinner, my son calls his Mamma - because it's a heavy-duty job that he himself cannot do.
So basically my son gives proxy to his Mom, and if needed - like when he has to perform a heavy-duty job like cooking - he simply delegates the task to his Mom. For all other lightweight jobs, his Mom, who obviously has a lot of significant jobs to perform, remains in the background. She comes in the foreground in case there is a heavy-duty task like cooking for a guest.
Here's the source code of the Proxy Pattern implemented in Python.
Enjoy.
class FamilyMember(ABC):
@abstractmethod
def openTheDoor(self):
pass
def cook(self):
pass
class Mamma(FamilyMember):
def openTheDoor(self):
print("Son will open the door")
def cook(self):
print("Mamma is cooking")
class Son(FamilyMember):
def __init__(self):
self.mamma = Mamma()
def openTheDoor(self):
print("Son opens the door")
def cook(self):
print("Son does not know how to cook He was just giving proxy for mamma")
self.mamma.cook()
class Home():
def __init__(self):
self.son = Son()
def openTheDoor(self):
self.son.openTheDoor()
def preparefood(self):
self.son.cook()
if __name__ == '__main__':
home = Home()
home.openTheDoor()
home.preparefood()
