Open In App

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:

Below is the implementation to convert a given number into a list of digits:






# Python program to convert a
# number to a list of digits
 
# Given number
n = 123456
 
# Stores the list of digits
lis = list(map(int, str(n)))
 
# Print the digits
print(lis)

Output: 
[1, 2, 3, 4, 5, 6]

 




# Python program to convert
# a sentence to a list of words
 
# Given sentence
sentence = "GeeksforGeeks is the computer science portal for geeks"
 
# Convert the sentence
# into a list of words
lis = list(sentence.split())
 
# Print the list of words
print(lis)

Output: 

['GeeksforGeeks', 'is', 'the', 'computer', 'science', 'portal', 'for', 'geeks']

 




# Python program to take
# newline-separated input
# in the form of a list
 
# Given input
n = int(input())
 
lis = [int(input()) for _ in range(n)]

Below is the implementation to demonstrate gcd() function: 




# Python program to demonstrate gcd() function
import math
a = 8
b = 24
 
# Print the GCD of a and b
print(math.gcd(a, b))

Output: 
8

 

Below is the implementation of the approach:




# Python program to print all
# permutations using library function
from itertools import permutations
 
# Get all permutations of [1, 2, 3]
perm = permutations([1, 2, 3])
 
# Print the obtained permutations
for i in list(perm):
    print (i)

Output: 
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

 




# Python program to print
# a string given number of times
 
# Given string
str ="India"
 
# Print the string 2 times
print(str * 2)

Output: 
IndiaIndia

 

Below is the implementation to print a list with spaces without loop: 




# Python program to print a list with spaces without loop
lis = [1, 2, 3, 4]
 
# Printing list elements with spaces
print(*lis)

Output: 
1 2 3 4

 

Below is the implementation of the above approach: 




# Python program to convert a
# binary string to its decimal
# equivalent using int() function
 
# Given string
binary = "1010"
 
# Print decimal equivalent
print(int(binary, 2))

Output
10

Below is the implementation to print a sorted list with spaces: 




# Python program to print a sorted list with
# spaces using sorted() function
lis = [6, 2, 7, 3, 4]
 
# Print the sorted sequence
print(*sorted(lis))

Output: 
2 3 4 6 7

 

Below is the implementation to demonstrate intersection() function:




# Python program to print common elements in
# both the list using intersection() function
array1 = [4, 5, 6, 7, 8]
array2 = [3, 4, 5, 1, 72]
 
# Print the common elements
print(set(array1).intersection(set(array2)))

Output
{4, 5}

 


Article Tags :