Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View hickford's full-sized avatar

M Hickford hickford

  • Cambridge, United Kingdom
View GitHub Profile
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 / Co.key
Created October 5, 2015 18:43
FreeDOS ships with the Colemak keyboard layout (to use, type "keyb co"). This file extracted from FREEDOS\PACKAGES\BASE\KEYBX\source\keydos\Co.key
[KEYS:kcommon]
18S 33/f 33/F 33/#6 33/#0 33/#0
19S 25/p 25/P 25/#16 25/#0 25/#0
20S 34/g 34/G 34/#7 34/#0 34/#0
21S 36/j 36/J 36/#10 36/#0 36/#0
22S 38/l 38/L 38/#12 38/#0 38/#0
23S 22/u 22/U 22/#21 22/#0 22/#0
24S 21/y 21/Y 21/#25 21/#0 21/#0
25S 39/#59 39/: 39/#0 39/#0 39/#0
31S 19/r 19/R 19/#18 19/#0 19/#0
@hickford
hickford / 500.py
Created July 7, 2015 12:50
Project Euler problem 500
# https://projecteuler.net/problem=500 Project Euler problem 500
"""The number of divisors of 120 is 16.
In fact 120 is the smallest number having 16 divisors.
Find the smallest number with 2**500500 divisors.
Give your answer modulo 500500507."""
from codejamhelpers import primes
import heapq
@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

If a problem is hard, try solving a simpler version. Here, how to build n from atoms '1', '+' and '*' with a minimal number of 1's.

Make one observation. Suppose an optimal expression for n contains an expression for some smaller number m. Then that expression for m is optimal. Why? If it weren't, we could replace it with a better one, and so improve the expression for n. Contradiction.

Aha! This means we can attack the problem with dynamic programming. Assuming we have optimal expressions for all numbers smaller than n, we can deduce an optimal expression for n. How? The expression for n must end either with addition (n-1) + 1 or with multiplication d * (n/d) where d divides n. Inserting optimal expressions for n-1 and n/d , we compute the cost of the expressions for n, and choose the cheapest.

In code

best = MinDict() # optimal expression by number

best[1] = (1, "1", False) # cost, expression, needs brackets

#!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()
#!python3
"""Solves Howard's goblins puzzle using backtracking. https://www.facebook.com/howard.dale.3/posts/10152106759878462?stream_ref=5 """
from collections import deque
class Game:
def __init__(self):
self.goblins = [0]*7
self.history = deque()
def time(self):
@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