# Getting Started with Competitive Programming in Python

Last Updated : 01 Nov, 2023

Python is a great option for programming in Competitive Programming. First off, its easy-to-understand and concise grammar enables quicker development and simpler debugging. The huge standard library of Python offers a wide range of modules and functions that can be used to effectively address programming difficulties. Python also offers dynamic typing, intelligent memory management, and high-level data structures, which speed up development and simplify coding.

### 1. How to start Competitive Programming using Python:

1. Learn Python language
1. Python list and string manipulation:
2. Learn Data Structures and Algorithms
1. Implementing a simple linked list:
3. Use Python Libraries
1. Using NumPy for array manipulation:
4. Optimize code step by step
1. Brute-force approach to find the maximum element in a list:
5. Take part in contests
1. Solving a simple problem on GeeksForGeeks:
6. Look for Better solutions
1. Comparing two solutions to find the maximum element in a list:
7. Practice Time Management

### 2. Examples:

1. Binary Search Algorithm in Python:
2. Solving the Knapsack Problem:
3. DFS algorithm for graph traversal:
4. Longest Increasing Subsequence problem using Dynamic Programming:
5. Trie data structure:

## How to start Competitive Programming using Python:

### 1. Learn Python language

We should learn the basics of the Python language which contain syntax, datatypes, list, string, tuples, etc;

## Python3

 `# Creating a list` `numbers ``=` `[``1``, ``2``, ``3``, ``4``, ``5``]`   `# Accessing list elements` `print``(numbers[``0``])  ``# Output: 1`   `# String concatenation` `name ``=` `"John"` `greeting ``=` `"Hello, " ``+` `name ``+` `"!"` `print``(greeting)  ``# Output: Hello, John!`

Output

```1
Hello, John!
```

### 2. Learn Data Structures and Algorithms

Learn data structures and algorithms like arrays, linked lists, stacks, queues, trees, graphs, sorting, searching, and dynamic programming.

## Python3

 `# Node class to represent a linked list node` `class` `Node:` `    ``def` `__init__(``self``, data):` `        ``self``.data ``=` `data` `        ``self``.``next` `=` `None`   `# Linked list class with basic operations` `class` `LinkedList:` `    ``def` `__init__(``self``):` `        ``self``.head ``=` `None`   `    ``def` `append(``self``, data):` `        ``new_node ``=` `Node(data)` `        ``if` `not` `self``.head:` `            ``self``.head ``=` `new_node` `        ``else``:` `            ``current ``=` `self``.head` `            ``while` `current.``next``:` `                ``current ``=` `current.``next` `            ``current.``next` `=` `new_node`   `    ``def` `print_list(``self``):` `        ``current ``=` `self``.head` `        ``while` `current:` `            ``print``(current.data, end``=``" ``-``> ")` `            ``current ``=` `current.``next` `        ``print``("``None``")`   `# Usage of linked list` `linked_list ``=` `LinkedList()` `linked_list.append(``1``)` `linked_list.append(``2``)` `linked_list.append(``3``)` `linked_list.print_list()`

Output

```1 -> 2 -> 3 -> None
```

### 3. Use Python Libraries

Python libraries such as NumPy, Pandas, SciPy, and Matplotlib are a few libraries for programming competitions.

## Python

 `import` `numpy as np`   `# Creating a NumPy array` `arr ``=` `np.array([``1``, ``2``, ``3``, ``4``, ``5``])`   `# Sum of array elements` `print``(np.``sum``(arr))  ``# Output: 15`   `# Sorting the array` `sorted_arr ``=` `np.sort(arr)` `print``(sorted_arr)  ``# Output: [1 2 3 4 5]`

### 4. Optimize code step by step

Optimize your code starting with a brute force approach, a better solution, and at last best solution.

## Python3

 `def` `find_max_element(arr):` `    ``max_element ``=` `arr[``0``]` `    ``for` `num ``in` `arr:` `        ``if` `num > max_element:` `            ``max_element ``=` `num` `    ``return` `max_element`

### 5. Take part in contests

Once you feel comfortable solving problems, participate in competitions like GeeksForGeeks, Google Code Jam, HackerRank, or Codeforces.

## Python3

 `def` `find_max_element_1(arr):` `    ``# Solution 1: Using built-in max() function` `    ``return` `max``(arr)`   `def` `find_max_element_2(arr):` `    ``# Solution 2: Using a loop to find max element` `    ``max_element ``=` `arr[``0``]` `    ``for` `num ``in` `arr:` `        ``if` `num > max_element:` `            ``max_element ``=` `num` `    ``return` `max_element`

### 6. Look for Better solutions

Review other people’s solutions after each problem or contest. Search for more elegant or effective solutions to these problems. You will increase your expertise by reading about and understanding the methods used by skilled programmers.

## Python3

 `def` `find_max_element_1(arr):` `    ``# Solution 1: Using built-in max() function` `    ``return` `max``(arr)`   `def` `find_max_element_2(arr):` `    ``# Solution 2: Using a loop to find max element` `    ``max_element ``=` `arr[``0``]` `    ``for` `num ``in` `arr:` `        ``if` `num > max_element:` `            ``max_element ``=` `num` `    ``return` `max_element`

### 7. Practice Time Management

Practice time management skills because programming competitions have time restrictions. Set time constraints for each challenge and concentrate on enhancing your accuracy and speed.

## Examples:

### 1. Binary Search Algorithm in Python:

To find the element present in a list or not with O(logN) time complexity.  It efficiently divides the search space in half at each step and divides down the search until the element is found or the search range is finished.

## Python3

 `# Iterative Binary Search Function` `# It returns index of x in given array arr if present,` `# else returns -1` `def` `binary_search(arr, x):` `    ``low ``=` `0` `    ``high ``=` `len``(arr) ``-` `1` `    ``mid ``=` `0`   `    ``while` `low <``=` `high:`   `        ``mid ``=` `(high ``+` `low) ``/``/` `2`   `        ``# If x is greater, ignore left half` `        ``if` `arr[mid] < x:` `            ``low ``=` `mid ``+` `1`   `        ``# If x is smaller, ignore right half` `        ``elif` `arr[mid] > x:` `            ``high ``=` `mid ``-` `1`   `        ``# means x is present at mid` `        ``else``:` `            ``return` `mid`   `    ``# If we reach here, then the element was not present` `    ``return` `-``1`     `# Test array` `arr ``=` `[ ``2``, ``3``, ``4``, ``10``, ``40` `]` `x ``=` `10`   `# Function call` `result ``=` `binary_search(arr, x)`   `if` `result !``=` `-``1``:` `    ``print``("Element ``is` `present at index", ``str``(result))` `else``:` `    ``print``("Element ``is` `not` `present ``in` `array")`   `# This code is contributed by Nikhil Garg(https://www.instagram.com/nikhilgarg471/)`

Output

```Element is present at index 3
```

Time Complexity: O(log N)
Auxiliary Space: O(1)

### 2. Solving the Knapsack Problem:

Returns the maximum value that can be put in a knapsack of capacity W. It evaluates the weight and value of each item and recursively finds two possibilities: include the current item or exclude it. The function returns the maximum value that can be put by selecting a subset of items within the weight capacity of the knapsack.

## Python

 `# Python code for knapsack problem`   `def` `knapSack(W, wt, val, n):`   `    ``if` `n ``=``=` `0` `or` `W ``=``=` `0` `:` `        ``return` `0`   `    ``# If weight of the nth item is more than Knapsack of capacity` `    ``# W, then this item cannot be included in the optimal solution` `    ``if` `(wt[n``-``1``] > W):` `        ``return` `knapSack(W, wt, val, n``-``1``)`   `    ``# return the maximum of two cases:` `    ``# (1) nth item included` `    ``# (2) not included` `    ``else``:` `        ``return` `max``(val[n``-``1``] ``+` `knapSack(W``-``wt[n``-``1``], wt, val, n``-``1``),` `                ``knapSack(W, wt, val, n``-``1``))`   `# Driver code` `val ``=` `[``60``, ``100``, ``120``]` `wt ``=` `[``10``, ``20``, ``30``]` `W ``=` `50` `n ``=` `len``(val)` `print` `knapSack(W, wt, val, n)`   `# This code is contributed by Nikhil Garg(https://www.instagram.com/nikhilgarg471/)`

Output

```220
```

Time Complexity: O(2N)
Auxiliary Space: O(N), Space used for auxiliary stack space in recursion calls

### 3. DFS algorithm for graph traversal:

For graph traversal of a directed graph. It visits each vertex of the graph and visits its adjacent vertices recursively until all vertices are visited. The DFS traversal order is printed as the output.

## Python

 `# Python program to print DFS traversal for complete graph` `from` `collections ``import` `defaultdict`   `# This class represents a directed graph using adjacency` `# list representation` `class` `Graph:`   `    ``# Constructor` `    ``def` `__init__(``self``):`   `        ``# default dictionary to store graph` `        ``self``.graph ``=` `defaultdict(``list``)`   `    ``# function to add an edge to graph` `    ``def` `addEdge(``self``,u,v):` `        ``self``.graph[u].append(v)`   `    ``# A function used by DFS` `    ``def` `DFSUtil(``self``, v, visited):`   `        ``# Mark the current node as visited and print it` `        ``visited[v]``=` `True` `        ``print` `v,`   `        ``# Recur for all the vertices adjacent to` `        ``# this vertex` `        ``for` `i ``in` `self``.graph[v]:` `            ``if` `visited[i] ``=``=` `False``:` `                ``self``.DFSUtil(i, visited)`     `    ``# The function to do DFS traversal. It uses` `    ``# recursive DFSUtil()` `    ``def` `DFS(``self``):` `        ``V ``=` `len``(``self``.graph) ``#total vertices`   `        ``# Mark all the vertices as not visited` `        ``visited ``=``[``False``]``*``(V)`   `        ``# Call the recursive helper function to print` `        ``# DFS traversal starting from all vertices one` `        ``# by one` `        ``for` `i ``in` `range``(V):` `            ``if` `visited[i] ``=``=` `False``:` `                ``self``.DFSUtil(i, visited)`     `# Driver code`   `g ``=` `Graph()` `g.addEdge(``0``, ``1``)` `g.addEdge(``0``, ``2``)` `g.addEdge(``1``, ``2``)` `g.addEdge(``2``, ``0``)` `g.addEdge(``2``, ``3``)` `g.addEdge(``3``, ``3``)`   `print` `"Following ``is` `Depth First Traversal"` `g.DFS()`   `# This code is contributed by Nikhil Garg(https://www.instagram.com/nikhilgarg471/)`

Output

```Following is Depth First Traversal
0 1 2 3
```

Time Complexity: O(V+E), where V is the number of vertices and E is the number of edges
Auxiliary Space: O(V)

### 4. Longest Increasing Subsequence problem using Dynamic Programming:

It calculates the length of the longest increasing subsequence in a given array using a bottom-up approach, where each LIS value is updated by considering all previous elements.

## Python

 `# Dynamic programming Python implementation of LIS problem`   `# lis returns length of the longest increasing subsequence` `# in arr of size n` `def` `lis(arr):` `    ``n ``=` `len``(arr)`   `    ``# Declare the list (array) for LIS and initialize LIS` `    ``# values for all indexes` `    ``lis ``=` `[``1``]``*``n`   `    ``# Compute optimized LIS values in bottom up manner` `    ``for` `i ``in` `range` `(``1``, n):` `        ``for` `j ``in` `range``(``0``, i):` `            ``if` `arr[i] > arr[j] ``and` `lis[i]< lis[j] ``+` `1` `:` `                ``lis[i] ``=` `lis[j]``+``1`   `    ``# Initialize maximum to 0 to get the maximum of all` `    ``# LIS` `    ``maximum ``=` `0`   `    ``# Pick maximum of all LIS values` `    ``for` `i ``in` `range``(n):` `        ``maximum ``=` `max``(maximum, lis[i])`   `    ``return` `maximum` `# end of lis function`   `# Driver program to test above function` `arr ``=` `[``10``, ``22``, ``9``, ``33``, ``21``, ``50``, ``41``, ``60``]` `print` `"Length of ``list` `is``", lis(arr)`   `# This code is contributed by Nikhil Garg(https://www.instagram.com/nikhilgarg471/)`

Output

```Length of list is 5
```

Time Complexity: O(N2)
Auxiliary space: O(N)

### 5. Trie data structure:

Here is the implementation of a Trie data structure for efficient insertion and search operations. It creates a Trie, inserts keys into it, and performs searches to check the presence of keys in the Trie.

## Python3

 `# Python program for insert and search` `# operation in a Trie`   `class` `TrieNode:` `    `  `    ``# Trie node class` `    ``def` `__init__(``self``):` `        ``self``.children ``=` `[``None``]``*``26`   `        ``# isEndOfWord is True if node represent the end of the word` `        ``self``.isEndOfWord ``=` `False`   `class` `Trie:` `    `  `    ``# Trie data structure class` `    ``def` `__init__(``self``):` `        ``self``.root ``=` `self``.getNode()`   `    ``def` `getNode(``self``):` `    `  `        ``# Returns new trie node (initialized to NULLs)` `        ``return` `TrieNode()`   `    ``def` `_charToIndex(``self``,ch):` `        `  `        ``# private helper function` `        ``# Converts key current character into index` `        ``# use only 'a' through 'z' and lower case` `        `  `        ``return` `ord``(ch)``-``ord``(``'a'``)`     `    ``def` `insert(``self``,key):` `        `  `        ``# If not present, inserts key into trie` `        ``# If the key is prefix of trie node,` `        ``# just marks leaf node` `        ``pCrawl ``=` `self``.root` `        ``length ``=` `len``(key)` `        ``for` `level ``in` `range``(length):` `            ``index ``=` `self``._charToIndex(key[level])`   `            ``# if current character is not present` `            ``if` `not` `pCrawl.children[index]:` `                ``pCrawl.children[index] ``=` `self``.getNode()` `            ``pCrawl ``=` `pCrawl.children[index]`   `        ``# mark last node as leaf` `        ``pCrawl.isEndOfWord ``=` `True`   `    ``def` `search(``self``, key):` `        `  `        ``# Search key in the trie` `        ``# Returns true if key presents` `        ``# in trie, else false` `        ``pCrawl ``=` `self``.root` `        ``length ``=` `len``(key)` `        ``for` `level ``in` `range``(length):` `            ``index ``=` `self``._charToIndex(key[level])` `            ``if` `not` `pCrawl.children[index]:` `                ``return` `False` `            ``pCrawl ``=` `pCrawl.children[index]`   `        ``return` `pCrawl.isEndOfWord`   `# Driver function` `def` `main():`   `    ``# Input keys (use only 'a' through 'z' and lower case)` `    ``keys ``=` `["the","a","there","anaswe","``any``",` `            ``"by","their"]` `    ``output ``=` `["Not present ``in` `trie",` `            ``"Present ``in` `trie"]`   `    ``# Trie object` `    ``t ``=` `Trie()`   `    ``# Construct trie` `    ``for` `key ``in` `keys:` `        ``t.insert(key)`   `    ``# Search for different keys` `    ``print``("{} ``-``-``-``-` `{}".``format``("the",output[t.search("the")]))` `    ``print``("{} ``-``-``-``-` `{}".``format``("these",output[t.search("these")]))` `    ``print``("{} ``-``-``-``-` `{}".``format``("their",output[t.search("their")]))` `    ``print``("{} ``-``-``-``-` `{}".``format``("thaw",output[t.search("thaw")]))`   `if` `__name__ ``=``=` `'__main__'``:` `    ``main()`   `# This code is contributed by Nikhil Garg(https://www.instagram.com/nikhilgarg471/)`

Output

```the ---- Present in trie
these ---- Not present in trie
their ---- Present in trie
thaw ---- Not present in trie
```

Time Complexity: O(N)
Auxiliary Space: O(N)

## Tips for improving in Competitive Programming:

• Practice regularly and consistently.
• Focus on problem-solving, not just coding.
• Use built-in functions and libraries to save time.
• Write clean, readable, and efficient code

## Pros of Using Python for CP:

• Python’s clear syntax and simple-to-follow code make it the perfect language for competitive programming, allowing for speedy implementation and troubleshooting.
• Python has a sizable standard library that offers ready-to-use modules and functions, reducing the time and effort required to implement common tasks.
• Python has built-in data structures like dictionaries, lists, and sets that make it easier to manipulate and store data effectively while solving problems.
• Python’s interpreted nature enables speedy experimentation and prototyping, facilitating quicker algorithm development iterations.

## Cons of Using Python for CP:

• Python’s interpreted nature can make it slower to execute than lower-level languages like C++ or Java. This could have an impact on performance in time-sensitive competitive programming scenarios.
• Python’s automatic memory management can result in greater memory use as compared to languages with human memory control, which can be problematic for issues requiring a lot of memory.

## Conclusion:

By learning Python and practicing algorithmic problem-solving techniques, programmers can know the power of Python for competitive programming and enhance their coding skills.

Previous
Next