Python From C++
Python Basics
Declare Variables
No need to specify a type
Indexing
We can iterate backward with negative index and access range of object using [start:end] or [start:stop:step]
Strings
split(separator, maxsplit)splits string by a separatorcount()counts number of occurrencestr()=to_string()int()=stoi()ord()returns ASCII of the characterchr()returns character of given ASCII
F-Strings
String that can combine normal text and variables
s = f"lorem ipsum {variable}"Math
import math
math.ceil()
math.floor()
math.gcd()
math.log(x, base)
bin() # turns to binaryBooleans
Use True and False instead of lowercase
Operators
- Arithmetic: Typical operators with
**(exponent)//(floor) - Logical: Say goodbye to
&& || !onlyand or not - Identity:
is/is notto check if they are the same object - Membership:
in/not into check if they a presented in the object
Collections
Lists []
Work like vector<T>
append()=push_back()insert()inserts between elementsextend()appends object to the listremove()removes first occurrence of the elementpop()=pop_back()but can specify the indexsort()andreverse()are methods not functions (passingreverse= Trueto sort descending)copy()/list()is needed becausenewlist = listwill be just a reference
List Comprehension
We can create a new list from other list in one line
newlist = [expression for i in iterable if condition]Custom Comparator
import functools
def compare(a, b):
...
list = sorted(list, key = functools.cmp_to_key(compare))Tuple ()
Immutable list
Set {}
Work like unordered_set<T>
add()=insert()remove()is the same
Dictionary {:}
Work like map<T, T>
items()returns(key, val)keys()andvalues()return a list of keys and valuesupdate()=insert()pop()=remove()
Deque
from collections import deque # Need to import
dq = deque()
dq.append() # push_back
dq.pop() # pop_back
dq.appendLeft() # push_front
dq.popleft() # pop_frontPriority Queue
import heapq # Need to import
pq = []
heapq.heapify(pq) # inititialize pq
heapq.heappush(pq, element) # push
top = heapq.heappop(pq) # pop -> topClass
class A:
def __init__(self, a, b, ...):
self.a = a
self.b = b
...
def __lt__(self, obj):
"""
custom comparator (less than)
also have __le__, __eq__, __ne__, __gt__, and __ge__
"""
return self.a < obj.a
def method(self):
...
...
obj = A(a, b, ...)Lambda
x = lambda args : expressionBuilt-in Functions
map(func, iterable)executes func for each item in the iterableenumerate(iterable)returns(idx, element)filter(func, iterable)returns list of elements that func returnsTrue
Pandas DataFrames
-
df[col]returns Pandas Series of specific col -
df[[cols]]returns Pandas DataFrames of specific cols -
df[condition]returns rows with specific condition -
df.shapereturns(no. of rows, no. of cols) -
df.head(x)returns firstxrows -
df.loc[[rows], [cols]]returns specific rows and cols; can be used with condition -
df.drop_duplicates(subset, keep, inplace)can be used to remove duplicates from cols in subset;keep = "first", "last", Falsedetermines which duplicate row to retain;inplace = True, Falsewhether to change directly or return new df -
df.dropna(axis, subset, inplace)can be used to drop missing values;axis = 0, 1drops row and col respectively -
df.fillna(axis, value, inplace)can be used to change missing values tovalue -
df.rename(columns = {})can be used to rename cols -
df.astype({col: type})can be used to change type of col -
pd.concat(objs, axis)can be used to concatenate DataFrames by axis -
df.pivot(index, columns, values)can be used to pivot the table;indexare rows;columnsare cols -
df.melt(id_vars, value_vars, var_name, value_name)can be used to transform table from wide to long;id_varsrefers to indentifiers;value_varsrefers to cols that will be transformed;var_namerefers to a new col with transformed cols name;value_namerefers to a new col with old value -
df.apply(func)applys specified function to df
Iteratation Trick
for idx, row in df.iterrows():
...