The Wayback Machine - https://web.archive.org/web/20240616195110/https://www.geeksforgeeks.org/python-tricks-competitive-coding/
Open In App

Python Tricks for Competitive Coding

Last Updated : 16 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python is one such programming language that makes everything easier and straight forward. Anyone who has dabbled in python for Competitive Coding gets somewhat addicted to its many features. Here is a list of some of its cool features that I’ve found most useful in a competitive coding environment.
 

The most common function of the Counter Package. 

This is probably the most useful function I’ve ever used and it’s always at the back of my mind while writing any python code. This function analyses a list/string and helps to return the top n entities in the list/string according to their number of occurrences in descending order where n is a number that is specified by the programmer. The individual entities are returned along with their number of occurrences in a tuple which can easily be referred/printed as and when required.
 

Python
# Code to find top 3 elements and their counts
# using most_common
from collections import Counter

arr = [1, 3, 4, 1, 2, 1, 1, 3, 4, 3, 5, 1, 2, 5, 3, 4, 5]
counter = Counter(arr)
top_three = counter.most_common(3)
print(top_three)

Output:

[(1, 5), (3, 4), (4, 3)]

The output tuple clearly states that 1 has occurred 5 times, 3 has occurred 4 times, and 4 has occurred 3 times.

The n-largest/n-smallest function of the heapq Package.

This function helps to return the top n smallest/largest elements in any list and here again n is a number specified by the programmer.
 

Python
# Python code to find 3 largest and 4 smallest
# elements of a list.
import heapq

grades = [110, 25, 38, 49, 20, 95, 33, 87, 80, 90]
print(heapq.nlargest(3, grades))
print(heapq.nsmallest(4, grades))

Output: 

[110, 95, 90]
[20, 25, 33, 38]

The first line of output gives 3 of the largest numbers present in the list grades. Similarly the second line of output prints out 4 of the smallest elements present in the list grades. Another specialty of this function is that it does not overlook repetitions. So in place of n if we were to place the length of the array then we would end up with the entire sorted array itself !!

Dictionary and concept of zipping Dictionaries 

Dictionaries in python are truly fascinating in terms of the unique functionality that they offer. They are stored as a Key and Value pair in the form of an array like structure. Each value can be accessed by its corresponding key. 
The zip function is used to join two lists together or we can even join the key and value pairs in a dictionary together as a single list. The application of this concept will be made clear in the following code snippet.

Python
# Python code to demonstrate use of zip.
import heapq

stocks = {
    'Goog' : 520.54,
    'FB' : 76.45,
    'yhoo' : 39.28,
    'AMZN' : 306.21,
    'APPL' : 99.76
    }

zipped_1 = zip(stocks.values(), stocks.keys())

# sorting according to values
print(sorted(zipped_1))

zipped_2 = zip(stocks.keys(), stocks.values())
print(sorted(zipped_2))
#sorting according to keys

Output: 

[(39.28, 'yhoo'), (76.45, 'FB'), (99.76, 'APPL'), (306.21, 'AMZN'), (520.54, 'Goog')]
[('AMZN', 306.21), ('APPL', 99.76), ('FB', 76.45), ('Goog', 520.54), ('yhoo', 39.28)]

The Map function


This function is a sneaky little shortcut that allows us to implement a simple function on a list of values in a very Unconventional Manner. The following example will give a simple application of this functionality. The function takes as parameters the function name and the name of the list the function needs to be applied upon.

Python
# Python code to apply a function on a list
income = [10, 30, 75]

def double_money(dollars):
    return dollars * 2

new_income = list(map(double_money, income))
print(new_income)

Output: 

[20, 60, 150]

Here, we just implemented a simple function that multiplies each list value by two and returns it as a new list.

Concatenation of list of strings

Suppose we have been given a list of strings and we have to give the output by concatenating the list 
Let’s look at the previous code what we were doing:

Python
string = ""
lst = ["Geeks", "for", "Geeks"]
for i in lst:
    string += i
print(string)

Output
GeeksforGeeks

This method of joining a list of strings is definitely not the best method because a new string will be created every time the loop is run.

Python
lst = ["Geeks", "for", "Geeks"]
string = ''.join(lst)
print(string)

Output
GeeksforGeeks

Using join() function is memory efficient as well as handy to write which definitely proves to be the advantage over the previous code.


Individually these functions might look innocent but will definitely come in handy in a TIME LIMITED CODING ENVIRONMENT in the sense that they offer large functionality in a VERY short amount of code. The functionalities discussed have very specific applications and act like a SHORTCUT or a CHEAT-SHEET in competitive coding. Having these useful tricks up your sleeve might just give someone the COMPETITIVE EDGE that they were looking for !!



Previous Article
Next Article

Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
Python Tips and Tricks for Competitive Programming
Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips: Converting a number into a List of digits using map() Fun
4 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Logarithm tricks for Competitive Programming
Logarithm: is the inverse function of the exponentiation which means the logarithm value of a given number x is the exponent to another number. [Tex]log_b(x) = y, \to b^{y} = x [/Tex] Below are some tricks using Logarithmic function which can be handy in competitive programming. Checking if a number is a power of two or not:Given an integer N, the
15+ min read
Tips and Tricks for Competitive Programmers | Set 1 (For Beginners)
This article is a collection of various tips that would help beginners of Competitive programming to get an insight of things that should or shouldn’t be done. Competitive programming can only be improved by “PRACTICE, PRACTICE AND PRACTICE”. Try to solve as many questions you can solve on sites like practice.geeksforgeeks.org. This will enhance yo
6 min read
C++ tricks for competitive programming (for C++ 11)
We have discussed some tricks in the below post. In this post, some more tricks are discussed. Writing C/C++ code efficiently in Competitive programming Although, practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging. 1) Checking if the numb
5 min read
Java tricks for competitive programming (for Java 8)
Although the practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.1) Checking if the number is even or odd without using the % operator: Although this trick is not much better than using a % operator but is sometimes efficient (with large n
5 min read
Bit Tricks for Competitive Programming
In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&1 Evaluates to 1 if the number is odd else evaluate
7 min read
Competitive Coding Setup for C++ and Python in VS Code using Python Script
Most of us struggle with using heavy software to run C++ and python code and things become more complicated when we have too many files in a folder. In this blog, we are going to create a python script with VS-code-editor that works out to do all your works. It creates the folder + numbers of files required by the user in that folder with proper ex
3 min read
Practice Tags :