Skip to content

Instantly share code, notes, and snippets.

@benui-dev
Created June 16, 2011 07:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benui-dev/1028843 to your computer and use it in GitHub Desktop.
Save benui-dev/1028843 to your computer and use it in GitHub Desktop.
Chinese Restaurant process in Python
import random
# Play with different concentrations
for concentration in [0.0, 0.5, 1.0]:
# First customer always sits at the first table
# To do otherwise would be insanity
tables = [1]
# n=1 is the first customer
for n in range(2,5000):
# Gen random number 0~1
rand = random.random()
p_total = 0
existing_table = False
for index, count in enumerate(tables):
prob = count / (n + concentration)
p_total += prob
if rand < p_total:
tables[index] += 1
existing_table = True
break
# New table!!
if not existing_table:
tables.append(1)
for index, count in enumerate(tables):
print index, "X"*(count/100), count
print "----"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment