Skip to content

Instantly share code, notes, and snippets.

@goulu
goulu / proportional.py
Last active September 20, 2021 09:40
assign n seats proportionaly to votes using the https://en.wikipedia.org/wiki/Hagenbach-Bischoff_quota method
def proportional(nseats,votes):
"""assign n seats proportionaly to votes using the https://en.wikipedia.org/wiki/Hagenbach-Bischoff_quota method
:param nseats: int number of seats to assign
:param votes: iterable of int or float weighting each party
:result: list of ints seats allocated to each party
"""
quota=sum(votes)/(1.+nseats) #force float
frac=[vote/quota for vote in votes]
res=[int(f) for f in frac]
n=nseats-sum(res) #number of seats remaining to allocate
@goulu
goulu / img2htmltable.py
Created January 31, 2014 13:00
Least efficient way to display an image in HTML
from PIL import Image
im = Image.open("img2htmltable.png")
mat=im.load()
width, height = im.size
file=open('img2htmltable.htm','w')
file.write('<table width="%d"px height="%d"px cellpadding=0 cellspacing=0 style="border-collapse: collapse;">'%(width,height))
for line in range(height):
@goulu
goulu / points_on_sphere.py
Created April 3, 2014 06:42
Generate N evenly distributed points on the unit sphere
def points_on_sphere(N):
""" Generate N evenly distributed points on the unit sphere centered at
the origin. Uses the 'Golden Spiral'.
Code by Chris Colbert from the numpy-discussion list.
"""
import numpy as np
phi = (1 + np.sqrt(5)) / 2 # the golden ratio
long_incr = 2*np.pi / phi # how much to increment the longitude
dz = 2.0 / float(N) # a unit sphere has diameter 2
@goulu
goulu / gist:0e35207dedf4e337c937
Last active August 29, 2015 14:20
Sum of Consecutive Primes
SCP[i_, n_] := Sum [Prime[j], {j, i, i + n - 1}]
PSP[n_, i_] := {m = i; While[p = SCP[m, n]; Not[PrimeQ[p]], m++]; p, m}
PSP[n_] := PSP[n, 1]
CPSP[list_] := {p = Map[PSP, list]; p1 = {};
While[p != p1, p1 = p; Print[p];
For[i = 2, i <= Length[list], i++,
While[p[[i, 1]] < p[[1, 1]],
p = ReplacePart[p, i -> PSP[list[[i]], p[[i, 2]] + 1]]];
While[p[[1, 1]] < p[[i, 1]],
p = ReplacePart[p, 1 -> PSP[list[[1]], p[[1, 2]] + 1]]];
@goulu
goulu / itimeout.py
Last active September 14, 2015 13:30
multiplatform timeout for loops in Python
from threading import Timer
from multiprocessing import TimeoutError
def itimeout(iterable,timeout):
"""timeout for loops
:param iterable: any iterable
:param timeout: float max running time in seconds
:yield: items in iterator until timeout occurs
:raise: multiprocessing.TimeoutError if timeout occured
"""
/*
Google Spreadsheet custom functions for Benford Law statistics
author : Philippe Guglielmetti aka Dr. Goulu
contact: drgoulu@gmailcom
license: LGPL
*/
function sum(a, b) { return a + b; } // not predefined ?
@goulu
goulu / fermat.py
Last active October 8, 2016 19:54
Generate (approximate) counter examples of Fermat's Theorem
#!/usr/bin/env python
# coding: utf8
"""
generate wrong counter-examples of Fermat's theorem
see http://www.drgoulu.com/2016/03/25/contre-exemples-au-theoreme-de-fermat-wiles/
"""
from __future__ import print_function, division
import itertools
__author__ = "Philippe Guglielmetti"
@goulu
goulu / faulhaber.py
Last active July 15, 2016 11:51
Faulhaber formula to calculate sum of powers of integers using a generator for Bernouilli numbers
from scipy.special import binom as binomial
def bernouilli_gen(init=1):
"""generator of Bernouilli numbers
:param init: int -1 or +1.
* -1 for "first Bernoulli numbers" with B1=-1/2
* +1 for "second Bernoulli numbers" with B1=+1/2
https://en.wikipedia.org/wiki/Bernoulli_number
https://rosettacode.org/wiki/Bernoulli_numbers#Python:_Optimised_task_algorithm
"""
@goulu
goulu / munchausen.py
Last active October 4, 2016 11:42
Efficient search of Munchausen numbers
#!/usr/bin/env python
# coding: utf8
"""
efficient search of Münchausen numbers
https://en.wikipedia.org/wiki/Munchausen_number
https://oeis.org/A046253
motivated by http://www.johndcook.com/blog/2016/09/19/munchausen-numbers/
"""
__author__ = "Philippe Guglielmetti"
@goulu
goulu / triples.py
Last active December 17, 2016 10:38
An inefficient way to generate Pythagorean triples
import itertools, math
def triples():
""" generates Pythagorean triples sorted by z,y,x with x<y<z
"""
for z in itertools.count(5):
for y in range(z-1,3,-1):
x=math.sqrt(z*z-y*y)
if x<y and abs(x-round(x))<1e-12:
yield (int(x),y,z)