Skip to content

Instantly share code, notes, and snippets.

View juanarrivillaga's full-sized avatar

Juan juanarrivillaga

View GitHub Profile
# So, assuming the lists have the same length, e.g.:
dummy_data = {
"Date":["01/24/2029","10/28/2027", "01/24/2024","03/24/2024"],
"Company Name":["Mcdonalds", "Burger King", "KFC","Popeyes"],
"File_name_location":["C/Documents/Files/invoice1.pdf", "C/Documents/Files/invoice1.pdf","C/Documents/Files/invoice1.pdf", "C/Documents/Files/invoice1.pdf"],
}
# Then, to sort everything, simply get a list of sorted indices.
# This can be done easily. Since you don't want `datetime.date` objects
import types
import copy
def clone_class(klass):
def _exec_body(ns):
ns_no_slots = {
k:v for k,v in vars(klass).items()
if not isinstance(v, types.MemberDescriptorType)
}
ns |= copy.deepcopy(ns_no_slots)
import datetime
DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap_year(year: int) -> int:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def add_months(date: datetime.date, months: int) -> datetime.date:
class BagOfClass(type):
class Value:
pass
def __iter__(klass):
for attr_value in vars(klass).values():
if isinstance(attr_value, type) and issubclass(
attr_value, BagOfClass.Value
):
yield attr_value
@juanarrivillaga
juanarrivillaga / simplysuper.py
Last active January 23, 2023 01:23
An example of how we could implement a basic `super` in pure Python
class SimpleSuper:
def __init__(self, cls, instance):
self.cls = cls
self.instance = instance
def __getattr__(self, name):
mro = type(self.instance).mro()
next_cls = mro[mro.index(self.cls) + 1]
attribute = getattr(next_cls, name)
if hasattr(attribute, "__get__"):
return attribute.__get__(self.instance, self.cls)
import matplotlib.pyplot as plt
import pandas as pd
from timeit import timeit
setup = """
def list_comp(d):
return [ (x*2)/3 for x in d ]
def pre_allocate(d):
result = [None]*len(d)
@juanarrivillaga
juanarrivillaga / tuple_gen_exp_vs_list_comp.py
Created August 29, 2021 20:54
Timing comparisons for creating a tuple from a generator expression versus a list comprehension
import pandas as pd
import matplotlib.pyplot as plt
from timeit import timeit
from tqdm import tqdm
gen_exp = "tuple(x for x in range({}))"
list_comp = "tuple([x for x in range({})])"
N = range(1, 500_001, 5000)
@juanarrivillaga
juanarrivillaga / comprehension_to_loop.py
Created May 25, 2021 08:21
Convert list comprehension to equivalent for loop
def parse_code(msg):
f,l,i=[item for item in msg.split('0') if len(item)>0]
return {'first_name':f,'last_name':l,'id':i}
def parse_code(msg):
result = []
for item in msg.split("0"):
if len(item) > 0:
result.append(item)
f,l,i = result
import pandas as pd
df = pd.read_csv('en_bigram.csv')
st = df[df["right"] == "some_text"]["left"]
st[st.str.startswith("My")].to_list()
# using a dict reader
import csv
result = []
with open("en_bigram.csv") as f:
@juanarrivillaga
juanarrivillaga / myrange.py
Created January 24, 2021 22:33
Explaining `range` objects
class Range:
def __init__(self, start, stop, step=1):
self.start = start
self.stop = stop
self.step = step
def __getitem__(self, index):
result = self.start + index*self.step
if result >= self.stop:
raise IndexError("Index out of range")
return result