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 separator
  • count() counts number of occurrence
  • str() = to_string()
  • int() = stoi()
  • ord() returns ASCII of the character
  • chr() 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 binary

Booleans

Use True and False instead of lowercase

Operators

  • Arithmetic: Typical operators with ** (exponent) // (floor)
  • Logical: Say goodbye to && || ! only and or not
  • Identity: is / is not to check if they are the same object
  • Membership: in / not in to check if they a presented in the object

Collections

Lists []

Work like vector<T>

  • append() = push_back()
  • insert() inserts between elements
  • extend() appends object to the list
  • remove() removes first occurrence of the element
  • pop() = pop_back() but can specify the index
  • sort() and reverse() are methods not functions (passing reverse= True to sort descending)
  • copy() / list() is needed because newlist = list will 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() and values() return a list of keys and values
  • update() = 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_front

Priority Queue

import heapq # Need to import
 
pq = []
 
heapq.heapify(pq) # inititialize pq
heapq.heappush(pq, element) # push
top = heapq.heappop(pq) # pop -> top

Class

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 : expression

Built-in Functions

  • map(func, iterable) executes func for each item in the iterable
  • enumerate(iterable) returns (idx, element)
  • filter(func, iterable) returns list of elements that func returns True

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.shape returns (no. of rows, no. of cols)

  • df.head(x) returns first x rows

  • 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", False determines which duplicate row to retain; inplace = True, False whether to change directly or return new df

  • df.dropna(axis, subset, inplace) can be used to drop missing values; axis = 0, 1 drops row and col respectively

  • df.fillna(axis, value, inplace) can be used to change missing values to value

  • 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; index are rows; columns are cols

  • df.melt(id_vars, value_vars, var_name, value_name) can be used to transform table from wide to long; id_vars refers to indentifiers; value_vars refers to cols that will be transformed; var_name refers to a new col with transformed cols name; value_name refers to a new col with old value

  • df.apply(func) applys specified function to df

Iteratation Trick

for idx, row in df.iterrows():
  ...