Friday, 13 March 2020

Python Cheat Sheet

How to define 2D array in python ?

arr = [[0 for x in range(col)] for y in range(row)]


How To Sort

G = [
        [1,(0,1)],
        [4,(0,2)],
        [2,(1,2)],
        [1,(2,3)],
        [5,(1,3)],
        [4,(2,4)],
        [2,(1,4)],
        [3,(3,4)],
    ]

In place sort:
G.sort(key=lambda x:x[0])  //means sort based on 0th field
G.sort(key=lambda x:x[1])  //means sort based on tuple
G.sort(key=lambda x:x[1][1]) //means sort based on second field of tuple

sorted(G, key=lambda x:x[1]) //returns new list

Custom Function for Sorting

arr = ["ksqvsyq","ks","kss","czvh","zczpzvdhx","zczpzvh","zczpzvhx","zcpzvh","zczvh","gr","grukmj","ksqvsq","gruj","kssq","ksqsq","grukkmj","grukj","zczpzfvdhx","gru"]

import functools       #for python 3
def mycmp(x, y):     #sort according to length
    if len(x) < len(y):
        return -1
    elif len(x) > len(y):
        return 1
    if x < y:
        return -1
   return 1
 
arr.sort(key=functools.cmp_to_key(mycmp))

print(arr)
['gr', 'ks', 'gru', 'kss', 'czvh', 'gruj', 'kssq', 'grukj', 'ksqsq', 'zczvh', 'grukmj', 'ksqvsq', 'zcpzvh', 'grukkmj', 'ksqvsyq', '
zczpzvh', 'zczpzvhx', 'zczpzvdhx', 'zczpzfvdhx']   

How to enumerate

arr = [i for i in range(1130)]
print(arr)
for index, element in enumerate(arr):       //index represent index of element in arr, element is value                                                                        //at index
    print(index, element)


How to use Queue

import queue
q_fifo = queue.Queue()  //means simple FIFO queue
q_lifo = queue.LifoQueue()  //means LIFO queue of stack
q_pq = queue.PriorityQueue() //means Priority Queue, lowest valued entries are retrieved first

API to access:
q_fifo.qsize() 
q_fifo.empty()
q_fifo.full()
q_fifo.put(item)
q_fifo.get()


How to convert char to ascii and ascii to char
ord("0")    //returns ascii of char 0 which is int and value 48
chr(48)     // return "0" as a char, given ascii 48

How to split the string into arrays
s = "Hello how are you"    
s_arr = s.split(" ")
print(s_arr)     //['Hello', 'how', 'are', 'you'] 

No comments:

Post a Comment

Python Cheat Sheet

How to define 2D array in python ? arr = [[0 for x in range(col)] for y in range(row)] How To Sort G = [         [1,(0,1)],       ...