avatarNaina Chaturvedi

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

32861

Abstract

hljs-string">'t'</span>, <span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>, <span class="hljs-string">'z'</span>]</pre></div><div id="b8ed"><pre>mapped_list = list(<span class="hljs-name">map</span>(<span class="hljs-name">lambda</span> x, y: (<span class="hljs-name">x</span>, y), strings, numbers))</pre></div><div id="a9ca"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(mapped_list)</span></span></pre></div><p id="e97c"><b>Output —</b></p><div id="acb5"><pre>[(<span class="hljs-symbol">'s</span>', <span class="hljs-number">1</span>), (<span class="hljs-symbol">'t</span>', <span class="hljs-number">2</span>), (<span class="hljs-symbol">'x</span>', <span class="hljs-number">3</span>), (<span class="hljs-symbol">'y</span>', <span class="hljs-number">4</span>), (<span class="hljs-symbol">'z</span>', <span class="hljs-number">5</span>)]</pre></div><p id="78ed"><b>Implementation —</b></p><div id="ff93"><pre><span class="hljs-comment">#map implementation</span> <span class="hljs-attr">days</span> = [<span class="hljs-string">'Sunday'</span>, <span class="hljs-string">'Monday'</span>, <span class="hljs-string">'Tuesday'</span>, <span class="hljs-string">'Wednesday'</span>]</pre></div><div id="439b"><pre>mod_days = <span class="hljs-built_in">list</span>(<span class="hljs-built_in">map</span>(str<span class="hljs-selector-class">.swapcase</span>, days))</pre></div><div id="615a"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(mod_days)</span></span></pre></div><p id="9661"><b>Output —</b></p><div id="f37f"><pre>[<span class="hljs-symbol">'sUNDAY</span>', <span class="hljs-symbol">'mONDAY</span>', <span class="hljs-symbol">'tUESDAY</span>', <span class="hljs-symbol">'wEDNESDAY</span>']</pre></div><p id="3e5c"><b>Implementation —</b></p><div id="f1e4"><pre><span class="hljs-meta prompt_">#</span><span class="language-bash">Filter <span class="hljs-keyword">function</span></span></pre></div><div id="5e64"><pre><span class="hljs-attr">marks</span> = [<span class="hljs-number">95</span>, <span class="hljs-number">40</span>, <span class="hljs-number">68</span>, <span class="hljs-number">95</span>, <span class="hljs-number">67</span>, <span class="hljs-number">61</span>, <span class="hljs-number">88</span>, <span class="hljs-number">23</span>, <span class="hljs-number">38</span>, <span class="hljs-number">92</span>]</pre></div><div id="3f19"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">stud</span>(<span class="hljs-params">score</span>): <span class="hljs-keyword">return</span> score < <span class="hljs-number">33</span></pre></div><div id="7844"><pre>fail_list = <span class="hljs-built_in">list</span>(<span class="hljs-attribute">filter</span>(stud, marks)) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(fail_list)</span></span></pre></div><p id="e9b8"><b>Output —</b></p><div id="33a3"><pre><span class="hljs-string">[23]</span></pre></div><h1 id="3cdc">All the Complete System Design Series Parts —</h1><blockquote id="f3fb"><p><a href="https://readmedium.com/complete-system-design-series-part-1-45bf9c8654bc"><b><i>1. System design basics</i></b></a></p></blockquote><blockquote id="c535"><p><a href="https://readmedium.com/complete-system-design-series-part-2-922f45f2faaf"><b><i>2. Horizontal and vertical scaling</i></b></a></p></blockquote><blockquote id="18a1"><p><a href="https://readmedium.com/part-3-complete-system-design-series-e1362baa8a4c"><b><i>3. Load balancing and Message queues</i></b></a></p></blockquote><blockquote id="4d43"><p><a href="https://readmedium.com/part-4-complete-system-design-series-138bc9fbcfc0"><b><i>4. High level design and low level design, Consistent Hashing, Monolithic and Microservices architecture</i></b></a></p></blockquote><blockquote id="d211"><p><a href="https://readmedium.com/part-5-complete-system-design-series-4b9b04f23608"><b><i>5. Caching, Indexing, Proxies</i></b></a></p></blockquote><blockquote id="10ec"><p><a href="https://readmedium.com/part-6-complete-system-design-series-59a2d8bbf1ed"><b><i>6. Networking, How Browsers work, Content Network Delivery ( CDN)</i></b></a></p></blockquote><blockquote id="2fb1"><p><a href="https://readmedium.com/part-7-complete-system-design-series-1bef528923d6"><b><i>7. Database Sharding, CAP Theorem, Database schema Design</i></b></a></p></blockquote><blockquote id="982a"><p><a href="https://readmedium.com/part-8-complete-system-design-series-57bc88433c8e"><b><i>8. Concurrency, API, Components + OOP + Abstraction</i></b></a></p></blockquote><blockquote id="f09e"><p><a href="https://readmedium.com/part-9-complete-system-design-series-df975c85ec51"><b><i>9. Estimation and Planning, Performance</i></b></a></p></blockquote><blockquote id="9128"><p><b><i>10. <a href="https://readmedium.com/part-10-complete-system-design-series-523b4dd978bf?sk=741f92929c8639a2e4cf218521e8cc4a">Map Reduce, Patterns and Microservices</a></i></b></p></blockquote><blockquote id="538c"><p><b><i>11. <a href="https://naina0412.medium.com/part-11-complete-system-design-series-9c8efbc0237a?sk=5bddf2adc78ea4947ae88ab21c94af1c">SQL vs NoSQL and Cloud</a></i></b></p></blockquote><blockquote id="bdf5"><p><a href="https://readmedium.com/most-popular-system-design-questions-mega-compilation-45218129fe26"><b><i>12. Most Popular System Design Questions</i></b></a></p></blockquote><h1 id="a23a">Github —</h1><div id="b414" class="link-block"> <a href="https://github.com/Coder-World04/Complete-System-Design/blob/main/README.md"> <div> <div> <h2>Complete-System-Design/README.md at main · Coder-World04/Complete-System-Design</h2> <div><h3>This repository contains everything you need to become proficient in System Design Topics you should know in System…</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div> </div> </div> </a> </div><h1 id="b4dc">Magic Methods in Python</h1><p id="4c43">In Python, Magic methods in Python are the special methods that start and end with the double underscores</p><ul><li>Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class once certain action is performed</li><li>Examples for magic methods are: new, repr, init, add, len, del etc. The init method used for initialization is invoked without any call</li><li>Use the dir() function to see the number of magic methods inherited by a class</li><li>The advantage of using Python’s magic methods is that they provide a simple way to make objects behave like built-in types</li><li>Magic methods can be used to emulate the behavior of built-in types of user-defined objects. Therefore, whenever you find yourself trying to manipulate a user-defined object’s output in a Python class, then use magic methods.</li></ul><blockquote id="41a5"><p>Example :</p></blockquote><blockquote id="5463"><p>v = 4</p></blockquote><blockquote id="2892"><p>v.add(2)</p></blockquote><p id="9f80"><b>Implementation —</b></p><div id="55bd"><pre># Del <span class="hljs-keyword">method</span></pre></div><div id="b521"><pre><span class="hljs-keyword">from</span> os.path <span class="hljs-keyword">import</span> <span class="hljs-keyword">join</span></pre></div><div id="19ee"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">FileObject:</span></pre></div><div id="e2fd"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, file_path=<span class="hljs-string">'~'</span>, file_name=<span class="hljs-string">'test.txt'</span></span>): <span class="hljs-variable language_">self</span>.file = open(join(file_path, file_name), <span class="hljs-string">'rt'</span>)</pre></div><div id="d7b4"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">del</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): <span class="hljs-variable language_">self</span>.file.close() del <span class="hljs-variable language_">self</span>.file</pre></div><p id="2b41"><b>Implementation —</b></p><div id="9d2f"><pre># repr <span class="hljs-keyword">method</span></pre></div><div id="0c60"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">String</span>:

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, string</span>):
    <span class="hljs-variable language_">self</span>.string = string</pre></div><div id="c63e"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">__repr__</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>):
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Object: {}'</span>.format(<span class="hljs-variable language_">self</span>.string)</pre></div><h1 id="2da2">Inheritance and Polymorphism in Python</h1><ul><li>In Python, Inheritance and Polymorphism are very powerful and important concept</li><li>Using inheritance you can use or inherit all the data fields and methods available in the parent class</li><li>On top of it, you can add you own methods and data fields</li><li>Python allows multiple inheritance i.e you can inherit from multiple classes</li><li>Inheritance provides a way to write better organized code and re-use the code</li></ul><p id="8aba">One of the best article I read on <a href="https://erdemisbilen.medium.com/class-inheritance-in-python-fundamentals-for-data-scientists-6a40e7ccc5db">class inheritance</a> by <a href="undefined">Erdem Isbilen</a></p><blockquote id="d6ca"><p>Syntax —</p></blockquote><blockquote id="3da4"><p>class ParentClass:</p></blockquote><blockquote id="85d1"><p>Body of parent class</p></blockquote><blockquote id="f225"><p>class DerivedClass(ParentClass):</p></blockquote><blockquote id="3be9"><p>Body of derived class</p></blockquote><ul><li>In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class</li></ul><blockquote id="b1f6"><p>Example —</p></blockquote><blockquote id="9926"><p>class X:</p></blockquote><blockquote id="e6ce"><p>def sample(self):</p></blockquote><blockquote id="6fa8"><p>print(“sample() method from class X”)</p></blockquote><blockquote id="33b7"><p>class Y(X):</p></blockquote><blockquote id="ee90"><p>def sample(self):</p></blockquote><blockquote id="9632"><p>print(“sample() method from class Y”)</p></blockquote><p id="4a3d"><b>Implementation —</b></p><div id="1298"><pre><span class="hljs-meta"># Inheritance</span></pre></div><div id="7b38"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Vehicle:</span></pre></div><div id="bf72"><pre>def __init__(self, <span class="hljs-keyword">name</span>, <span class="hljs-built_in">color</span>):
    self.__<span class="hljs-keyword">name</span> = <span class="hljs-keyword">name</span>      
    self.__<span class="hljs-built_in">color</span> = <span class="hljs-built_in">color</span></pre></div><div id="7fab"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">getColor</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>):         
    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>.__color</pre></div><div id="3f11"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">setColor</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, color</span>):  
    <span class="hljs-variable language_">self</span>.__color = color</pre></div><div id="0e30"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_Name</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>):          
    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>.__name</pre></div><div id="925b"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Bike</span>(<span class="hljs-symbol">Vehicle</span>):</pre></div><div id="6550"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, name, color, model</span>):
      
    <span class="hljs-variable language_">super</span>().__init__(name, color)       <span class="hljs-comment"># call parent class</span>
    <span class="hljs-variable language_">self</span>.__model = model</pre></div><div id="78f5"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_details</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>):
    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>.get_Name() + <span class="hljs-variable language_">self</span>.__model + <span class="hljs-string">" in "</span> +  
           <span class="hljs-variable language_">self</span>.getColor() + <span class="hljs-string">" color"</span></pre></div><div id="5479"><pre>b_obj = <span class="hljs-built_in">Bike</span>(<span class="hljs-string">"Cziar"</span>, <span class="hljs-string">"red"</span>, <span class="hljs-string">"TK720"</span>)

<span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(b_obj.get_details()</span></span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(b_obj.get_Name()</span></span>)</pre></div><p id="80d1"><b>Output —</b></p><div id="bd40"><pre>Cziar TK720 in <span class="hljs-built_in">red</span> <span class="hljs-type">color</span> Cziar</pre></div><p id="cad6"><b>Implementation —</b></p><div id="9fb8"><pre><span class="hljs-meta"># Polymorphism</span></pre></div><div id="5193"><pre><span class="hljs-keyword">from</span> <span class="hljs-built_in">math</span> <span class="hljs-keyword">import</span> pi</pre></div><div id="aaaa"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">Shape</span>: <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, name</span>): <span class="hljs-variable language_">self</span>.name = name</pre></div><div id="2fb7"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">area</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): pass</pre></div><div id="fdb3"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">Sqr</span>(<span class="hljs-title class_">Shape</span>): <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, length</span>): <span class="hljs-variable language_">super</span>().init(<span class="hljs-string">"Square"</span>) <span class="hljs-variable language_">self</span>.length = length</pre></div><div id="1d47"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">area</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>.length**<span class="hljs-number">2</span></pre></div><div id="c78c"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">Circle</span>(<span class="hljs-title class_">Shape</span>): <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, radius</span>): <span class="hljs-variable language_">super</span>().init(<span class="hljs-string">"Circle"</span>) <span class="hljs-variable language_">self</span>.radius = radius</pre></div><div id="98fa"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">area</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): <span class="hljs-keyword">return</span> pi*<span class="hljs-variable language_">self</span>.radius**<span class="hljs-number">2</span></pre></div><div id="67cc"><pre><span class="hljs-selector-tag">a</span> = <span class="hljs-built_in">Square</span>(<span class="hljs-number">6</span>) <span class="hljs-selector-tag">b</span> = <span class="hljs-built_in">Circle</span>(<span class="hljs-number">10</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(a.area()</span></span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(b.area()</span></span>)</pre></div><p id="c338"><b>Output —</b></p><div id="a492"><pre><span class="hljs-attribute">36</span> <span class="hljs-attribute">314</span>.<span class="hljs-number">1592653589793</span></pre></div><h1 id="6da2">Errors and Exception Handling in Python</h1><p id="52a3">In Python, an error can be a syntax error or an exception.</p><p id="7df7">When the parser detects an incorrect statement, Syntax errors occur.</p><ul><li>Exceptions errors are raised when an external event occurs which in some way changes the normal flow of the program</li><li>Exception error occurs whenever syntactically correct python code results in an error</li><li>Python comes with various built-in exceptions as well as the user can create user-defined exceptions</li><li>Garbage collection is the memory management feature i.e a process of cleaning shared computer memory</li></ul><p id="bfe4">Some of python’s built in exceptions —</p><blockquote id="0919"><p>IndexError : When the wrong index of a list is retrieved</p></blockquote><blockquote id="1464"><p>ImportError : When an imported module is not found</p></blockquote><blockquote id="92df"><p>KeyError : When the key of the dictionary is not found</p></blockquote><blockquote id="bdfc"><p>NameError: When the variable is not defined</p></blockquote><blockquote id="5439"><p>MemoryError : When a program run out of memory</p></blockquote><blockquote id="f1ca"><p>TypeError : When a function and operation is applied in an incorrect type</p></blockquote><blockquote id="278d"><p>AssertionError : When assert statement fails</p></blockquote><blockquote id="09b5"><p>AttributeError : When an attribute assignment is failed</p></blockquote><h1 id="2878">Try and Except in Python</h1><p id="6db3">In Python, exceptions can be handled using a try statement</p><ul><li>The block of code which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause</li><li>In case no exception has occurred, the except block is skipped and program normal flow continues</li><li>A try clause can have any number of except clauses to handle different exceptions but only one will be executed in case the exception occurs</li><li>We can also raise exceptions using the raise keyword</li><li>The try statement in Python can have an optional finally clause which executes regardless of the result of the try- and except blocks</li></ul><p id="ee3e">Example :</p><blockquote id="167b"><p>try:</p></blockquote><blockquote id="c252"><p>print(a)</p></blockquote><blockquote id="4fe2"><p>except:</p></blockquote><blockquote id="7a3a"><p>print(“Something went wrong”)</p></blockquote><blockquote id="4017"><p>finally:</p></blockquote><blockquote id="315f"><p>print(“Exit”)</p></blockquote><p id="a5f9"><b>Implementation —</b></p><div id="a8b3"><pre># <span class="hljs-keyword">try</span>, <span class="hljs-keyword">except</span>, <span class="hljs-keyword">finally</span></pre></div><div id="42fc"><pre><span class="hljs-variable"><span class="hljs-keyword">try</span></span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-number">1</span> / <span class="hljs-number">0</span>)</span> <span class="hljs-variable"><span class="hljs-keyword">except</span></span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-string">"Error occurred"</span>)</span></pre></div><div id="46d2"><pre><span class="hljs-variable"><span class="hljs-keyword">finally</span></span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-string">"Exit"</span>)</span></pre></div><p id="3856"><b>Output —</b></p><div id="8dc2"><pre><span class="hljs-keyword">Error </span>occurred Exit</pre></div><h1 id="9d57">User-defined Exceptions</h1><p id="3c9d">In Python, user can create his own error by creating a new exception class</p><ul><li>Exceptions need to be derived from the Exception class, either directly or indirectly</li><li>Exceptions errors are raised when an external event occurs which in some way changes the normal flow of the program</li><li>User defined exceptions can be implemented by raising an exception explicitly, by using assert statement or by defining custom classes for user defined exceptions</li><li>Use assert statement to implement constraints on the program. When, the condition given in assert statement is not met, the program gives AssertionError in output</li><li>You can raise an existing exception by using the raise keyword and the name of the exception</li><li>To create a custom exception class and define an error message, you need to derive the errors from the Exception class directly</li><li>When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions, this is called Hierarchical custom exceptions</li></ul><blockquote id="1388"><p>Example —</p></blockquote><blockquote id="5796"><p>class class_name(Exception)</p></blockquote><p id="be45"><b>Implementation —</b></p><div id="9a9a"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Error</span>(<span class="hljs-symbol">Exception</span>): <span class="hljs-symbol">pass</span></pre></div><div id="9ab3"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">TooSmallValueError</span>(<span class="hljs-symbol">Error</span>): <span class="hljs-symbol">pass</span></pre></div><div id="afd2"><pre><span class="hljs-attribute">number</span> <span class="hljs-operator">=</span> <span class="hljs-number">100</span></pre></div><div id="ec9d"><pre><span class="hljs-variable"><span class="hljs-keyword">while</span></span> <span class="hljs-variable"><span class="hljs-literal">True</span></span>: <span class="hljs-variable"><span class="hljs-keyword">try</span></span>: <span class="hljs-variable">num</span> = <span class="hljs-function"><span class="hljs-title">int</span>(<span class="hljs-title">input</span>(<span class="hljs-string">"Enter a number: "</span>))</span> <span class="hljs-variable"><span class="hljs-keyword">if</span></span> <span class="hljs-variable">num</span> < <span class="hljs-variable">number</span>: <span class="hljs-variable">raise</span> <span class="hljs-variable">TooSmallValueError</span> <span class="hljs-variable">break</span> <span class="hljs-variable"><span class="hljs-keyword">except</span></span> <span class="hljs-variable">TooSmallValueError</span>: <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-string">"Value too small"</span>)</span></pre></div><p id="cc89"><b>Output —</b></p><div id="dabd"><pre>Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: <span class="hljs-number">40</span> Value too small</pre></div><h1 id="0687">Garbage Collection in Python</h1><p id="002a">In Python, Garbage collection is the memory management feature i.e a process of cleaning shared computer memory which is currently being put to use by a running program when that program no longer needs that memory and can be used other programs</p><ul><li>In python, Garbage collection works automatically. Hence, python provides with good memory management and prevents the wastage of memory</li><li><i>In python, forcible garbage collection can be done by calling collect() function of the gc module</i></li><li>In python, when there is no reference left to the object in that case it is automatically destroyed by the Garbage collector of python and del() method is executed</li></ul><p id="b06a">Example :</p><blockquote id="896f"><p>import gc</p></blockquote><blockquote id="5c63"><p>gc.collect()</p></blockquote><p id="0fda"><b>Implementation —</b></p><div id="1e83"><pre><span class="hljs-meta">#manual garbage collection</span></pre></div><div id="f3ab"><pre><span class="hljs-keyword">import</span> sys, gc</pre></div><div id="675a"><pre>def <span class="hljs-built_in">test</span>(): list = [<span class="hljs-number">18</span>, <span class="hljs-number">19</span>, <span class="hljs-number">20</span>,<span class="hljs-number">34</span>,<span class="hljs-number">78</span>] list.<span class="hljs-built_in">append</span>(list)</pre></div><div id="5a16"><pre><span class="hljs-variable">def</span> <span class="hljs-function"><span class="hljs-title">main</span>(): <span class="hljs-title">print</span>(<span class="hljs-string">"Garbage Creation"</span>)</span> <span class="hljs-variable">for</span> <span class="hljs-variable">i</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-function"><span class="hljs-title">range</span>(<span class="hljs-number">5</span>): <span class="hljs-title">test</span>()</span></pre></div><div id="4d5a"><pre><span class="hljs-built_in">print</span>(<span class="hljs-string">"Collecting.."</span>) n = gc.collect() <span class="hljs-built_in">print</span>(<span class="hljs-string">"Unreachable objects collected by GC:"</span>, n) <span class="hljs-built_in">print</span>(<span class="hljs-string">"Uncollectable garbage list:"</span>, gc.garbage)</pre></div><div id="5f34"><pre><span class="hljs-keyword">if</span> name == <span class="hljs-string">"main"</span>: main() sys.<span class="hljs-keyword">exit</span>()</pre></div><p id="76a4"><b>Output —</b></p><div id="3dbb"><pre>Garbage Creation <span class="hljs-function"><span class="hljs-title">Collecting</span></span>.. Unreachable objects collected by GC: <span class="hljs-number">33</span></pre></div><h1 id="808d">Python Debugger</h1><p id="a54e">Debugging is the process of locating and solving the errors in the program. In python, pdb which is a part of Python’s standard library is used to debug the code</p><ul><li>pdb module internally makes used of bdb and cmd modules</li><li>It supports setting breakpoints and single stepping at the source line level, inspection of stack frames, source code listing etc</li></ul><p id="dee3"><b>Syntax —</b></p><blockquote id="5913"><p>import pdb</p></blockquote><blockquote id="c804"><p>pdb.set_trace()</p></blockquote><ul><li>To set the breakpoints, there is a built-in function called breakpoint()</li></ul><p id="8cd5"><b>Implementation —</b></p><div id="0e59"><pre><span class="hljs-keyword">import</span> pdb

<span class="hljs-keyword">def</span> <span class="hljs-title function_">multiply</span>(<span class="hljs-params">a, b</span>): answer = a * b <span class="hljs-keyword">return</span> answer

pdb.set_trace() a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter first number : "</span>)) b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter second number : "</span>)) <span class="hljs-built_in">sum</span> = multiply(a, b)</pre></div><h1 id="c980">Decorators in Python</h1><p id="67bb">In Python, a decorator is any callable Python object that is used to modify a function or a class. It takes a function, adds some functionality, and returns it.</p><ul><li>Decorators are a very powerful and useful tool in Python since it allows programmers to modify/control the behavior of function or class.</li><li>In Decorators, functions are passed as an argument into another function and then called inside the wrapper function.</li><li>Decorators are usually called before the definition of a function you want to decorate.</li></ul><p id="634c">There are two different kinds of decorators in Python:</p><blockquote id="fd40"><p>Function decorators</p></blockquote><blockquote id="2d2a"><p>Class decorators</p></blockquote><ul><li>When using Multiple Decorators to a single function, the decorators will be applied in the order they’ve been called</li><li>By recalling that decorator function, we can re-use the decorator</li></ul><p id="56a9"><b>Implementation —</b></p><div id="3084"><pre><span class="hljs-meta">#Decorators</span></pre></div><div id="e521"><pre><span class="hljs-variable">def</span> <span class="hljs-function"><span class="hljs-title">test_decorator</span>(<span class="hljs-variable">func</span>): <span class="hljs-variable">def</span> <span class="hljs-title">function_wrapper</span>(<span class="hljs-variable">x</span>): <span class="hljs-title">print</span>(<span class="hljs-string">"Before calling"</span> + <span class="hljs-variable">func.name</span>)</span> <span class="hljs-variable">res</span> = <span class="hljs-function"><span class="hljs-title">func</span>(<span class="hljs-variable">x</span>)</span> <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable">res</span>)</span> <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-string">"After calling"</span> + <span class="hljs-variable">func.name</span>)</span> <span class="hljs-variable">return</span> <span class="hljs-variable">function_wrapper</span></pre></div><div id="cb2d"><pre>@test_decorator def s<span class="hljs-string">qr(n)</span>: <span class="hljs-keyword">return</span> n**<span class="hljs-number">2</span> s<span class="hljs-string">qr(20)</span></pre></div><p id="22ce"><b>Output —</b></p><div id="7938"><pre><span class="hljs-built_in">Before</span> <span class="hljs-variable">callingsqr</span> <span class="hljs-number">400</span> <span class="hljs-built_in">After</span> <span class="hljs-variable">callingsqr</span></pre></div><p id="7beb"><b>Implementation —</b></p><div id="5b61"><pre><span class="hljs-meta"># Multiple Decorators</span></pre></div><div id="20dd"><pre>def lowercase_decorator(<span class="hljs-keyword">function</span>): def <span class="hljs-keyword">wrapper</span>(): func= <span class="hljs-keyword">function</span>() make_lowercase = func.lower() <span class="hljs-keyword">return</span> make_lowercase <span class="hljs-keyword">return</span> <span class="hljs-keyword">wrapper</span></pre></div><div id="e240"><pre>def split_string(<span class="hljs-keyword">function</span>): def <span class="hljs-keyword">wrapper</span>(): func= <span class="hljs-keyword">function</span>() split_string =func.split() <span class="hljs-keyword">return</span> split_string <span class="hljs-keyword">return</span> <span class="hljs-keyword">wrapper</span></pre></div><div id="90c5"><pre><span class="hljs-variable">@split_string</span> <span class="hljs-variable">@lowercase_decorator</span></pre></div><div id="f6d6"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_func</span>(): <span class="hljs-keyword">return</span> <span class="hljs-string">'MOTHER OF DRAGONS'</span> test_func()</pre></div><p id="95d1"><b>Output —</b></p><div id="7a27"><pre>[<span class="hljs-symbol">'mother</span>', <span class="hljs-symbol">'of</span>', <span class="hljs-symbol">'dragons</span>']</pre></div><h1 id="662c">Memoization using Decorators</h1><p id="e39b">In Python, memoization is a technique which allows you to optimize a Python function by caching its output based on the parameters you supply to it.</p><ul><li>Once you memoize a function, it will only compute its output once for each set of parameters you call it w

Options

ith. Every call after the first will be quickly retrieved from a cache.</li><li>If you want to speed up the parts in your program that are expensive, memoization can be a great technique to use.</li></ul><p id="9f75">One of the best article I read about <a href="https://readmedium.com/understanding-decorators-in-python-9bc55b16b5c8">Decorators</a> by <a href="undefined">Hensle Joseph</a></p><p id="c21b">There are three approaches to Memoization —</p><blockquote id="4039"><p>Using global</p></blockquote><blockquote id="b377"><p>Using objects</p></blockquote><blockquote id="d148"><p>Using default parameter</p></blockquote><blockquote id="0105"><p>Using a Callable Class</p></blockquote><p id="ba89"><b>Implementation —</b></p><div id="2a6c"><pre><span class="hljs-comment">#fibonacci series using Memoization using decorators</span></pre></div><div id="4f7d"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">memoization_func</span>(<span class="hljs-params">t</span>): dict_one = {} <span class="hljs-keyword">def</span> <span class="hljs-title function_">h</span>(<span class="hljs-params">z</span>): <span class="hljs-keyword">if</span> z <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> dict_one:
dict_one[z] = t(z) <span class="hljs-keyword">return</span> dict_one[z] <span class="hljs-keyword">return</span> h

<span class="hljs-meta">@memoization_func</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">fib</span>(<span class="hljs-params">n</span>): <span class="hljs-keyword">if</span> n == <span class="hljs-number">0</span>: <span class="hljs-keyword">return</span> <span class="hljs-number">0</span> <span class="hljs-keyword">elif</span> n == <span class="hljs-number">1</span>: <span class="hljs-keyword">return</span> <span class="hljs-number">1</span> <span class="hljs-keyword">else</span>: <span class="hljs-keyword">return</span> fib(n-<span class="hljs-number">1</span>) + fib(n-<span class="hljs-number">2</span>)</pre></div><div id="4483"><pre><span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-title">fib</span>(<span class="hljs-number">20</span>))</span></pre></div><p id="33bb"><b>Output —</b></p><div id="1330"><pre><span class="hljs-number">6765</span></pre></div><h1 id="8d6d">Defaultdict</h1><p id="82bc">In python, a dictionary is a container that holds key-value pairs. Keys must be unique, immutable objects</p><ul><li>If you try to access or modify keys that don’t exist in the dictionary, it raise a KeyError and break up your code execution. To tackle this issue, Python defaultdict type, a dictionary-like class is used</li><li>If you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it</li><li>A defaultdict will never raise a KeyError</li><li>Any key that does not exist gets the value returned by the default factory</li><li>Hence, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict</li></ul><p id="6514">Syntax —</p><blockquote id="529e"><p>from collections import defaultdict</p></blockquote><blockquote id="d3bf"><p>demo = defaultdict(int)</p></blockquote><p id="8a9a"><b>Implementation —</b></p><div id="8e96"><pre>from collections import defaultdict

default_dict_var = <span class="hljs-built_in">defaultdict</span>(list)

<span class="hljs-keyword">for</span> <span class="hljs-selector-tag">i</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>): default_dict_var<span class="hljs-selector-attr">[i]</span><span class="hljs-selector-class">.append</span>(i)

<span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(default_dict_var)</span></span></pre></div><p id="9623"><b>Output —</b></p><div id="288f"><pre>defaultdict(<class <span class="hljs-string">'list'</span>>, {<span class="hljs-number">0</span>: [<span class="hljs-number">0</span>], <span class="hljs-number">1</span>: [<span class="hljs-number">1</span>], <span class="hljs-number">2</span>: [<span class="hljs-number">2</span>], <span class="hljs-number">3</span>: [<span class="hljs-number">3</span>], <span class="hljs-number">4</span>: [<span class="hljs-number">4</span>], <span class="hljs-number">5</span>: [<span class="hljs-number">5</span>], <span class="hljs-number">6</span>: [<span class="hljs-number">6</span>], <span class="hljs-number">7</span>: [<span class="hljs-number">7</span>], <span class="hljs-number">8</span>: [<span class="hljs-number">8</span>], <span class="hljs-number">9</span>: [<span class="hljs-number">9</span>]})</pre></div><h1 id="9d9c">OrderedDict</h1><p id="d257">In python, OrderedDict is one of the high performance container datatypes and a subclass of dict object. It maintains the order in which the keys are inserted. In case of deletion or re-insertion of the key, the order is maintained and used when creating an iterator</p><ul><li>It’s a dictionary subclass that remembers the order in which its contents are added</li><li>When the value of a specified key is changed, the ordering of keys will not change for the OrderedDict</li><li>If an item is overwritten in the OrderedDict, it’s position is maintained</li><li>OrderedDict popitem removes the items in FIFO order</li><li>The reversed() function can be used with OrderedDict to iterate elements in the reverse order</li><li>OrderedDict has a move_to_end() method to efficiently reposition an element to an endpoint</li></ul><p id="e08a">Example —</p><blockquote id="b996"><p>from collections import OrderedDict</p></blockquote><blockquote id="8637"><p>my_dict = {‘Sunday’: 0, ‘Monday’: 1, ‘tuesday’: 2}</p></blockquote><blockquote id="b043"><p># creating ordered dict</p></blockquote><blockquote id="8928"><p>ordered_dict = OrderedDict(my_dict)</p></blockquote><h1 id="09dd">Generators in Python</h1><p id="1d1b">In Python, Generator functions act just like regular functions with just one difference that they use the Python <b><i>yield</i></b> keyword instead of <b><i>return</i></b> . A generator function is a function that returns an iterator A generator expression is an expression that also returns an iterator</p><ul><li>Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop.</li><li>A return statement terminates a function entirely but a yield statement pauses the function saving all its states and later continues from there on successive calls.</li><li>Generator expressions can be used as the function arguments. Just like list comprehensions, generator expressions allow you to quickly create a generator object within minutes with just a few lines of code.</li><li>The major difference between a list comprehension and a generator expression is that a list comprehension produces the entire list while the generator expression produces one item at a time as lazy evaluation. For this reason, compared to a list comprehension, a generator expression is much more memory efficient</li></ul><p id="c558">Example —</p><blockquote id="0248"><p>def generator():</p></blockquote><blockquote id="b720"><p>yield “x”</p></blockquote><blockquote id="2797"><p>yield “y”</p></blockquote><blockquote id="d570"><p>for i in generator():</p></blockquote><blockquote id="a226"><p>print(i)</p></blockquote><p id="723b"><b>Implementation —</b></p><div id="8e82"><pre>def test_sequence(): <span class="hljs-built_in">num</span> = <span class="hljs-number">0</span> <span class="hljs-keyword">while</span> <span class="hljs-built_in">num</span><<span class="hljs-number">10</span>: <span class="hljs-keyword">yield</span> <span class="hljs-built_in">num</span> <span class="hljs-built_in">num</span> += <span class="hljs-number">1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> test_sequence(): <span class="hljs-built_in">print</span>(i, end=<span class="hljs-string">","</span>)</pre></div><p id="f5f4"><b>Output —</b></p><div id="9db6"><pre><span class="hljs-attribute">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,</pre></div><p id="7b95"><b>Implementation —</b></p><div id="b929"><pre># Python generator <span class="hljs-keyword">with</span> <span class="hljs-keyword">Loop</span></pre></div><div id="c3d5"><pre>#Reverse a <span class="hljs-built_in">string</span> def reverse_str(test_str): length = <span class="hljs-built_in">len</span>(test_str) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(length - <span class="hljs-number">1</span>, <span class="hljs-number">-1</span>, <span class="hljs-number">-1</span>): <span class="hljs-built_in">yield</span> test_str[i] <span class="hljs-keyword">for</span> <span class="hljs-built_in">char</span> <span class="hljs-keyword">in</span> reverse_str(<span class="hljs-string">"Trojan"</span>): <span class="hljs-built_in">print</span>(<span class="hljs-built_in">char</span>,<span class="hljs-keyword">end</span> =<span class="hljs-string">" "</span>)</pre></div><p id="8a29"><b>Output —</b></p><div id="3975"><pre><span class="hljs-built_in">n</span> a j o r <span class="hljs-built_in">T</span></pre></div><p id="3288"><b>Implementation —</b></p><div id="a81f"><pre><span class="hljs-comment"># Generator Expression</span> <span class="hljs-comment"># Initialize the list</span> test_list = [1, 3, 6, 10] <span class="hljs-comment"># list comprehension</span> list_comprehension = [x*<span class="hljs-number">3</span> <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> test_list] <span class="hljs-comment"># generator expression</span> test_generator = (x<span class="hljs-number">*3</span> <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> test_list) <span class="hljs-built_in">print</span>(list_comprehension) <span class="hljs-built_in">print</span>(type(test_generator)) <span class="hljs-built_in">print</span>(tuple(test_generator))</pre></div><p id="068c"><b>Output —</b></p><div id="d3ea"><pre><span class="hljs-string">[1, 27, 216, 1000]</span> <<span class="hljs-keyword">class</span> '<span class="hljs-symbol">generator</span>'> (<span class="hljs-symbol">1, <span class="hljs-symbol">27</span>, <span class="hljs-symbol">216</span>, <span class="hljs-symbol">1000</span></span>)</pre></div><h1 id="7f08">Coroutine in Python</h1><ul><li>Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed</li><li>Because coroutines can pause and resume execution context, they’re well suited to concurrent processing</li><li>Coroutines are a special type of function that yield control over to the caller, but does not end its context in the process, instead maintaining it in an idle state</li><li>Using coroutines the yield directive can also be used on the right-hand side of an = operator to signify it will accept a value at that point in time.</li></ul><p id="274f">Example —</p><blockquote id="18a3"><p>def func():</p></blockquote><blockquote id="2924"><p>print(“My first Coroutine”)</p></blockquote><blockquote id="f0d0"><p>while True:</p></blockquote><blockquote id="d9ef"><p>var = (yield)</p></blockquote><blockquote id="63c3"><p>print(var)</p></blockquote><blockquote id="d22e"><p>coroutine = func()</p></blockquote><blockquote id="4723"><p>next(coroutine)</p></blockquote><p id="790a"><b>Implementation —</b></p><div id="822c"><pre>def <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">"My first Coroutine"</span>) while True: <span class="hljs-keyword">var</span> = (yield) <span class="hljs-built_in">print</span>(<span class="hljs-keyword">var</span>) coroutine = <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> next(coroutine)</pre></div><p id="f98a"><b>Output —</b></p><div id="85c9"><pre>My <span class="hljs-keyword">first</span> Coroutine</pre></div><h2 id="6fbc">Keep Learning and coding :) Peace out :)</h2><h1 id="aa82">Advanced SQL Series</h1><blockquote id="90b5"><p><b>Day 1 : <a href="https://readmedium.com/day-1-of-15-days-of-advanced-sql-series-a3676272dd5f?sk=991e8c82a9c378675080b83254ad13a2">SQL Basics and Kick start of Advanced SQL Series</a></b></p></blockquote><blockquote id="3423"><p><b>Day 2 : <a href="https://readmedium.com/day-1-of-15-days-of-advanced-sql-series-a3676272dd5f?sk=991e8c82a9c378675080b83254ad13a2">SQL Basics, Query Structure, Built In functions Conditions</a></b></p></blockquote><blockquote id="9f47"><p><b>Day 3 : <a href="https://readmedium.com/day-3-of-15-days-of-advanced-sql-series-c2ab52598a50?sk=bf9fb75360feb5d6506d04d011414d76">Most Important Commands, Joins and Filters</a></b></p></blockquote><blockquote id="b9e1"><p><b>Day 4 : <a href="https://readmedium.com/day-4-of-15-days-of-advanced-sql-series-3c06c9e1fc26?sk=336c132c67279805ba770156ed8e506d">Set Theory Operations, Stored Procedures and CASE statements in SQL</a></b></p></blockquote><blockquote id="718d"><p><b>Day 5 : <a href="https://readmedium.com/day-5-of-15-days-of-advanced-sql-series-310023a4083?sk=81c0eed74a24f3e43e54a0f087b898e7">Wildcards, Aggregation and Sequences in SQL</a></b></p></blockquote><blockquote id="daec"><p><b>Day 6 : <a href="https://readmedium.com/day-6-of-15-days-of-advanced-sql-series-548769f14138?sk=5a1b436c8b6ca2a738ba865f1972ee19">Subqueries, Group by, order by and Having clauses in SQL and Analytical Functions</a></b></p></blockquote><blockquote id="d268"><p><b>Day 7 : <a href="https://readmedium.com/day-7-of-15-days-of-advanced-sql-series-5f93bbfa734?sk=1b0e08bb48cf75d76f327053814ad4a7">Window Functions, Grouping Sets and Constraints in SQL</a></b></p></blockquote><blockquote id="fe1f"><p><b>Day 8 : <a href="https://readmedium.com/day-8-of-15-days-of-advanced-sql-series-8387b74d270?sk=2734fb4be2e7968e0fa27612785a76ed">BigQuery Basics, SELECT, FROM, WHERE and Date and Extract in BigQuery</a></b></p></blockquote><blockquote id="653c"><p><b>Day 9 : <a href="https://readmedium.com/day-9-of-15-days-of-advanced-sql-series-6bfde9f997a6?sk=fa5b407ba124825c5b3b26109999e28b">Common Expression Table, UNNEST Clause, SQL vs NoSQL Databases</a></b></p></blockquote><blockquote id="9d00"><p><b>Day 10 : <a href="https://readmedium.com/day-10-of-15-days-of-advanced-sql-series-9cb7438b1442?sk=437428d85d85281fa9c289fbafbaaa50">Triggers, Pivot and Cursors in SQL</a></b></p></blockquote><blockquote id="badc"><p><b>Day 11 : <a href="https://readmedium.com/day-11-of-15-days-of-advanced-sql-series-fbb863662786?sk=1342587e4be148ab2931280b52a3c05d">Views, Indexes and Auto Increment in SQL</a></b></p></blockquote><blockquote id="3b11"><p><b>Day 12 : <a href="https://readmedium.com/day-12-of-15-days-of-advanced-sql-series-98654987d9aa?sk=4c294f3c9807b87cceb52d6d8d7222bc">Query optimizations, Performance tuning in SQL</a></b></p></blockquote><blockquote id="8826"><p><b>Day 13 : <a href="https://readmedium.com/day-13-of-15-days-of-advanced-sql-series-991a315b73cf?sk=caacd74f6702270130e1875932e96d39">Introduction to MySQL, PostgreSQL and Mongo DB, Comparison between MySQL and PostgreSQL and Mongo DB, Introduction to SQL and NoSQL Databases</a></b></p></blockquote><blockquote id="5e9a"><p><b>Day 14 : <a href="https://readmedium.com/day-14-of-15-days-of-advanced-sql-series-c6126c3e8601?sk=221dc236be193d224b30a9d1972d3bb5">MySQL in Depth</a></b></p></blockquote><blockquote id="06b2"><p><b>Day 15 : <a href="https://readmedium.com/day-15-of-15-days-of-advanced-sql-series-9309f860bf1c?sk=4f44ece49732072fa796334f1611fc27">PostgreSQL inDepth</a></b></p></blockquote><p id="9662">Anyways, For Day 15 of 15 days of Advanced SQL, we will cover —</p><blockquote id="6da9"><p><b>PostgreSQL inDepth</b></p></blockquote><p id="bba6"><b><i>Github for Advanced SQL that you can follow —</i></b></p><div id="325c" class="link-block"> <a href="https://github.com/Coder-World04/Complete-Advanced-SQL-Series/blob/main/README.md"> <div> <div> <h2>Complete-Advanced-SQL-Series/README.md at main · Coder-World04/Complete-Advanced-SQL-Series</h2> <div><h3>This repository contains everything you need to become proficient in Advanced SQL Structured Query Language Query…</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Ryx7inaYd_Q2GsQu)"></div> </div> </div> </a> </div><p id="3f6b"><b><i>All the projects, data structures, algorithms, system design, Data Science and ML, Data Engineering, MLOps and Deep Learning videos will be published on our youtube channel ( just launched).</i></b></p><p id="f10f"><b><i>Subscribe today!</i></b></p><div id="7232" class="link-block"> <a href="https://www.youtube.com/channel/UCOdLTXh9sIiBR_s9yh3-bEQ/about"> <div> <div> <h2>Ignito</h2> <div><h3>Excited to share that we have launched our Youtube channel — Ignito to cover all the projects and coding exercise for …</h3></div> <div><p>www.youtube.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*okwkD4LOH9YJcx2S)"></div> </div> </div> </a> </div><h1 id="29d1">System Design Case Studies — In Depth</h1><blockquote id="c55d"><p><a href="https://readmedium.com/day-4-of-system-design-case-studies-series-design-instagram-part-1-10943440f29c?sk=38e68a213058e169e71754e00c501813"><b>Design Instagram</b></a></p></blockquote><blockquote id="23da"><p><a href="https://readmedium.com/day-5-of-system-design-case-studies-series-design-messenger-app-7b73c589f4a?sk=4a53b122e8f02836c17fa35622aa0309"><b>Design Messenger App</b></a></p></blockquote><blockquote id="2dc6"><p><a href="https://readmedium.com/day-7-of-system-design-case-studies-series-design-twitter-fd0722d7bb7c?sk=cdfc23d38edd5f48dc30efdcc0801c3e"><b>Design Twitter</b></a></p></blockquote><blockquote id="d605"><p><a href="https://readmedium.com/day-8-of-system-design-case-studies-series-design-url-shortener-91c812a08e0b?sk=5e20d426c91ebaacfe43031bc43642da"><b>Design URL Shortener</b></a></p></blockquote><blockquote id="1913"><p><a href="https://readmedium.com/day-9-of-system-design-case-studies-series-design-dropbox-ead523ccccfa?sk=03b3b4ea3633051f7a9a7d379b1066b8"><b>Design Dropbox</b></a></p></blockquote><blockquote id="25bf"><p><a href="https://readmedium.com/day-10-of-system-design-case-studies-series-design-youtube-58bc4ad09c4b?sk=18560ffcc3d7174566d38d60c99d4914"><b>Design Youtube</b></a></p></blockquote><blockquote id="6d16"><p><a href="https://readmedium.com/day-11-of-system-design-case-studies-series-design-api-rate-limiter-8627993c5a92?sk=fad32cada40f414aef47b7928dfb7e67"><b>Design API Rate Limiter</b></a></p></blockquote><blockquote id="3942"><p><a href="https://readmedium.com/day-12-of-system-design-case-studies-series-design-web-crawler-efba93f40030?sk=185e88e37fbc3d30dcaf41bc3863a868"><b>Design Web Crawler</b></a></p></blockquote><blockquote id="80bf"><p><a href="https://naina0412.medium.com/day-13-of-system-design-case-studies-series-design-facebooks-newsfeed-e96294c7d871?sk=f0956b536721902c7da6a1ec8e2f0880"><b>Design Facebook’s Newsfeed</b></a></p></blockquote><blockquote id="2353"><p><a href="https://readmedium.com/day-14-of-system-design-case-studies-series-design-yelp-af432d13e838?sk=55e19b7d8ad43c4109e9b1694678c177"><b>Design Yelp</b></a></p></blockquote><blockquote id="dcb7"><p><a href="https://readmedium.com/day-15-of-system-design-case-studies-series-design-uber-2adc612701d?sk=d1c5481fcfd4f30e84074e5a5d7c548e"><b>Design Uber</b></a></p></blockquote><blockquote id="580e"><p><a href="https://readmedium.com/day-16-of-system-design-case-studies-series-design-tinder-a0867163f449?sk=6313f0b9760c3d78a17443a98bdb3330"><b>Design Tinder</b></a></p></blockquote><blockquote id="6b84"><p><a href="https://readmedium.com/day-17-of-system-design-case-studies-series-design-tiktok-58e5a93bcfb5?sk=5eed7cbac7af8b6506951417514ec8e0"><b>Design Tiktok</b></a></p></blockquote><blockquote id="1a51"><p><a href="https://readmedium.com/day-18-of-system-design-case-studies-series-design-whatsapp-38ec39f32b44?sk=89cc7003e78917fd65330ad56a7ed8f0"><b>Design Whatsapp</b></a></p></blockquote><blockquote id="86fc"><p><a href="https://readmedium.com/most-popular-system-design-questions-mega-compilation-45218129fe26?sk=6432dd01c067dd28bc81da1dfceccdab"><b>Most Popular System Design Questions</b></a></p></blockquote><blockquote id="ac9c"><p><a href="https://readmedium.com/quick-roundup-solved-system-design-case-studies-6ad776d437cf?sk=e42f56968e1b592382f484c222e7c111"><b>Mega Compilation : Solved System Design Case studies</b></a></p></blockquote><h1 id="c325">Complete Data Structures and Algorithm Series</h1><blockquote id="c8f1"><p><a href="https://readmedium.com/day-4-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-83d4c90d9115?sk=8ab3d284915f8f28534651d1c9cf41e5"><b>Complexity Analysis</b></a></p></blockquote><blockquote id="c155"><p><a href="https://readmedium.com/day-5-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-backtracking-f7de93dbe72d?sk=08c8ce11404387e46fdd73013aec267f"><b>Backtracking</b></a></p></blockquote><blockquote id="66fd"><p><a href="https://readmedium.com/day-3-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-af62dc4aec9c?sk=704354dbc4c0048ac0a0b5c97f1eef0e"><b>Sliding Window</b></a></p></blockquote><blockquote id="da37"><p><a href="https://readmedium.com/day-6-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-greedy-technique-4b219a8488d0?sk=540b74ce2d13f345dd00cbbfb252815f"><b>Greedy Technique</b></a></p></blockquote><blockquote id="d262"><p><a href="https://readmedium.com/day-8-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-two-pointer-7c513302dfa9?sk=cc32bc3ce22139845c64d195553859e0"><b>Two pointer Technique</b></a></p></blockquote><blockquote id="43b9"><p><a href="https://readmedium.com/day-11-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-arrays-bf7045a3c98b?sk=42ad70a29aa9f7891794d7feaa63bea9"><b>Arrays</b></a></p></blockquote><blockquote id="8dbb"><p><a href="https://readmedium.com/day-13-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-linked-list-6536f0041153?sk=952899c3d2e2bd5b4dbd6c8ad7debf05"><b>Linked List</b></a></p></blockquote><blockquote id="29e2"><p><a href="https://readmedium.com/day-12-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-strings-fa27c45a5fd6?sk=f6b3fc7bf5c770d2d04107667be1c446"><b>Strings</b></a></p></blockquote><blockquote id="95aa"><p><a href="https://readmedium.com/day-14-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-stack-b26d68eb3477?sk=ed28cc4e45134ad3562a3594ddea4017"><b>Stack</b></a></p></blockquote><blockquote id="07fc"><p><a href="https://readmedium.com/day-15-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-queue-db38d5477cd5?sk=44ae516bf0f1da510ee9618b7f135995"><b>Queues</b></a></p></blockquote><blockquote id="0e08"><p><a href="https://readmedium.com/day-17-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-hash-ddfe72657211?sk=a457b598d5f5f3d2572029693c587198"><b>Hash Table/Hashing</b></a></p></blockquote><blockquote id="b6d3"><p><a href="https://readmedium.com/day-16-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-binary-search-8799ce6321cb?sk=e4ee1b96f1cd2f9531b5e739539d8b7e"><b>Binary Search</b></a></p></blockquote><blockquote id="5586"><p><a href="https://readmedium.com/day-7-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-1-d-dynamic-2560f585499?sk=0756b6bd798238d9a96fe3d161690350"><b>1- D Dynamic Programming</b></a></p></blockquote><blockquote id="be69"><p><a href="https://readmedium.com/day-10-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-divide-and-a00f7375507?sk=3d52023dade6f37c396b58e039ca29f2"><b>Divide and Conquer Technique</b></a></p></blockquote><blockquote id="b173"><p><a href="https://readmedium.com/day-9-of-30-days-of-data-structures-and-algorithms-and-system-design-simplified-recursion-ed6f7f41742?sk=bf98ce6abdb3e3f2fa71213c6ed8caa9"><b>Recursion</b></a></p></blockquote><p id="9215"><b>Github —</b></p><div id="3244" class="link-block"> <a href="https://github.com/Coder-World04/Complete-Data-Structures-and-Algorithms"> <div> <div> <h2>GitHub — Coder-World04/Complete-Data-Structures-and-Algorithms: This repository contains everything…</h2> <div><h3>This repository contains everything you need to become proficient in Data Structures and Algorithms Start here : Day 1…</h3></div> <div><p>github.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*82WWl4vZvYx1zwkR)"></div> </div> </div> </a> </div><h1 id="fa23">Want to read programmers humor?</h1><div id="fd28" class="link-block"> <a href="https://readmedium.com/programming-humor-part-2-f92cf5a26f2b"> <div> <div> <h2>Programming Humor Part 2</h2> <div><h3>Keep laughing because it’s hilarious ….</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*xkCXqHz7vIXjmjD_.png)"></div> </div> </div> </a> </div><div id="1e2f" class="link-block"> <a href="https://readmedium.com/the-most-hilarious-code-comments-ever-bae3cb1030b5"> <div> <div> <h2>The Most Hilarious Code Comments Ever</h2> <div><h3>Programmer Humor: Yes, coders actually wrote them!</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*C-cPP9D2MIyeexAT.gif)"></div> </div> </div> </a> </div><div id="93a8" class="link-block"> <a href="https://readmedium.com/coding-sins-hilarious-developer-confessions-f55eb342454e"> <div> <div> <h2>Coding Sins: Hilarious Developer Confessions</h2> <div><h3>How ‘whiteboarding’ got mocked</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*JceCvoRHEHRXyHnb.jpeg)"></div> </div> </div> </a> </div><div id="052b" class="link-block"> <a href="https://readmedium.com/10-witty-programming-jokes-that-will-make-you-go-rofl-a53fbfb91943"> <div> <div> <h2>10 Witty Programming Jokes That Will Make You Go ROFL</h2> <div><h3>These are hilarious ….</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*c6MUlOF-1Z2Su0-E)"></div> </div> </div> </a> </div><h1 id="b5de">Recommended Articles -</h1><div id="f7a3" class="link-block"> <a href="https://readmedium.com/python-iterators-generators-and-decorators-made-easy-659cae26054f"> <div> <div> <h2>Python Iterators, Generators And Decorators Made Easy</h2> <div><h3>A Quick Implementation Guide</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*XtVnWXUTVVE13f3-.jpeg)"></div> </div> </div> </a> </div><div id="70ed" class="link-block"> <a href="https://readmedium.com/23-data-science-techniques-you-should-know-61bc2c9d1b3a"> <div> <div> <h2>23 Data Science Techniques You Should Know!</h2> <div><h3>Save your precious time by using these hacks</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*222j6BFuGGqZxksgOHa4kg.png)"></div> </div> </div> </a> </div><div id="b8f3" class="link-block"> <a href="https://readmedium.com/coding-sins-hilarious-developer-confessions-f55eb342454e"> <div> <div> <h2>Coding Sins: Hilarious Developer Confessions</h2> <div><h3>How ‘whiteboarding’ got mocked</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*JceCvoRHEHRXyHnb.jpeg)"></div> </div> </div> </a> </div><div id="c55e" class="link-block"> <a href="https://readmedium.com/5-cool-advanced-pandas-techniques-for-data-scientists-c5a59ae0625d"> <div> <div> <h2>5 Cool Advanced Pandas Techniques for Data Scientists</h2> <div><h3>Use these techniques …</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*nd1WG4uRgLzMQr8P.jpeg)"></div> </div> </div> </a> </div><div id="bbb9" class="link-block"> <a href="https://readmedium.com/stack-overflow-analyzed-data-from-60-000-software-developers-hours-they-work-languages-they-476ac6ca0197"> <div> <div> <h2>Stack Overflow Analyzed Data from 60,000+ Software Developers — Hours They Work, Languages They…</h2> <div><h3>Here is what they found…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*LWGz2247yyjKfW6g.png)"></div> </div> </div> </a> </div><div id="4965" class="link-block"> <a href="https://readmedium.com/advanced-python-made-easy-part-4-a4996ba9fe19"> <div> <div> <h2>Advanced Python Made Easy — Part 4</h2> <div><h3>Use these hacks and techniques…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*nd1WG4uRgLzMQr8P.jpeg)"></div> </div> </div> </a> </div><div id="1938" class="link-block"> <a href="https://readmedium.com/advanced-python-made-easy-part-1-ce1e2f17431e"> <div> <div> <h2>Advanced Python Made Easy — Part 1</h2> <div><h3>Use these hacks and techniques…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*nd1WG4uRgLzMQr8P.jpeg)"></div> </div> </div> </a> </div></article></body>

Python Crash Course — Part 2

With Code Implementation…

You can find Python Crash Course — Part 1 —

This is the part 2 of Python Crash Course.

Some of the other best Series —

30 Days of Natural Language Processing ( NLP) Series

How to solve any System Design Question ( approach that you can take)?

30 days of Data Engineering with projects Series

60 days of Data Science and ML Series with projects

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

30 days of Machine Learning Ops

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

System Design Case Studies — In Depth

Design Instagram

Design Messenger App

Design Twitter

Design URL Shortener

Design Dropbox

Mega Compilation : Solved System Design Case studies

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

Introduction to Functions in Python

In python, functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it, define interfaces and save a lot of time

  • A function can be called multiple times to provide modularity and reusability to the python program
  • We can easily track a large python program easily when it is divided into multiple functions
  • There are mainly two types of functions —

User-define functions — Defined by the user to perform the specific task

Built-in functions — Functions which are pre-defined

  • You can define the function using the def keyword
  • Arguments is the information that’s passed into the function
  • The return statement is used to return the value. A function can have only one return
  • Once created, we can call the function using the function name followed by the parentheses

Example :

def my_function(parameters):

print(“My first Function”)

return expression

#calling the function

my_function()

Private Variables in Python

In python, a variable is a named location used to store or hold the value/data in the memory.

  • When we create a variable inside a function, it is local by default
  • We create Private Variables by using underscore _ before a named prefix
  • This is quite helpful for letting subclasses override methods without breaking intraclass method calls

There are three ways private variables can be implemented :

_Single Leading Underscores

__Double Leading Underscores

__Double leading and Double trailing underscores__

  • __name__ is a special built-in variable which points to the name of the current module

Example :

_program

__var

__len__

Implementation —

# Private Variable 
#Single underscore (_)
class test:
    def __init__(self,num):
        self._num= num#_privatemethod private method
    def _numfunc(self):
        print("Hello")obj=test(156)
#_ attributes can be accessed as normal variables
obj._numfunc()

Implementation —

# Private Variable 
#Double Underscore (__)class test:
    def __init__(self,num):
        self.__num= num
    def Print(self):
        print("__num = {}".format(self.__num))obj=test(156)

Implementation —

# Private Variable 
#Trailing underscore(n_)class Test:
    def __init__(self,c):
        #To avoid clash with python keyword 
        self.num_= num

Global and Non Local Variables in Python

When we create a variable inside a function, it is local by default. When we define a variable outside of a function, it is global by default

  • Nonlocal variables are used in nested functions whose local scope is not defined
  • Global variables are those variables which are defined and declared outside a function and we can use them inside the function or we can use global keyword to make a variable global inside a function

Example :

global variable_name

Implementation —

#Local Variabledef test():
    l = "local_variable"
    return lvar=test()
print(var)

Output —

local_variable

Implementation —

#Global Variablevar = 10def test():
    var = 20
    print("local variable x:", var)val=test()
print("global variable x:", var)

Output —

local variable x: 20
global variable x: 10

Implementation —

#Non Local Variabledef test():
    var = "local_variable"def test_one():
        nonlocal var
        var = "non_local_variable"
        print("Non Local value:", var)
    test_one()
    print("Outer value:", var)
test()

First Class functions in Python

In python, a function in Python is First Class Function, if it supports all of the properties of a First Class object such as —

It is an instance of an Object type

Pass First Class Function as argument of some other functions

Return Functions from other function

Store Functions in lists, sets or some other data structures

Functions can be stored as variable

  • In Python, a function can be assigned as variable which is used without function parentheses
  • Functions are objects you can pass them as arguments to other functions
  • First-class functions allow you to pass around behavior and abstract
  • Closure functions — Functions are be nested and they can carry forward parent function’s state with them

Example :

def func1(func):

var = func(‘Hello World’)

print(var)

Implementation —

#Implementation 2
def outer(a):   # Outer functiondef inner(b):   # Inner function
        return b+10
    return inner(a)a = 10
var = outer(a) 
print(var)

Output —

20

__import__() function

In python, the inbuilt __import__() function helps to import modules in runtime

Syntax —

__import__(name, globals, locals, fromlist, level)

  • name : Name of the module to import.
  • globals : Dictionary of global names used to determine how to interpret the name in a package context.
  • locals : Dictionary of local names names used to determine how to interpret the name in a package context.
  • fromlist : The fromlist gives the names of objects or submodules that should be imported from the module given by name.
  • level : level specifies whether to use absolute or relative imports.
  • To import a module by name, use importlib.import_module()

Example :

_var = __import__(‘spam.ham’, globals(), locals(), [], -1)

Implementation —

#implementation
#fabs() method is defined in the math module which returns the #absolute value of a number
math_score = __import__('math', globals(), locals(), [], 0)
print(math_score.fabs(-17.4))

Output —

17.4

Tuple Unpacking with Python Functions

In python, tuples are immutable data types. Python offers a very powerful tuple assignment tool that maps right hand side arguments into left hand side arguments i.e mapping is known as unpacking of a tuple of values into a normal variable.

  • During the unpacking of tuple, the total number of variables on the left-hand side should be equivalent to the total number of values in given tuple
  • It uses a special syntax to pass optional arguments (*args) for tuple unpacking

Example :

days = (“sunday”, “monday”, “tuesday”,”wednesday”,”thursday”)

(day1, day2, *day) = days

Implementation —

def result(a, b):
    return a + b
# function with normal variables
print (result(100, 200))
 
# A tuple is created
c = (100, 300)
 
# Tuple is passed
# function unpacked them
 
print (result(*c))

Output —

300
400

Static Variables and Methods in Python

In Python, Static variables are the variables that belong to the class and not to objects.

  • Static variables are shared amongst objects of the class
  • Python allows providing same variable name for a class/static variable and an instance variable

One of the best article I read on Functions by

Neel Gorasiya

Static Method -

  • In Python, Static methods are the methods which are bound to the class rather than an object of the class
  • Static Methods are called using the class name and not the objects of the class
  • Static methods are bound to the class
  • There are two ways of defining a static method:

@staticmethod

staticmethod()

Example :

class class_name:

@staticmethod

def function_name(parameters):

print(var)

Implementation —

class test:
    static_variable = 25 # Access through classprint(test.static_variable) # prints 5# Access through an instance
ins = test()
print(ins.static_variable) # still 5# Change within an instance
ins.static_variable = 14
print(ins.static_variable) 
print(test.static_variable)

Output —

25
25
14
25

Implementation —

# Static Method : Use @staticmethod
class sample_shape:
    
    @staticmethod
    def msgg(msg):
        print(msg)
        print("Triangles")
        
sample_shape.msgg("Welcome to sample shape class")

Output —

Welcome to sample shape class
Triangles

Lambda Functions in Python

In python, Lambda is used to create small anonymous functions using “lambda” keyword and can be used wherever function objects are needed.It can any number of arguments but only one expression

Syntax :

lambda argument(s): expression

  • It can be used inside another function
  • In python normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword
  • Whenever we require a nameless function for a short period of time, we use lambda functions

Example :

var = lambda x: x * 5

Implementation —

#A lambda function that adds 10 to the number passed in as an #argument, and print the result
x = lambda a, b, c : a * b + c
print(x(5, 6, 8))

Output —

38

Map and Filter Functions in Python

In python, Map allows you to process and transform the items of the iterables or collections without using a for loop.

  • In Python, the map() function applies the given function to each item of a given iterable construct (i.e lists, tuples etc) and returns a map object

Syntax —

map(function, iterable)

  • In python, filter() function returns an iterator when the items are filtered through a function to test if the item is true or not

Syntax —

filter(function, iterable)

where function is the to be run for each item in the iterable

iterable is the iterable to be filtered

Example :

result = map(lambda x: x+x, numbers)

var = filter(function_name, sequence)

Implementation —

#map
numbers = [1,2,3,4,5]
strings = ['s', 't', 'x', 'y', 'z']
mapped_list = list(map(lambda x, y: (x, y), strings, numbers))
print(mapped_list)

Output —

[('s', 1), ('t', 2), ('x', 3), ('y', 4), ('z', 5)]

Implementation —

#map implementation
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday']
mod_days = list(map(str.swapcase, days))
print(mod_days)

Output —

['sUNDAY', 'mONDAY', 'tUESDAY', 'wEDNESDAY']

Implementation —

#Filter function
marks = [95, 40, 68, 95, 67, 61, 88, 23, 38, 92]
def stud(score):
    return score < 33
fail_list = list(filter(stud, marks))
print(fail_list)

Output —

[23]

All the Complete System Design Series Parts —

1. System design basics

2. Horizontal and vertical scaling

3. Load balancing and Message queues

4. High level design and low level design, Consistent Hashing, Monolithic and Microservices architecture

5. Caching, Indexing, Proxies

6. Networking, How Browsers work, Content Network Delivery ( CDN)

7. Database Sharding, CAP Theorem, Database schema Design

8. Concurrency, API, Components + OOP + Abstraction

9. Estimation and Planning, Performance

10. Map Reduce, Patterns and Microservices

11. SQL vs NoSQL and Cloud

12. Most Popular System Design Questions

Github —

Magic Methods in Python

In Python, Magic methods in Python are the special methods that start and end with the double underscores

  • Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class once certain action is performed
  • Examples for magic methods are: __new__, __repr__, __init__, __add__, __len__, __del__ etc. The __init__ method used for initialization is invoked without any call
  • Use the dir() function to see the number of magic methods inherited by a class
  • The advantage of using Python’s magic methods is that they provide a simple way to make objects behave like built-in types
  • Magic methods can be used to emulate the behavior of built-in types of user-defined objects. Therefore, whenever you find yourself trying to manipulate a user-defined object’s output in a Python class, then use magic methods.

Example :

v = 4

v.__add__(2)

Implementation —

# __Del__ method
from os.path import join
class FileObject:
def __init__(self, file_path='~', file_name='test.txt'):
        self.file = open(join(file_path, file_name), 'rt')
def __del__(self):
        self.file.close()
        del self.file

Implementation —

# __repr__ method
class String:
      
    def __init__(self, string):
        self.string = string
def __repr__(self):
        return 'Object: {}'.format(self.string)

Inheritance and Polymorphism in Python

  • In Python, Inheritance and Polymorphism are very powerful and important concept
  • Using inheritance you can use or inherit all the data fields and methods available in the parent class
  • On top of it, you can add you own methods and data fields
  • Python allows multiple inheritance i.e you can inherit from multiple classes
  • Inheritance provides a way to write better organized code and re-use the code

One of the best article I read on class inheritance by Erdem Isbilen

Syntax —

class ParentClass:

Body of parent class

class DerivedClass(ParentClass):

Body of derived class

  • In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class

Example —

class X:

def sample(self):

print(“sample() method from class X”)

class Y(X):

def sample(self):

print(“sample() method from class Y”)

Implementation —

# Inheritance
class Vehicle:
def __init__(self, name, color):
        self.__name = name      
        self.__color = color
def getColor(self):         
        return self.__color
def setColor(self, color):  
        self.__color = color
def get_Name(self):          
        return self.__name
class Bike(Vehicle):
def __init__(self, name, color, model):
          
        super().__init__(name, color)       # call parent class
        self.__model = model
def get_details(self):
        return self.get_Name() + self.__model + " in " +  
               self.getColor() + " color"
b_obj = Bike("Cziar", "red", "TK720")
print(b_obj.get_details())
print(b_obj.get_Name())

Output —

Cziar TK720 in red color
Cziar

Implementation —

# Polymorphism
from math import pi
class Shape:
    def __init__(self, name):
        self.name = name
def area(self):
        pass
class Sqr(Shape):
    def __init__(self, length):
        super().__init__("Square")
        self.length = length
def area(self):
        return self.length**2
class Circle(Shape):
    def __init__(self, radius):
        super().__init__("Circle")
        self.radius = radius
def area(self):
        return pi*self.radius**2
a = Square(6)
b = Circle(10)
print(a.area())
print(b.area())

Output —

36
314.1592653589793

Errors and Exception Handling in Python

In Python, an error can be a syntax error or an exception.

When the parser detects an incorrect statement, Syntax errors occur.

  • Exceptions errors are raised when an external event occurs which in some way changes the normal flow of the program
  • Exception error occurs whenever syntactically correct python code results in an error
  • Python comes with various built-in exceptions as well as the user can create user-defined exceptions
  • Garbage collection is the memory management feature i.e a process of cleaning shared computer memory

Some of python’s built in exceptions —

IndexError : When the wrong index of a list is retrieved

ImportError : When an imported module is not found

KeyError : When the key of the dictionary is not found

NameError: When the variable is not defined

MemoryError : When a program run out of memory

TypeError : When a function and operation is applied in an incorrect type

AssertionError : When assert statement fails

AttributeError : When an attribute assignment is failed

Try and Except in Python

In Python, exceptions can be handled using a try statement

  • The block of code which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause
  • In case no exception has occurred, the except block is skipped and program normal flow continues
  • A try clause can have any number of except clauses to handle different exceptions but only one will be executed in case the exception occurs
  • We can also raise exceptions using the raise keyword
  • The try statement in Python can have an optional finally clause which executes regardless of the result of the try- and except blocks

Example :

try:

print(a)

except:

print(“Something went wrong”)

finally:

print(“Exit”)

Implementation —

# try, except, finally
try:
     print(1 / 0)
except:
     print("Error occurred")
finally:
     print("Exit")

Output —

Error occurred
Exit

User-defined Exceptions

In Python, user can create his own error by creating a new exception class

  • Exceptions need to be derived from the Exception class, either directly or indirectly
  • Exceptions errors are raised when an external event occurs which in some way changes the normal flow of the program
  • User defined exceptions can be implemented by raising an exception explicitly, by using assert statement or by defining custom classes for user defined exceptions
  • Use assert statement to implement constraints on the program. When, the condition given in assert statement is not met, the program gives AssertionError in output
  • You can raise an existing exception by using the raise keyword and the name of the exception
  • To create a custom exception class and define an error message, you need to derive the errors from the Exception class directly
  • When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions, this is called Hierarchical custom exceptions

Example —

class class_name(Exception)

Implementation —

class Error(Exception):
    pass
class TooSmallValueError(Error):
    pass
number = 100
while True:
    try:
        num = int(input("Enter a number: "))
        if num < number:
            raise TooSmallValueError
        break
    except TooSmallValueError:
        print("Value too small")

Output —

Enter a number: 40
Value too small

Garbage Collection in Python

In Python, Garbage collection is the memory management feature i.e a process of cleaning shared computer memory which is currently being put to use by a running program when that program no longer needs that memory and can be used other programs

  • In python, Garbage collection works automatically. Hence, python provides with good memory management and prevents the wastage of memory
  • In python, forcible garbage collection can be done by calling collect() function of the gc module
  • In python, when there is no reference left to the object in that case it is automatically destroyed by the Garbage collector of python and __del__() method is executed

Example :

import gc

gc.collect()

Implementation —

#manual garbage collection
import sys, gc
def test():
    list = [18, 19, 20,34,78]
    list.append(list)
def main():
    print("Garbage Creation")
    for i in range(5):
        test()
print("Collecting..")
    n = gc.collect()
    print("Unreachable objects collected by GC:", n)
    print("Uncollectable garbage list:", gc.garbage)
if __name__ == "__main__":
    main()
    sys.exit()

Output —

Garbage Creation
Collecting..
Unreachable objects collected by GC: 33

Python Debugger

Debugging is the process of locating and solving the errors in the program. In python, pdb which is a part of Python’s standard library is used to debug the code

  • pdb module internally makes used of bdb and cmd modules
  • It supports setting breakpoints and single stepping at the source line level, inspection of stack frames, source code listing etc

Syntax —

import pdb

pdb.set_trace()

  • To set the breakpoints, there is a built-in function called breakpoint()

Implementation —

import pdb
   
def multiply(a, b):
    answer = a * b
    return answer
  
pdb.set_trace()
a = int(input("Enter first number : "))
b = int(input("Enter second number : "))
sum = multiply(a, b)

Decorators in Python

In Python, a decorator is any callable Python object that is used to modify a function or a class. It takes a function, adds some functionality, and returns it.

  • Decorators are a very powerful and useful tool in Python since it allows programmers to modify/control the behavior of function or class.
  • In Decorators, functions are passed as an argument into another function and then called inside the wrapper function.
  • Decorators are usually called before the definition of a function you want to decorate.

There are two different kinds of decorators in Python:

Function decorators

Class decorators

  • When using Multiple Decorators to a single function, the decorators will be applied in the order they’ve been called
  • By recalling that decorator function, we can re-use the decorator

Implementation —

#Decorators
def test_decorator(func):
    def function_wrapper(x):
        print("Before calling" + func.__name__)
        res = func(x)
        print(res)
        print("After calling" + func.__name__)
    return function_wrapper
@test_decorator
def sqr(n):
    return n**2
sqr(20)

Output —

Before callingsqr
400
After callingsqr

Implementation —

# Multiple Decorators
def lowercase_decorator(function):
    def wrapper():
        func= function()
        make_lowercase = func.lower()
        return make_lowercase
    return wrapper
def split_string(function):
    def wrapper():
        func= function()
        split_string =func.split()
        return split_string
    return wrapper
@split_string
@lowercase_decorator
def test_func():
    return 'MOTHER OF DRAGONS'
test_func()

Output —

['mother', 'of', 'dragons']

Memoization using Decorators

In Python, memoization is a technique which allows you to optimize a Python function by caching its output based on the parameters you supply to it.

  • Once you memoize a function, it will only compute its output once for each set of parameters you call it with. Every call after the first will be quickly retrieved from a cache.
  • If you want to speed up the parts in your program that are expensive, memoization can be a great technique to use.

One of the best article I read about Decorators by Hensle Joseph

There are three approaches to Memoization —

Using global

Using objects

Using default parameter

Using a Callable Class

Implementation —

#fibonacci series using Memoization using decorators
def memoization_func(t):
    dict_one = {}
    def h(z):
        if z not in dict_one:            
            dict_one[z] = t(z)
        return dict_one[z]
    return h
    
@memoization_func
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
print(fib(20))

Output —

6765

Defaultdict

In python, a dictionary is a container that holds key-value pairs. Keys must be unique, immutable objects

  • If you try to access or modify keys that don’t exist in the dictionary, it raise a KeyError and break up your code execution. To tackle this issue, Python defaultdict type, a dictionary-like class is used
  • If you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it
  • A defaultdict will never raise a KeyError
  • Any key that does not exist gets the value returned by the default factory
  • Hence, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict

Syntax —

from collections import defaultdict

demo = defaultdict(int)

Implementation —

from collections import defaultdict 
     
default_dict_var = defaultdict(list) 
  
for i in range(10): 
    default_dict_var[i].append(i) 
  
print(default_dict_var)

Output —

defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6], 7: [7], 8: [8], 9: [9]})

OrderedDict

In python, OrderedDict is one of the high performance container datatypes and a subclass of dict object. It maintains the order in which the keys are inserted. In case of deletion or re-insertion of the key, the order is maintained and used when creating an iterator

  • It’s a dictionary subclass that remembers the order in which its contents are added
  • When the value of a specified key is changed, the ordering of keys will not change for the OrderedDict
  • If an item is overwritten in the OrderedDict, it’s position is maintained
  • OrderedDict popitem removes the items in FIFO order
  • The reversed() function can be used with OrderedDict to iterate elements in the reverse order
  • OrderedDict has a move_to_end() method to efficiently reposition an element to an endpoint

Example —

from collections import OrderedDict

my_dict = {‘Sunday’: 0, ‘Monday’: 1, ‘tuesday’: 2}

# creating ordered dict

ordered_dict = OrderedDict(my_dict)

Generators in Python

In Python, Generator functions act just like regular functions with just one difference that they use the Python yield keyword instead of return . A generator function is a function that returns an iterator A generator expression is an expression that also returns an iterator

  • Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop.
  • A return statement terminates a function entirely but a yield statement pauses the function saving all its states and later continues from there on successive calls.
  • Generator expressions can be used as the function arguments. Just like list comprehensions, generator expressions allow you to quickly create a generator object within minutes with just a few lines of code.
  • The major difference between a list comprehension and a generator expression is that a list comprehension produces the entire list while the generator expression produces one item at a time as lazy evaluation. For this reason, compared to a list comprehension, a generator expression is much more memory efficient

Example —

def generator():

yield “x”

yield “y”

for i in generator():

print(i)

Implementation —

def test_sequence():
    num = 0
    while num<10:
        yield num
        num += 1
for i in test_sequence():
       print(i, end=",")

Output —

0,1,2,3,4,5,6,7,8,9,

Implementation —

# Python generator with Loop
#Reverse a string
def reverse_str(test_str):
    length = len(test_str)
    for i in range(length - 1, -1, -1):
        yield test_str[i]
for char in reverse_str("Trojan"):
    print(char,end =" ")

Output —

n a j o r T

Implementation —

# Generator Expression
# Initialize the list
test_list = [1, 3, 6, 10]
# list comprehension
list_comprehension = [x**3 for x in test_list]
# generator expression
test_generator = (x**3 for x in test_list)
print(list_comprehension)
print(type(test_generator))
print(tuple(test_generator))

Output —

[1, 27, 216, 1000]
<class 'generator'>
(1, 27, 216, 1000)

Coroutine in Python

  • Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed
  • Because coroutines can pause and resume execution context, they’re well suited to concurrent processing
  • Coroutines are a special type of function that yield control over to the caller, but does not end its context in the process, instead maintaining it in an idle state
  • Using coroutines the yield directive can also be used on the right-hand side of an = operator to signify it will accept a value at that point in time.

Example —

def func():

print(“My first Coroutine”)

while True:

var = (yield)

print(var)

coroutine = func()

next(coroutine)

Implementation —

def func(): 
            print("My first Coroutine") 
            while True: 
                         var = (yield) 
                         print(var) 
coroutine = func() 
next(coroutine)

Output —

My first Coroutine

Keep Learning and coding :) Peace out :)

Advanced SQL Series

Day 1 : SQL Basics and Kick start of Advanced SQL Series

Day 2 : SQL Basics, Query Structure, Built In functions Conditions

Day 3 : Most Important Commands, Joins and Filters

Day 4 : Set Theory Operations, Stored Procedures and CASE statements in SQL

Day 5 : Wildcards, Aggregation and Sequences in SQL

Day 6 : Subqueries, Group by, order by and Having clauses in SQL and Analytical Functions

Day 7 : Window Functions, Grouping Sets and Constraints in SQL

Day 8 : BigQuery Basics, SELECT, FROM, WHERE and Date and Extract in BigQuery

Day 9 : Common Expression Table, UNNEST Clause, SQL vs NoSQL Databases

Day 10 : Triggers, Pivot and Cursors in SQL

Day 11 : Views, Indexes and Auto Increment in SQL

Day 12 : Query optimizations, Performance tuning in SQL

Day 13 : Introduction to MySQL, PostgreSQL and Mongo DB, Comparison between MySQL and PostgreSQL and Mongo DB, Introduction to SQL and NoSQL Databases

Day 14 : MySQL in Depth

Day 15 : PostgreSQL inDepth

Anyways, For Day 15 of 15 days of Advanced SQL, we will cover —

PostgreSQL inDepth

Github for Advanced SQL that you can follow —

All the projects, data structures, algorithms, system design, Data Science and ML, Data Engineering, MLOps and Deep Learning videos will be published on our youtube channel ( just launched).

Subscribe today!

System Design Case Studies — In Depth

Design Instagram

Design Messenger App

Design Twitter

Design URL Shortener

Design Dropbox

Design Youtube

Design API Rate Limiter

Design Web Crawler

Design Facebook’s Newsfeed

Design Yelp

Design Uber

Design Tinder

Design Tiktok

Design Whatsapp

Most Popular System Design Questions

Mega Compilation : Solved System Design Case studies

Complete Data Structures and Algorithm Series

Complexity Analysis

Backtracking

Sliding Window

Greedy Technique

Two pointer Technique

Arrays

Linked List

Strings

Stack

Queues

Hash Table/Hashing

Binary Search

1- D Dynamic Programming

Divide and Conquer Technique

Recursion

Github —

Want to read programmers humor?

Recommended Articles -

Machine Learning
Python
Data Science
Tech
Programming
Recommended from ReadMedium