Skip to content

Instantly share code, notes, and snippets.

@alexandru-dinu
alexandru-dinu / ap.py
Created August 24, 2023 12:50
Average Precision
def ap_k(res: list[bool], K: int):
out = np.zeros(K, dtype=np.float32)
rel = np.zeros(K, dtype=np.float32)
for k in range(K):
rel[k] = res[k] # is current result relevant?
out[k] = sum(rel) / (k + 1) # how many relevant results until now?
if rel.sum() == 0:
return 0
from IPython.core.magic import register_line_magic
# From https://stackoverflow.com/a/64791087
def _global_import(obj: str, syn: str = None, ctx: str = None):
"""[from `ctx`] import `obj` [as `syn`]"""
explain = [f"import {obj}"]
if syn:
explain.append(f"as {syn}")
if ctx:
@alexandru-dinu
alexandru-dinu / median_freq_table.py
Created February 23, 2022 18:59
Median given a frequency table
def median_freq_table(freq_table: np.ndarray) -> float:
"""
Find median of an array represented as a frequency table [[ val, freq ]].
"""
values = freq_table[:, 0]
freqs = freq_table[:, 1]
# cumulative frequencies
cf = np.cumsum(freqs)
# total number of elements
@alexandru-dinu
alexandru-dinu / hypothesis_sqrt.py
Last active November 4, 2021 20:16
Python hypothesis example.
"""
Simple hypothesis example.
Test that sqrt computed using Newton-Raphson is correct.
Run with:
$ py.test --hypothesis-show-statistics sqrt.py
"""
import hypothesis.strategies as st
from hypothesis import given, settings
@alexandru-dinu
alexandru-dinu / leetcode_dl.py
Last active November 4, 2021 14:43
Get the most recent accepted submissions from leetcode.
"""
1) Fetch submisssions using
https://github.com/world177/Leetcode-Downloader-for-Submissions
2) Use this script to move the *latest accepted* submission to ./out/<problem>
3) Replace "// " comments from the first line of all python files
f in $(ls **/*.py); do sed -i.bak "1 s/\/\/ /# /" $f; done
"""
@alexandru-dinu
alexandru-dinu / deadline.py
Created October 6, 2021 18:50
Simple countdown until a deadline.
import argparse
import math
import time
from datetime import datetime
from rich import box
from rich.align import Align
from rich.live import Live
from rich.panel import Panel
@alexandru-dinu
alexandru-dinu / over_allocation.py
Last active August 29, 2021 20:45
Python over allocation
import os
import sys
import psutil
UNIT = 2 ** 20 # MB
print("All size units are in M\n")
proc = psutil.Process(pid=os.getpid())
m0 = proc.memory_info().rss
@alexandru-dinu
alexandru-dinu / fizzbuzz.cpp
Last active November 4, 2021 15:51
FizzBuzz
// adapted from
// https://wiki.haskell.org/Haskell_Quiz/FizzBuzz/Solution_Acontorer
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
const vector<pair<int, string>> tags = { { 3, "Fizz" },
{ 5, "Buzz" },
@alexandru-dinu
alexandru-dinu / mmr.py
Last active October 14, 2021 09:16
Maximal Marginal Relevance (Carbonell and Goldstein, 1998)
import numpy as np
import torch as T
def maximal_marginal_relevance(
score_di_q: T.Tensor,
score_di_dj: T.Tensor,
*,
lam: float,
num_iters: int,