zip

class ZIPCode:
	def __init__(self, zip):
		self._zip = zip
		self.checkRep()

	def zip(self):
		return self._zip()

	def checkRep(self):
		assert len(self.zip()) == 5
		for i in range(0, 5):
			assert '0' <= self.zip()[i] <= '9'
import re

def test(s):

	if re.search("]*>", s) >= 0:
		return "FAIL"
	else
		return "PASS"

def ddmin(s):
	assert test(s) == "FAIL"

	n = 2
	while len(s) >= 2:
		start = 0
		subset_length = len(s) / n
		some_complement_is_failing = False

		while start < len(s):
			compleent = s[:start] + [start + subset_length:]
			if test(complement) == "FAIL":
				s = complement
				n = max(n - 1, 2)
				some_complement_is_failing = True
				break

			start = start + subset_length

		if not some_complement_is_failing:
			n = min( n * 2, len(s))
			if n == len(s):
				break

	return s
import random

def fuzzer():
	string_length = int(random.random() * 1024)
	out = ""
	for i in range(0, string_length):
		c = chr(int(random.random() * 96 + 32))
		out = out + c

	return out
print fuzzer()
patches = [1, 2, 3, 4, 5, 6, 7, 8]

def test(s):
	print repr(s), len(s),
	if 3 in s and 6 in s:
		print "FAIL"
		return "FAIL"
	else:
		print "PASS"
		return "PASS"

print ddmin(patches, test)

Debugging

def debug(command, my_arg, my_locals):
	global stepping
	global breakpoints

	if command.find(' ') > 0:
		arg = command.split(' ')[1]
	else:
		arg = None

	if command.startswith('s'):
		stepping = True
		return True

def traceit(frame, event, arg):
	global stepping
	global breakpoints

	if event == 'Line':
		if stepping or breaking.has_key(frame.f_lineno):
			resume = False
			while not resume:
				print event, frame.f_lineno, frame.f_code.co_name, frame.f_locals
				command = input_command()
				resume = debug(command, arg, frame.f_locals)
		return traceit

Assertions is the most powerful debugging tool, automating debugging tool.

def test_square_root():
	assert square_root(4) == 2
	assert square_root(g) == 3
	# and so on
import math

def square_root(x):
	assert x >= 0
	y = math.sqrt(x)
	assert y * y == x
	return y

testing square root

import math
random

def square_root(x):
	assert x >= 0
	y = math.sqrt(x)
	assert y * y == x
	return y

for i in range(1, 1000):
	r = random.random() * 10000
	try:
		z = square_root(r)
	except:
		print r, math.sqrt(r) * math.sqrt(r)
		break

print "Done!"
import math
import random

def square_root(x, eps=10e-7):
    assert x >= 0
    y = math.sqrt(x)
    assert abs(y * y - x) < eps
    return y

for i in range(1, 1000):
    r = random.random() * 1000
    z = square_root(r)

print "Done!"
class Time:
	def __init__(self, h = 0, m = 0, s = 0):
		self._hours = h
		self._minutes = m
		self._seconds = s

	def hours(self):
		return self._hours

	def minutes(self):
		return self._minutes

	def seconds(self):
		return self._seconds

	def __repr__(self):
		return "{:2d}{:2d}{:2d}".format(
			self.hours(), self.minutes(), self.seconds())

t = Time(13, 0, 0)
print t

parsing tree

hello my luft ballons
[(“word-element”, “hello”),
(“word-element”,”my”),
(“javascript-element”), “document.write(99);”)
(“word-elment”, “luftballons”),
]

def interpret(trees):
	for tree in trees:
		treetype = tree[0]
		if treetype == "word-element":
			graphics.word(node[1])
		elif treetype == "javascript-element":
			jstext = tree[1]
			jslexer = lex.lex(module=jstokens)
			jsparser = yacc.yacc(module=jsgrammar)
			jstree = jsparser.parse(jstext,lexer=jslexer)
			result = jsinterp.interpret( jstree )
			graphics.word( result )
def env_lookup(vname, env):
	if vname in env[1]:
		return (env[1])[vname]
	elif env[0] == None:
		return None
	else:
		return env_lookup(vname, env[0])
var a = 1;
function mistletue(baldr){
	baldr = baldr + 1;
	a = a + 2;
	baldr = baldr + a;
	return baldr;
}
write (mistletue(5));
def optimize(tree):
	etype = tree[0]
	if etype == "binop":
		a = tree[1]
		op = tree[2]
		b = tree[3]
		if op == "*" and b == ("number","1"):
			return a
		return tree
def remove_html_markup(s):
	tag = False
	out = ""

	for c in s:
		if c == '<':
			tag = True
		elif c == '>':
			tag = False
		elif not tag:
			out = out + c

	return out
print remove_html_markup("<b>foo</b>")

fibo

def fibo(n):
	in n <= 2:
		return 1
	else:
		return fibo(n-1)+fibo(n-2)

print fibo(20)
&#91;/python&#93;

&#91;python&#93;
chart = {}

def memofibo(n):
    if n in chart:
    	return chart&#91;n&#93;
    elif n <= 2:
    	chart&#91;n&#93; = 1
    
print memofibo(24)
&#91;/python&#93;

&#91;python&#93;
def t_javascript(token):
	r'<script\ type=\"text\/javascript\"\>'
	token.lexer.code_start = token.lexer.lexpos
	token.lexer.begin("javascript")

def t_javascript_end(token):
def t_javascript(token):
	r'<script\ type=\"text\/javascript\"\>'
	token.lexer.code_start = token.lexer.lexpos
	token.lexer.begin("javascript")

def t_javascript_end(token):
	r'\<\/script\>'
	token.value = token.lexer.lexdata[token.lexer.code_start:
		token.lexer.lexpos-9]
	token.type = 'JAVASCRIPT'
	token.lexer.lineno += token.value.count('\n')
	token.lexer.begin.('INITIAL')
	return token

parthing:構文解析 lexing:字句解析
after regular expression, lexer get token value.

javascript to python

#        function mymin(a, b){
#            if (a < b){
#                return a;
#            } else {
#                return b;
#            };
#        }
#        
#        function square(x){
#            return x * x;
#        }
#        
#        write(mymin(square(-2), square(3)));

def mymin(a, b):
	if (a < b):
		return a
	else:
		return b

def square(x):
	return x * x
print mymin(square(-2), square(3))
[1,2,3,4,5,6,7]

def odds_only(numbers):
	for N in numbers:
		if N % 2 == 1:
			yield N
def small_words(words):
	for word in words:
		if len(word) <= 3:
			yield word

print [w for w in small_words(["The","quick","brown","fox"])]
grammar = [
	("exp",["exp","+","exp"]),
	("exp",["exp","-","exp"]),
	("exp",["(","exp",")"]),
	("exp",["num"]),
]

def expand(tokens, grammar):
	for pos in range(len(tokens)):
		for rule in grammar:

depth = 1
utterances = [["exp"]]
def sublists(big_list, selected_so_far):
	if big_list == []:
		print selected_so_far
	else:
		current_element = big_list[0]
		rest_of_big_list = big_list[1:]
		sublists(rest_of_big_list, selected_so_far + [current_element])
		sublists(rest_of_big_list, selected_so_far )

	dinner_guests = ["LM", "ECS", "SBA"]
	sublists(dinner_guests, [])
def cfgempty(grammar, symbol, visited):
	if symbol in visited:
		return None
	elif not any([rule[0] == symbol for rule in grammar ]):
		return [symbol]
	else:
		new_visited = visited + [symbol]
		for rhs in [r[1] for r in grammar if r[0] == symbol]:
			if all([None] != cfgempty(frammar, r, new_visited) for r in rhs):
				result = []
				for r in rhs:
					result = result + cfgempty(grammar, r, new_visited)
				return result
		return None

JS Number

tokens = (
	'IDENTIFIER',
	'NUMBER',
	'STRING'
	)

def t_NUMBER(t):
	r'-?[0-9]+(?:\.[0-9]*)?'
	t.value = float(t.value)
	return t

def t_STRING(t):
	r'([^"\\]|(\\.))*"'
	t.value = t.value[1:-1]
	return t
function gcd(a,b){
	if(a==b){
		return a;
	} else {
		if(a > b){
		return gcd(a-b, b);
		} else {
			return gcd(a, b- a)
		}
	}
}

recursion: function call itself

javascript and python

def uptoten(x):
if x < 10: return x else: return 10 javascriptcode=""" function uptoten(x) { if x < 10 { return x } else { return 10 } } """ [/python]

element

def findmax(f,l):
	best_element_sofar = None
	best_f_value_sofar = None
	for i in range(len(l)-1):
		elt = l[i]
		f_value = f(elt)
		if best_f_value_sofar == None or \
			f_value > best_f_value_sofar:
			best_element_sofar = elt
			best_f_value_sofar = f_value
	return best_element_sofar

Modern programming languages like Python can understand hexadecimal
numbers natively! Try it:

print 0x234 # uncomment me to see 564 printed
print 0xb # uncomment me to see 11 printed

import ply.lex as lex

tokens = ('NUM', 'ID')

def test_lexer(input_string):
	lexer.input(input_string)
	result = [ ]
	while True:
		tok = lexer.token()
		if not tok: break
		result = result + [(tok.type,tok.value)]
	return result

specification

import re
re.findall(needle,haystack)

def t_LANGLESLASH(token):
    r'
def t_NUMBER(token):
	r"[0-9]+"
	token.value = int(token.value)
	return token
def t_STRING(token):
    r'"[^"]*"'
    return token
def t_WORD(token):
    r'[^ <>]+'
    return token
def t_IDENTIFIER(token):
    r'[a-zA-Z][a-zA-Z_]*'
    return token
def t_NUMBER(token):
    r'-?[0-9]+(:?\.[0-9]*)'   
    return token