Skip to content

Instantly share code, notes, and snippets.

View yoniLavi's full-sized avatar
:octocat:
Figuring things out

Yoni Lavi yoniLavi

:octocat:
Figuring things out
View GitHub Profile
@yoniLavi
yoniLavi / reversible_linked_list.py
Last active November 20, 2018 13:58
A reversible Pythonic LinkedList class
class LinkedList:
def __init__(self, collection):
try:
iterator = iter(collection)
head = next(iterator)
self._value = head
tail = LinkedList(iterator)
self._tail = tail
self._len = tail._len + 1
except StopIteration:
"""Hyperoperations implementation (https://en.wikipedia.org/wiki/Hyperoperation)"""
from functools import reduce
zeration = lambda a, b: b+1
addition = lambda a, b: reduce(lambda x, _: zeration(0, x), [None]*b, a)
multiplication = lambda a, b: reduce(lambda x, _: addition(a, x), [None]*b, 0)
exponentiation = lambda a, b: reduce(lambda x, _: multiplication(a, x), [None]*b, 1)
tetration = lambda a, b: reduce(lambda x, _: exponentiation(a, x), [None]*b, 1)
pentation = lambda a, b: reduce(lambda x, _: tetration(a, x), [None]*b, 1)
DAYS = ["1st", "2nd", "3rd"] + [f"{i}th" for i in range(4, 12+1)]
GIFTS = ["a partridge in a pear tree.", "two turtle doves,",
"three French hens,", "four calling birds,",
"five gold rings,", "six geese a-laying,",
"seven swans a-swimming,", "eight maids a-milking,",
"nine ladies dancing,", "ten lords a-leaping,",
"eleven pipers piping,", "twelve drummers drumming,"]
STANZA_TEMPLATE = "On the {} day of Christmas,\nmy true love gave to me\n{}\n"
def incremental_max(l: List[int]) -> List[int]:
if not l:
return []
maxes = [l[0]]
for i in range(1, len(l)):
maxes.append(max(maxes[i-1], l[i]))
return maxes
class Solution:
@yoniLavi
yoniLavi / additive_heterogenous_array.py
Last active June 17, 2021 21:20
A numpy array that supports addition of different types
import numpy as np
class AdditiveHeterogenousArray(np.lib.mixins.NDArrayOperatorsMixin):
"""A numpy array that supports addition of different types"""
def __init__(self, *args, **kwargs):
self.array = np.array(*args, **kwargs)
def __repr__(self):
class Stack(list):
def push(self, item):
"""Push item on top of stack"""
self.append(item)
def reverse(self, target=None):
"""Destructively reverse self onto another stack
To reverse a stack `s` in place, use `s = s.reverse()`
"""
@yoniLavi
yoniLavi / recursive_generator.py
Created April 28, 2021 23:15
Tree traversal using a generator
#!/usr/bin/env python3
tree = {
"name": '1', "children": [
{"name": '11', "children": [
{"name": '111', "children": [
{"name": '1111', "children": []},
]},
{"name": '112', "children": []},
]},
@yoniLavi
yoniLavi / password_generator.py
Created June 21, 2021 14:02
Example function to generate a random password
from random import choice, shuffle
from string import ascii_lowercase, ascii_uppercase, digits
def generate_password(length=16, groups=[ascii_lowercase, ascii_uppercase, digits]):
"""Generate a random strong password.
It will be of length `length`, with at least one character of each of the `groups`.
"""
group_indices = list(range(len(groups)))
from dataclasses import dataclass, field
from itertools import chain
class Node:
"""A tree node of arbitrary values"""
def __init__(self, value, children=None):
self.value = value
self.children = children or []
@yoniLavi
yoniLavi / setnum.py
Last active June 3, 2023 01:43
Basic example of defining a natural number using (frozen) sets
class SetNum(frozenset):
"""A set-theoretical definition of a natural number"""
def __repr__(self):
members_repr = ', '.join(map(repr, iter(self)))
return "{" + members_repr + "}"
def successor(self):
cls = type(self)
return cls(self | cls((self,))) # using a tuple to force nesting