Skip to content

Instantly share code, notes, and snippets.

import itertools
import operator
# https://joelgrus.com/2015/07/07/haskell-style-fibonacci-in-python/
def tee_fibs():
yield 1
yield 1
fibs1, fibs2 = itertools.tee(tee_fibs())
next(fibs2) # Offset fibs2
yield from map(operator.add, fibs1, fibs2)
from time import time # For tracking how long everything is taking
import os
import matplotlib.pyplot as plt # For plotting
import matplotlib.ticker as ticker
import geopandas as gpd # For geographic data
import pandas as pd # For population data
from shapely.geometry import Polygon # Used to filter out empty polygons
# pip install z3-solver
from z3 import Int, Solver, And, sat, If, Sum, Or
from typing import List, Tuple
width = 8 # Number of columns
height = 8 # Number of rows
# Matrix of integers (0 if grass, 1 if tent), using integer so we can use Sum to count them
X = [[Int(f"x_{i+1}_{j+1}") for j in range(width)] for i in range(height)]
import z3
answers = [z3.Bool(f"answer{i}") for i in range(1,7)]
implications = [
z3.And(answers[1:]), # All of the below
z3.Not(z3.Or(answers[2:])), # None of the below
z3.And(answers[:2]), # All of the above
z3.Or(answers[:3]), # Any of the above
z3.Not(z3.Or(answers[:4])), # None of the above
z3.Not(z3.Or(answers[:5]))] # None of the above
@Recursing
Recursing / test_colored_print.py
Created July 29, 2019 11:31
Test terminal colors
def print_pos(board):
print()
uni_pieces = {
"r": "♜", "n": "♞", "b": "♝", "q": "♛", "k": "♚", "p": "♟",
"R": "♖", "N": "♘", "B": "♗", "Q": "♕", "K": "♔", "P": "♙", ".": "·"}
colors = ["\x1b[48;5;255m", "\x1b[48;5;253m"]
sc, ec = "\x1b[0;30;107m", "\x1b[0m"
for i, row in enumerate(board.split()):
colored = [colors[(i + c) % 2] + uni_pieces[p] for c, p in enumerate(row)]
print(" ", sc, 8 - i, " ".join(colored), ec)
@Recursing
Recursing / truncated_random.py
Last active April 10, 2018 10:19
Truncated random variable with given expected value
from random import random
def truncated_given_exp(minimum, maximum, expected):
if expected == minimum: return expected
maximum -= minimum
expected -= minimum
k = maximum/expected - 1 # Questa si comporta peggio della prima se expected - min < max - expected
return minimum + maximum * random()**k
@Recursing
Recursing / reverse_cf.py
Created February 27, 2018 17:16
Estrai informazioni dal codice fiscale
from collections import namedtuple
from datetime import date
Person = namedtuple('Person', 'cognome nome data_nascita sesso comune')
def reverse_cf(cf: str) -> Person:
assert len(cf) == 16
cf = cf.upper()
cognome = cf[:3]