Posts

Count frequency of items in a list using Python

In this post I am going to show you how we can write a program in Python that can count the frequency of items in a list. First I shall implement it using the dictionary data structure in Python. Then I shall make it shorter (and nicer) using the defaultdict and Counter data structures from the collections module . Here is our code that we will use to run and test the program - if __name__ == "__main__": li = [2, 6, 9, 2, 8, 2, 9, 9, 3, 1, 4, 5, 7, 1, 8, 10, 2, 10, 10, 5] freq = frequency_counter(li) assert freq[1] == 2 assert freq[2] == 4 assert freq[3] == 1 assert freq[11] == 0 Now let's look at the implementation using dictionary. We will iterate over all the items and then check if it exists in the dictionary. If it exists, we shall increase the count. And if it doesn't, then we shall set the count to 1. def frequency_counter(li): freq_dt = dict() for item in li: if item in freq_dt: freq_dt[item] += 1

Python Program to Find Prime Factors of a Number

 In this post I am going to write a program in python that finds all the prime factors of a number. I am going to start by writing an empty function and a test. def get_prime_factors(number): prime_factors = [] return prime_factors if __name__ == "__main__": n = 8 expected = [2, 2, 2] result = get_prime_factors(n) assert expected == result, result Now, if you run the program above, it will give an AssertionError, as we are returning an empty list. Let's write some code to make our test pass. def get_prime_factors(number): prime_factors = [] while number % 2 == 0: prime_factors.append(2) number = number // 2 return prime_factors The program will work for multiple of 2's. Our next task is to find the other prime factors. For example, prime factors of 10 are 2 and 5. We shall add this test case first and then write code to pass this test.

divmod - division and modulus together in Python

divmod is a wonderful, nice, little built-in function in Python that allows you to do division and modulus operation together. Using it, you can make your code slightly beautiful, thus Pythonic! Check the following example - >>> 10 / 3 3.3333333333333335 >>> 10 // 3 3 >>> 10 % 3 1 >>> divmod(10, 3) (3, 1)

Python all any built-in function

I have been using Python for a long time, still learning lot of simple and new things. Recently I came to know about two built-in functions named all and any . Today while I was solving a hackerrank problem , I used both functions which makes the code a bit nicer, in my opinion. The functions compares two singly linked lists and if they are equal, returns 1, otherwise returns 0. Here is my code - def compare_lists(llist1, llist2): while all([llist1, llist2]): if llist1.data != llist2.data: return 0 llist1 = llist1.next llist2 = llist2.next if any([llist1, llist2]): return 0 return 1 Sometimes, this kind of simple thing brings joy to me. Let me know your thoughts. :)

Create 2D Array using List in Python

If for some reason you want to create a two dimensional array in Python and don't want to use external packages like numpy etc., the most obvious thing is to write a code like this : >>> n = 3 >>> m = 4 >>> ara = [[0] * m] * n >>> ara [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] But there is a problem. Check the code below- >>> ara[0][0] = 1 >>> ara [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]] Actually, when you do [0] * m, it returns a reference to a list and when you multiply it with n, the same reference is duplicated. Hence you see the change in a way that you didn't expect. The right way to do it is to append [0] * m, n times in the array. You can code it in multiple ways. My preferred way is: >>> ara = [[0] * m for _ in range(n)]

Table Driven Unit Test in Python

Now days, table driven tests are pretty much industry standard. In my workplace, we use table driven tests when we write unit tests (in golang though). Here I shall share a simple code example using pytest that shows how to write table driven tests in Python. In table driven test, what you need to do is, to gather all the tests cases together in a single table. We can use dictionary for each test case and a list to store all the test cases. Instead of discussing it further, let me show you an example : def average(L): if not L: return None return sum(L)/len(L) def test_average(): test_cases = [ { "name": "simple case 1", "input": [1, 2, 3], "expected": 2.0 }, { "name": "simple case 2", "input": [1, 2, 3, 4], "expected": 2.5 }, { "name": "list w

global and nonlocal variable in Python

Most of us are already familiar with global variables in Python. If we declare those variables in a module, the functions inside that module (can read python file or .py file) can access the variable. For example, check the code below : x = 5 def myfnc(): print("inside myfnc", x) def myfnc2(): print("inside myfnc2", x) myfnc2() myfnc() It will print :  inside myfnc 5 inside myfnc2 5 If you change your code like this : x = 5 def myfnc(): print("inside myfnc", x) def myfnc2(): print("inside myfnc2", x) x = 10 print("x = ", x) myfnc2() myfnc() You will get an error :   File "program.py", line 6, in myfnc2     print("inside myfnc2", x) UnboundLocalError: local variable 'x' referenced before assignment The moment you wrote x = 10, Python assume that x is a local variable, and inside the print function, it is giving this error. Because local variables are determi