Basic Python Functions
Rock those LeetCode easies with these basic Python functions π
Lists
list.insert(<index>, <elem>)
list.remove(<elem>) #removes first matching occurrence of element
list.append(elem)
list.extend(<another list>) #concatenates two lists (or a list and any iterable)
list.sort() #check below to see more on sorting
list.reverse() #this acts in place, returns none
list.pop(<index>)
x = list.pop(index) # returns popped value
x = list.index(index)
x = list.count(elem)
Check if Val in List
Clone a List
Lists & Tuples
String/List Manipulation
Split String by Delimiter
string.split(<separator, default whitespace>)
txt = “hello how are you”
x = txt.split() # this will output: [‘hello’, ‘how’, ‘are’, ‘you’]
Split String by Character
list(<string>)
list(nice) # this will output [‘n’,’i’,’c’,’e’]
Join a List into a String
separator.join(<iterable>)
numList = [‘1’,’2’,’3’]
separator = ‘, ‘
separator.join(numList) #this will output: ‘1, 2, 3’
Sorting
Basic Sorting
sorted(<iterable>, <key>, <reverse>)
a = [1,3,2]
x = sorted(a) #sorts ascending
#ex: key = len would sort by length, but can input your own func
Sorting a Nested List
a = [[‘a’,1],[‘b’,2]]
def sorter(a):
m = iterable[1]
n = iterable[0]
return(m,n)
x = sorted(a, key=sorter)
#will sort by in priority of the sorter function
y = sorted(a, key = lambda i : i[1])
#will sort by second value in the nested list
Reading Values
input() # fetch input from user
raw_input() #fetch input from user, always set it as a string type
map(int, raw_input().split()) #breaks up input into a list and sets values as integers
Numpy
import numpy as np
a = np array([[1,2,3],[4,5,6]])
Shape
array.shape = (int, int)
make an empty array (with 0. values) of the selected dimensions
array.shape
get the shape of an array
x = np.reshape(array, (int,int))
get a reshaped array of the selected dimensions
Identity Matrices
numpy.identity(int) # generates identity matrix
numpy.eye(rows, cols, k) # if k pos then 1s for upper diag, is k neg then 1s for lower diag, 0 for main diag
Comments
Post a Comment