This post explains how to solve leetcode problem – 21. merge two sorted list – using python 3. Let’s take a look at an example. Let’s say there are two lists: 1 -> 3 -> 5 and 2 -> 4. After merging those lists, the expected answer is 1 -> 2 -> 3 -> 4 -> 5. You are supposed to merge the list in sorted order. This problem doesn’t require any tricks but you just need to be able to operate on iterating and merging the list. With that said, the algorithm is very simple.1. iterate nodes in each READ MORE
Category: Python 3
LeetCode 206. Reverse Linked List
This post explains leetcode problem 206. reverse linked list using python 3. For example, let’s say there is a linked list: 1 -> 2-> 3-> 4 -> 5. After reversing the list, the expected result is 5 -> 4 -> 3 -> 2 -> 1. This is a fairly easy problem and there is a couple of ways to solve this. Using stack This method uses extra space (stack) as the name indicates. The algorithm is:1. As iterating the original linked list, create the node and push it to the top of the stack. Note that the next pointer should READ MORE
Python Context Manager
The purpose of python context manager objects is to control a with statement.It is primarily used to make try/except/finally block simple.The finally block exists to execute some code no matter what happens after try/except block, which is usually releasing some resources or clean-up.Just like finally block, context manager objects actually do perform some block of code. Context Manager Protocol The context manager protocol consists of two methods: __enter__ and __exit__.As you can imagine, __enter__ is called when the with statement starts, which is invoked on the context manager object.The __exit__ method is called at the end of the with block. READ MORE
Python – best practices using else block
Typical use case of else block is with if in many programming languages.It usually serves as branch control such if it doesn’t meet certain conditions in if block it will just execute else block instead of if block.And it is the same case for python else block too. However, python extended else block usage more than the above.In python, you can actually use else block not only with if but also with for, while, try blocks.In that case, the name – else – could be quite misleading when used with for, while, try blocks.Since we automatically think of if-else we READ MORE