Python3 for CP
Difference between en2 and en3, changed 15 character(s)
Hi! ↵
I found python to be very easy to learn but I was not able  to use it for cp before because of things like io speed which I  did not know how to optimize earlier↵
these are some things I learnt which made it much easier for me to use python for cp↵

Fast Input:↵

~~~~~↵
import sys↵
inp = [a.strip() for a in sys.stdin.readlines()]  #inp is an array of input lines.↵
~~~~~↵


Reading an array↵

~~~~~↵
arr = [int(x) for x in inp[i].split()]  # use float(x) if dealing with decimal values↵
~~~~~↵



Making 2d matrix ( or any n dim matrix ) of 0s↵

~~~~~↵
mat = [[0 for i in range(n)] for j in range(n)]↵
~~~~~↵



Printing without the \n:↵

~~~~~↵
print("output",end="")↵
~~~~~↵



Sorting using key (see example below)↵

~~~~~↵
arr = [[3,4],[1,2],[5,3],[-1,4]]↵
def fkey(a):↵
    return a[0]*a[1]↵
arr.sort(key=fkey)↵
~~~~~↵


Reversing array/string↵

~~~~~↵
arr=arr[::-1]↵
~~~~~↵


Note 1:↵
if arr is a list,↵

~~~~~↵
brr=arr↵
brr[0]*=2 # this also modifies arr and both lists are an array of pointers to the same thing↵
~~~~~↵

To make a copy of an array use this code↵
`brr=list(arr)`↵
Copy of string is also similar↵
`brr=string(arr)`↵

Note 2:↵

~~~~~↵
a="ilu python"↵
a[0]='a' # this line gives the following error:↵
#'str' object does not support item assignment↵

# so if you have to modify the string, convert it into a list first↵
( list(a) )↵
~~~~~↵


Note 3: ↵
division in python normally returns a float, so to get integer division similar to cpp↵
use '//' (a//b)  operator or int(a/b)↵

Cpp data structures and their python equivalents:↵
vector : list↵
Map : dict↵
set : set↵
string : str↵
stack/queue: (Implemented using list) https://www.geeksforgeeks.org/using-list-stack-queues-python/↵
list : -↵

 ↵
Useful Libraries↵
1. Counter (to import: `from collections import Counter` ) # to count number of occurances of each element in a list↵
2. itertools (import itertools) (https://docs.python.org/2/library/itertools.html#module-itertools)↵
3. math↵

Thanks!

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English ameykudari05 2019-09-15 12:30:37 18 Indentation fix, sorry I will make sure I dont edit it very often
en4 English ameykudari05 2019-09-15 12:26:08 19 Intendation Fixes
en3 English ameykudari05 2019-09-15 12:23:50 15 Intendation Fixes
en2 English ameykudari05 2019-09-15 12:21:50 13
en1 English ameykudari05 2019-09-15 11:27:21 2034 Initial revision (published)