Skip to content

Instantly share code, notes, and snippets.

View hickford's full-sized avatar

M Hickford hickford

  • Cambridge, United Kingdom
View GitHub Profile
@hickford
hickford / numbers-game.py
Last active September 28, 2021 20:20
How to make 21 from the numbers 1,5,6,7?
#!python
import operator
import itertools
from fractions import Fraction
operations = dict()
operations['+'] = operator.add
operations['-'] = operator.sub
operations['/'] = operator.truediv
operations['*'] = operator.mul
@hickford
hickford / group-adjacent-by.cs
Created April 1, 2012 16:58
GroupAdjacentBy method for .NET in C#
public static class LINQExtensions
{
public static IEnumerable<IGrouping<TKey, TElement>> GroupAdjacentBy<TElement, TKey>(this IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer=null)
{
comparer = comparer ?? EqualityComparer<TKey>.Default;
List<TElement> elements = null;
TKey key = default(TKey);
TKey lastKey = default(TKey);
foreach (var x in source)
{
@hickford
hickford / buffer-until-calm.cs
Created March 29, 2012 21:32
BufferUntilCalm method for .NET's Reactive Extensions
public static class ObservableExtensions
{
/// <summary>
/// Group observable sequence into buffers separated by periods of calm
/// </summary>
/// <param name="source">Observable to buffer</param>
/// <param name="calmDuration">Duration of calm after which to close buffer</param>
/// <param name="maxCount">Max size to buffer before returning</param>
/// <param name="maxDuration">Max duration to buffer before returning</param>
public static IObservable<IList<T>> BufferUntilCalm<T>(this IObservable<T> source, TimeSpan calmDuration, Int32? maxCount=null, TimeSpan? maxDuration = null)
#!python
elements = "H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Uut Fl Mc Lv Ts Og".split()
def decompose(word):
"""Express given word as chemical compound. If there are multiple solutions, return one of minimal weight."""
progress = [False for x in range(len(word)+1)] # solution for word[:i]
progress[0] = []
for i in range(1, len(word)+1):
possibles = list()
"""I'm thinking of a ten-digit integer whose digits are all distinct. It happens that the number formed by the first n of them is divisible by n for each n from 1 to 10. What is my number?
http://blog.pizzahut.com/flavor-news/national-pi-day-math-contest-problems-are-here-2/ """
digits = [None] * 10
def pretty(A):
return "".join(str(x) if x != None else "-" for x in A)
assert pretty([5, None, 3]) == "5-3"
def comparator(x, i, j):
"""Swap x[i] and x[j] if they are out of order"""
if x[i] > x[j]:
x[i], x[j] = x[j], x[i]
def oddevenmergesort(x, indexes=None):
"""In-place odd-even mergesort, applied to slice of x defined by indexes. Assumes len(x) is a power of 2. """
if indexes == None:
indexes = range(len(x))
n = len(indexes)
@hickford
hickford / layout.ini
Last active December 24, 2015 09:39
If your Windows keyboard layout is Colemak UK and your colleague would like to type in Qwerty UK, run this PKL script.
; Keyboard Layout definition for
; Portable Keyboard Layout
; http://pkl.sourceforge.net
[informations]
layoutname = ColemakUk
layoutcode = ColemakUk
localeid = 00000809
[global]
@hickford
hickford / alice.txt
Last active December 17, 2015 18:58
Unified diff example `diff -u alice.txt bob.txt > unified-diff.txt`
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversation?'
alicewasbeginningtogetverytiredofsittingbyhersisteronthe
bankandofhavingnothingtodoonceortwiceshehadpeepedintothe
bookhersisterwasreadingbutithadnopicturesorconversationsin
itandwhatistheuseofabookthoughtalicewithoutpicturesor
conversation
soshewasconsideringinherownmindaswellasshecouldforthe
hotdaymadeherfeelverysleepyandstupidwhetherthepleasure
ofmakingadaisychainwouldbeworththetroubleofgettingupand
pickingthedaisieswhensuddenlyawhiterabbitwithpinkeyesran
#!python
# -*- coding: utf-8 -*-
# http://blog.jgc.org/2013/04/the-minimum-coin-problem-with-prize.html
# I have in my pocket the following British coins: one £2, two £1, two 50p, three 20p, one 10p, two 5p, two 2p and two 1p. I wish to buy a copy of today's paper at a cost of £1.70.
# What is the maximum number of coins I can use to pay for the paper? With the restriction that I pay in a reasonable manner (e.g. I could give exactly £1.70 or an amount greater than that but without giving extraneous coins: e.g. giving the seller all the coins would not be acceptable, but giving him one £1 an two 50ps and expecting 30p in change is OK). The reasonable manner is simply: if I give the seller a set of coins he should not be able to return any to me without the sum of the remaining coins dropping below £1.70.
from collections import Counter, OrderedDict
def solve_exact(coins, P, f=len):