Skip to content

Instantly share code, notes, and snippets.

View tanghaibao's full-sized avatar
:electron:
Turing complete

Haibao Tang tanghaibao

:electron:
Turing complete
View GitHub Profile
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@tanghaibao
tanghaibao / civ3.py
Last active May 31, 2023 05:37
Probability calculation for civ3 battle round
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
A problem from civ3 game. Let's say attacker has m hp, defender has n hp. In
each round, attacker will inflict damage of 1hp with probability of p, or lose
1hp with probability of 1-p. We ask the probability of final outcome.
"""
@tanghaibao
tanghaibao / cointoss.R
Created November 10, 2010 04:17
R code to check the posterior prob of a rigged coin-tossing experiment
# calculate the prob of P(fake|data)
calc_prob <- function(heads)
{
P_fake = .1 # my prior belief of the experiment being rigged
P_real = 1 - P_fake
P_data_given_fake = dnorm(heads, mean=10000, sd=10) # P(data|fake)
P_data_given_real = dbinom(heads, size=20000, p=.5) # P(data|real)
# bayes theorem
@tanghaibao
tanghaibao / casino_strategy.py
Created August 1, 2010 21:30
casino strategy
"""
This script simulates a common casino strategy when playing roulette:
bet on odd/even, and stick to your choice. bet $20 at start, if you lose,
double the bet; if you win, start with the $20 bet again.
This simulation suggests that if you follow this strategy for a few rounds (say 50),
more than 90% of the people will make money, with only a slight chance of bankrupt
$ python casino_strategy.py
@tanghaibao
tanghaibao / frond.py
Created July 29, 2010 03:35
fern leaf fractal
# Iterated_function_system to draw fern leaf
# http://en.wikipedia.org/wiki/Iterated_function_system
funcs = (
lambda x, y: (0, .16*y),
lambda x, y: (.2*x-.26*y, .23*x+.22*y+1.6),
lambda x, y: (-.15*x+.28*y, .26*x+.24*y+.44),
lambda x, y: (.85*x+.04*y, -.04*x+.85*y+1.6),
)
@tanghaibao
tanghaibao / elfHash.pyx
Created July 25, 2010 18:32
cython practice for elf hash
cpdef unsigned int elfHash(char *value):
cdef unsigned int i, x, result
result = 0
for i in range(len(value)):
result = (result << 4) + value[i]
x = result & 0xF0000000
if x:
result ^= (x >> 24)
result &= ~x
@tanghaibao
tanghaibao / gist:384470
Created April 29, 2010 23:52
phytozome xml query
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
This script queries the phytozome database to get gene annotations (chr, start, stop, gene name), commonly known as the .bed format.
"""
import urllib as U
import sys