Skip to content

Instantly share code, notes, and snippets.

View chemacortes's full-sized avatar

Chema Cortés chemacortes

View GitHub Profile
@chemacortes
chemacortes / benchmarks.scala
Last active February 3, 2024 14:35
Benchmarks in scala
def benchmarks[A](f: => A) =
inline def memory() = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
val t0 = System.nanoTime()
val m0 = memory()
val ret = f
val t1 = System.nanoTime()
val m1 = memory()
@chemacortes
chemacortes / fibo_matrix.py
Last active January 30, 2024 09:41
fibonacci - matrix exponentiation
import numpy as np
import sys
sys.set_int_max_str_digits(0)
def matrix_power(A: np.matrix, n: int) -> np.matrix:
if n == 0:
return np.matrix( ((1,0),(0,1)), dtype=object )
elif n%2 == 1:
@chemacortes
chemacortes / fibs.scala
Last active January 27, 2024 01:04
Fibonacci succession with scala3 (oneline versions)
val fibs: LazyList[BigInt] = BigInt(1) #:: BigInt(1) #:: (fibs zip fibs.tail).map(_+_)
val fibs: LazyList[BigInt] = 1 #:: fibs.scan(BigInt(1))(_+_)
val lucas: LazyList[BigInt] = 2 #:: fibs.scan(BigInt(1))(_+_)
@chemacortes
chemacortes / last_execution_time.py
Created September 28, 2023 16:30
Decorator that calc the last execution time of a function. The result is added as a new function attribute named 'last_execution_time'.
import time
import functools
def timer_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time_ns()
res = func(*args, **kwargs)
end = time.time_ns()
wrapper.last_execution_time = end - start
@chemacortes
chemacortes / isPrime.scala
Last active January 18, 2023 16:05
Primes generators
// Check primes with a stream
object isPrime {
lazy val primes: Stream[Int] = 2 #:: Stream.from(3,2)
.filter(i =>primes.takeWhile{j => j * j <= i}.forall{ k => i % k > 0})
def apply(n:Int) = primes.takeWhile(_<=n).contains(n)
def range(from:Int, to:Int) = primes.dropWhile(_<from).takeWhile(_<=to)
@chemacortes
chemacortes / longpath.py
Last active November 14, 2022 15:16
Clase LongPath para usar rutas largas en windows
from pathlib import WindowsPath
class LongPath(WindowsPath):
uncprefix = "\\\\?\\"
def __new__(cls, *pathsegments):
ins = super().__new__(cls, *pathsegments)
abspath = ins.expanduser().absolute()
match abspath.parts:
case (drive, *parts) if not drive.startswith(cls.uncprefix):
@chemacortes
chemacortes / Readme.md
Last active September 19, 2022 09:14
Juego de la vida de Conway realizado en numpy y animado con matplotlib. Basado en el artículo de Juan Luis Cano (@Juanlu001) en http://pybonacci.wordpress.com/2012/11/30/juego-de-la-vida-de-conway-con-python-usando-numpy/

El juego de la vida de Conway

Aunque hay muchas variantes del juego de la vida, nos vamos a centrar en la que publicó originalmente Conway en 1970.

El juego de la vida es un juego de cero jugadores, lo que quiere decir que su evolución está determinada por el estado inicial y no necesita ninguna entrada de datos posterior (Wikipedia).

Las reglas son las siguientes:

  • El tablero es una rejilla de celdas cuadradas (n x m) que tienen dos posibles estados: viva y muerta.
from itertools import count, takewhile
def calc_pi(error: float = 1e-6) -> float:
terms = (1 / (2 * k - 1) for k in count(1))
it = takewhile(lambda x: 2 * x >= error, terms)
ts = list(x - y for x, y in zip(it, it))
pi = 4 * sum(ts)
calc_pi.error = error
@chemacortes
chemacortes / fact_par.sc
Last active February 17, 2022 15:55
Scala parallel collections
#!/usr/bin/env -S scala-cli shebang
//> using scala "3.1.0"
//> using lib "org.scala-lang.modules::scala-parallel-collections:1.0.4"
import scala.collection.parallel.CollectionConverters._
def fact(n: BigInt) =
(n to 1 by -1).par.product
@chemacortes
chemacortes / reducebykey.py
Last active May 30, 2021 21:22 — forked from astrojuanlu/reducebykey.py
Python implementation of Spark reduceByKey()
from functools import reduce
from itertools import groupby
from operator import (itemgetter,add)
def reduceByKey(func, iterable):
"""Reduce by key.
Equivalent to the Spark counterpart
Inspired by http://stackoverflow.com/q/33648581/554319