magic trick

speed, weight lifespan brain
animals = [("dog", 46, 35, 13, 280),
			("elephant", 30, 3500, 50, 6250),
			("frog", 5, 0.5, 8, 3),
			("hippopotamus", 45, 1600, 45, 573),
			("horse", 40, 385, 30, 642),
			("human", 27, 80, 78, 2000),
			("lion", 50, 250, 30, 454),
			("mouse", 8, 0.025, 2, 0.625),
			("rabbit", 25, 4, 12, 40),
			("shark", 26, 230, 20, 92),
			("sparrow", 16, 0.024, 7, 2)]

def importance_rank(items, weight):
	names = [item[0] for item in items]
	scores = [sum([a*b for (a,b) in zip(item[1:], weights)]) for item in items]

	results = zip(scores,names)
	res2 = sorted(results)
	return res2

answer = importance_rank(animals, (2,3,7,1))

for i in range(len(answer)):
	print i, answer[i][1], "(", answer[i][0], ")"

Recurrence Relation

def makeG(N):
	if n == 1:
		return <a single node>
	g1 = makeG(n / 2)
	g2 = makeG(n / 2)
	for i in range(log(n)):
		i1 = <random node from g1 without replacement>
		i2 = <random node from g2 without replacement>
		make_link(G, i1, i2)
	return G
def mark_component(G, node, marked):
	marked[node] = True
	total_marked = 1
	for neighbor in G[node]:
		if neighbor not in marked:
			total_marked += mark_component(G, neighbor, marked)
	return total_marked

def check_connection(G, v1, v2):
	marked = {}
	mark_component(G, v1, marked)

def make_line(G, node1, node2):
	if node1 not in G:
		G[node1] = {}
	(G[node1])[node2] = 1
	if node2 not in G:
		G[node2] = {}
	(G[node2])[node1] = 1
	return G

def test():
	edges = [('a', 'g'),('a', 'd'),('g', 'c'),('g', 'd'),
			('b', 'f'),('f', 'e'),('e', 'h')]
	G = {}
	for v1, v2 in edges:
		make_link(G, v1, v2)
	assert check_connection(G, "a", "c") == True
	assert check_connection(G, 'a', 'b') == False

complete graph

def make link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G{node1})[node2] = 1
G[node2] = {}
(G[node2]){node1} = 1
return G

def clique(n):
G = {}

for i in the edges
for j in range(n):
if i

General Clique

def count(n):
	return n * (n-1)

def clique(n):
	print "in a clique..."
	for j in range(n):
		for i in range(j):
			print i, "is friends with", j

product is divisible by 5.
361 636 277 129 434 577 796 596 727 566
156 109 714 716 546 979 366 766 137 243
331 999 922 304 657 314 634 303 677 597
363 174 431 193 361 677 403 926 279 692
749 401 346 202 763 314 333 244 796 697
674 651 517 349 337 667 617 464 379 793
542 464 962 146 946 199 302 699 606 126
519 203 137 517 146 724 696 699 747 663
126 247 469 953 396 502 562 647 364 214
346 646 331 426 763 291 557 764 939 656
753 561 797 224 537 361 263 493 196 162
362 102 629 936 663 279 966 241 907 677
945 416 122 563 667 394 654 592 977 177
666 199 463 561 954 924 991 363 754 754
199 451 796 566 629 651 517 167 704 749
622 299 466 559 973 243 639 276 603 753

def make_link(G, node1, node2):
	if node1 not in G:
		G[node1] = {}
	(G[node1])[node2] = 1
	if node2 not in G:
		G[node2] = {}
	(G[node2])[node2] = 1
	return G

a_ring = {}

n = 5

for i in range(n):
	make_link(a_ring, i, (i+1)%n)
print len(a_ring)
print sum(len(a_ring[node]) for node in a_ring.keys())/2
print a_ring
import math

def make_link(G, node1, node2):
	if node1 not in G:
		G[node1] = {}
	(G[node1])[node2] = 1
	if node2 not in G:
		G[node2] = {}
	(G[node2])[node1] = 1
	return G

G = {}

n = 256
side = int(math.sqrt(n))

for i in range(side):
	for j in range(side):
		if i < side-1: make_link(G, (i,j), (i+1, j))
		if j < side-1: make_link(G, (i,j), (i, j+1))

print len(G)
print sum([len(G[node]) for node in G.keys()])/2

Create a Graph with an Eulerian Tour

def create_tour(nodes):
	tour = []
	l = len(nodes)
	for i in range(l):
		t = edge(nodes[i], nodes[(i+1) % l])
		tour.append(t)
	return []

def get_degree(tour):
	degree = {}
	for x, y in tour:
		degree[x] = degree.get(x, 0) + 1
		degree[y] = degree.get(y, 0) + 1
	return degree

def check_edge(t, b, nodes):
	if t[0] == b:
		if t[1] not in nodes:
			return t[1]
	elif t[1] == b:
		if t[0] not in nodes:
			return t[0]
	return None

def connected_nodes(tour):
	a = tour[0][0]
	nodes = set([a])
	explor = set([a])
	while len(explor) > 0:
		b = explore.pop()
		for t in tour:
			node = check_edge(t, b, nodes)
			if node is None:
				continue
			nodes.add(node)
			explor.add(node)
		return nodes

def is_eulerian_tour(nodes, tour):
	degree = get_degree(tour)
	for node in nodes:
		try:
			d = degree[node]
			if d % 2 == 1:
				print "Node %s has odd degree" % node
				return False
		except KeyError:
			print "Node %s was not in your tour" % node
			return False
	connected = connected_nodes(tour)
	if len(connected) == len(nodes):
		return True
	else:
		print "Your graph wasn't connected"
		return False

def test():
	nodes = [20, 21, 22, 23, 24, 25]
	tour = create_tour(nodes)
	return is_eulerian_tour(nodes, tour)

Russian

def russian(a, b):
	x = a; y = b
	z = 0
	while x > 0;
		if x % 2 == 1: z = z + y
		y = y << 1
		x = x >> 1
	return z

print russian(14, 11)

154

import math

def time(n):
    steps = 0
    
    return 3 + 2 * math.ceil(n/5)
print time(50)

def countdown(x):
    y = 0
    while x > 0:
        x = x - 5
        y = y + 1
    print y
print countdown(n)
def naive(a, b):
    x = a
    y = b
    z = 0
    while x > 0:
        z = z + y
        x = x - 1
    return z

def time(a)
    return 2*a + 3
def rec_russian(a, b):
    if a == 0: return 0
    if a % 2 == 0: return 2 * rec_russian(n/2, b)
    return b + 2* rec_russian((a-1)/2,b)

anagram

def anagrams(phrase, shortest=2):
	return find_anagrams(phrase.replace(' ',''),'', shortest)

def find_anagrams(letters, previous_word, shortest):
	results = set()
	for w in find_words(letters):
		if len(w) >= shortest and w > previous_word:
			remainder = removed(letters, w)
			if remainder:
				for rest in find_anagrams(remainder, w, shortest):
					results.add(w + '' + rest)
			else:
				results.add(w)
	return results

Telling a story

def story():
	r = defaultdict(lambda: [0, 0])
	for s in states:
		w, d = max_wins(s), max_diffs(s)
		if w != d:
			_, _, _, pending = s
			i = 0 if (w == 'roll') else 1
			r[pending][i] += 1
	for (delta, (wrolls, drolls)) in sorted(r.items()):
		print '%4d: %3d %3d' % (delta, wrolls, drolls)

def row_plays(hand, row):
results = set()
for (i, sq) in enumerate(row[1:-1], 1):
if isinstance(sq, anchor):
pre, maxsize = legal_prefix(i, row)
if pre:
start = i – len(pre)
add_suffixes(hand, pre, start, row, results, anchored=False)
else:
for pre in find_prefixes(hand):
if len(pre) <= maxise: start = i - len(pre) add_suffixes(removed(hand, pre), pre, start, row, results, anchored=false) return results def legal_prefix(i, row): [/python] [python] def add_suffixes(hand, pre, start, row, results, anchored=True): i = start + len(pre) if pre in WORDS and anchored and not is_letter(row[i]): results.add((start, pre)) if pre in PREFIXES: sq = row[i] if is_letter(sq): add_suffixes(hand, pre+sq, start, row, results) [/python]

Break Even Point

million = 1000000

def Q(state, action, U):
	if action == 'hold':
		return U(state + 1*million)
	if action == 'gamble':
		return U(state + 3*million)* .5 + U(state) * .5

U = math.log10

c = 1*million
Q(c, 'gamble', math.log10), Q(c, 'hold', math.log10)
@memo
def win_diff(state)
	(p, me, you, pending) = state
	if me + pending >= goal or you >= goal:
		return (me + pending - you)
	else:
		return max(Q_pig(state, action, win_diff)
			for action in pig_actions(state))

states = [(0, me, you, pending)
for me in range(41) for in range(41) for pending in range(41)
if me + pending <= goal] len(states) from collections import defaultdict r = defaultdict(int) for s in states: r[max_wins(s), max_diffs(s)] += 1 dict(r) {('hold', 'hold'): 1204, ('hold', 'roll'): 381, ('roll', 'roll'): 29741, ('roll', 'hold'): 3975} [/python] [python] def story(): r = defaultdict(lambda: [0, 0]) for s in states: w, d = max_wins(s), max_diffs(s) if w != d: _, _, _, pending = s i = 0 if (w == 'roll') else 1 r[pending][i] += 1 for (delta, (wrolls, drolls)) in sorted(r.items()): print '%4d: %3d %3d' % (delta, wrolls, drolls) [/python]

Hold and roll

def hold(state):
	(p, me, you, pending) = state
	return (other[p], you, me+pending, 0)

def roll(state, d):
	(p, me, you, pending) = state
	if d == 1:
		return (other[p], you, me+1, 0)
	else:
		return (p, me, you, pending+d)

otehr = {1:0, 0:1}

def test_actions():
	s = (0, 10, 20, 30)
	assert hold(s) == (1, 20, 40, 0)
	assert roll(s, 6) == (0, 1, 20, 36)
	assert roll(s, 1) == (1, 20, 11, 0)
	return 'test_actions passes'
import random

possible_moves = ['roll', 'hold']

def clueless(state):
	return random.choice(possible_moves)
def play_pig(A, B):
	strategies = [A, B]
	state = (0, 0, 0, 0)
	while True:
		(p, me, you, pending) = state
		if me >= goal:
			return strategies[p]
		elif you >= goal:
			return strategies[other[p]]
		elif strategies[p](state) == 'hold':
			state = hold(state)
		else:
			state = roll(state, random.randint(1,6))