Estimating Runtime

import itertools

houses = [1, 2, 3, 4, 5]
orderings = list(itertools.permutation(houses))

for (red, green, ivory, yellow, blue) in orderings:
	for (Englishman, Spaniard, Ukranian, Japanese, Norwegian) in orderings:
		for (dog, snails, fox, horse, ZEBRA) in orderings:
			for (coffee, tea, milk, oj, WATER) in orderings:
				for (oldGold, kools, Chesterfields, LuckyStrike, Parliaments) in orderings:
def zebra_puzzle():
	houses = first, _, middle, _, _ = [1, 2, 3, 4, 5]
	orderings = list(itertools.permutations(houses))
	return next((WATER, ZEBRA)
import time

def t():
	t0 = time.clock()
	zebra_puzzle()
	t1 = time.clock()
	return t1-t0

print t()

def timecall(fn, *args):
	t0 = time.clock()
	result = fn(*args)
	t1 = time.clock()
	return t1-t0
def timecall(fn, *args):
	t0 = time.clock()
	result = fn(*args)
	t1 = time.clock()
	return t1-t0

def timedcalls(n, fn, *args):
	times = [timedcall(fn, *args)[0] for _ in range(n)]
	return min(times), average(times), max(times)

def average(numbers):
	return sum(numbers) / float(len(numbers))
def instrument_fn(fn, *args):
	c.starts, c.items = 0, 0
	result = fn(*args)
	print '%s got %s with %5d iters over %7d items' % (
		fn.__name__, result, c.starts, c.items)

def ints(start, end):
i = start
while i <= end yield i i = i + 1 [/python] [python] def all_ints(): "Generate integers in the order 0, +1, -1, +2, -2, +3, -3,..." yield 0 for i in ints(1): yield +i yield -i [/python] [python] import string, re def valid(f): try: return not re.search(r'\b0[0-9]', f) and eval(f) is True except ArithmeticError: return False [/python] [python] import string, re def solve(formula): def valid(f): try: return not re.search(r'\b0[0-9]', f) and eval(f) is True except ArithmeticError: return False [/python]

card shuffle

import random

mydeck = [r+s for r in '23456789TJQKA' for s in 'SHDC']

def deal(numhands, n=5, deck=mydeck)
	random.shuffle(deck)
	return [deck[n*i:n*(i+1)] for i in range(numhands)]
def hand_percentages(n=700*1000):
	"sample n random hands and print a table of percentages for each type of hand."
	counts = [0] * 9
	for i in range(n/10):
		for hand in deal(10):
			ranking = hand_rank(hand)[0]
			counts[ranking] += 1
	for i in reversed(range(9)):
		print "%14s: %6.3f %%" % (hand_names[i], 100.*counts[i]/n)
def shuffle1(deck):
	N = len(deck)
	swapped = [False] * N
	while not all(swapped)
		i, j = random.randrange(N), random.randrange(N)
		swapped[i] = swapped[j] = True
		swap(deck, i, j)

def swap(deck, i, j):
	print 'swap', i, j
	deck[i], deck[j] = deck[j], deck[i]
utas = ['Peter', 'Andy', 'Sarah', 'Gundega', 'Job', 'Sean']
uppercasetas = [name.upper() for name in utas]
print uppercasetas

total nums

def ss(nums):
	total = 0
	for i in range(len(nums)):
		total = (total + num[i]**2)
	return total
def ss(nums):
	return sum(x**2 for x in nums)

poker problem set
[‘js’,’jd’,’2s’,’2c’,’7h’]
[(11,’s’),(11,’d’),(2,’s’),(2,’c’),(7,’h’)]

key abs mean absolute value, so -5 would be max nums

def poker(hands):
	"Return the best hand: poker([hand,...]) => hand"
	return max

print max([3, 4, 5, 0]), max([s, 4, -5, 0], key=abs)

highest rank

def poker(hands):
	"Return the best hand: poker([hand,...]) => hand"
	return max(hands, key=hand_rank)

def hand_rank(hand)
	return ???

print max([3, 4, 5, 0]), max([s, 4, -5, 0], key=abs)

Testing

def poker(hands):
    "Return the best hand: poker([hand,...]) => hand"
    return max(hands, key=hand_rank)

def test():
    "Test cases for the functions in poker program"
    sf = "6C 7C 8C 9C TC".split() 
    fk = "9D 9H 9S 9C 7D".split() 
    fh = "TD TC TH 7C 7D".split()
    assert poker([sf, fk, fh]) == sf
    assert poker([fk, fh]) == fk
    assert poker([fh, fh]) == fh
    assert poker([sf]) == sf
    assert poker([sf] + 99*[fh]) == sf
    return 'tests pass'
def hand_rank(hand):
	"Return a value indicating the ranking of a hand"
    ranks = card_ranks(hand)
    if straight(ranks) and flush(hand):            # straight flush
        return (8, max(ranks))
    elif kind(4, ranks):                           # 4 of a kind
        return (7, kind(4, ranks), kind(1, ranks))
    elif kind(3, ranks) and kind(2, ranks):        # full house
        return (6, kind(3, ranks), kind(2, ranks))
    elif flush(hand):                              # flush
        return (5, ranks)
    elif straight(ranks):                          # straight
        return (4, max(ranks))
    elif kind(3, ranks):                           # 3 of a kind
        return (3, kind(3, ranks), ranks)
    elif two_pair(ranks):                          # 2 pair
        return (2, two_pair(ranks), ranks)
    elif kind(2, ranks):                           # kind
        return (1, kind(2, ranks), ranks)
    else:                                          # high card
        return (0, ranks)
def poker(hands):
    "Return the best hand: poker([hand,...]) => hand"
    return allmax(hands, key=hand_rank)

def allmax(iterable, key=None):
	"Return a list of all items equal to the max of the iterable."
	result, maxval = [], None
	key = key or (lambda x: x)
	for x in iterable:
		xval = key(x)
		if not result or xval > maxval:
			result, maxval = [x], xval
		elif xval == maxval:
			result.append(x)
	return result

def hand_rank(hand):
	"Return a value indicating the ranking of a hand"
    ranks = card_ranks(hand)
    if straight(ranks) and flush(hand):            # straight flush
        return (8, max(ranks))
    elif kind(4, ranks):                           # 4 of a kind
        return (7, kind(4, ranks), kind(1, ranks))
    elif kind(3, ranks) and kind(2, ranks):        # full house
        return (6, kind(3, ranks), kind(2, ranks))
    elif flush(hand):                              # flush
        return (5, ranks)
    elif straight(ranks):                          # straight
        return (4, max(ranks))
    elif kind(3, ranks):                           # 3 of a kind
        return (3, kind(3, ranks), ranks)
    elif two_pair(ranks):                          # 2 pair
        return (2, two_pair(ranks), ranks)
    elif kind(2, ranks):                           # kind
        return (1, kind(2, ranks), ranks)
    else:                                          # high card
        return (0, ranks)

def card_ranks(cards):
    "Return a list of the ranks, sorted with higher first."
    ranks = ['--23456789TJQKA'.index(r) for r,s in cards]
    ranks.sort(reverse=True)
    return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2])

def straight(ranks):
	"Return True if the ordered ranks form a 5-card straight."
	return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5

def flush(hand):
	"Return True if all the cards have the same suit."
	suits = [s for r, s in hand]
	return len(set(suits)) == 1

def kind(n, ranks):
	"""Return the first rank that this hand has exactly n of.
	Return None if there is no n-of-a-kind in the hand."""
	for r in ranks:
		if ranks.count(r) == n: return r
	return None

def two_pair(ranks):
	"""If there are two pair, return the two ranks as a
	tuple: (highest, lowest); otherwise return None."""
	pair = kind(2, ranks)
	lowpair = kind(2, list(reversed(ranks)))
	if pair and lowpair != pair:
		return (pair, lowpair)
	else:
		return None

def test():
    "Test cases for the functions in poker program"
    sf = "6C 7C 8C 9C TC".split() # Straight Flush
    fk = "9D 9H 9S 9C 7D".split() # Four of a Kind
    fh = "TD TC TH 7C 7D".split() # Full House
    tp = "5S 5D 9H 9C 6S".split() # two pair
    s1 = "AS 2S 3S 4S 5C".split() # A-5 straight
    s2 = "2C 3C 4C 5S 6S".split() # 2-6 straight
    ah = "AS 2S 3S 4S 6C".split() # A high
    sh = "2S 3S 4S 6C 7D".split() # 7 high
    assert poker([s1, s2, ah, sh]) == s2
    fkranks = card_ranks(fk)
    tpranks = card_ranks(tp)
    assert kind(4, fkranks) == 9
    assert kind(3, fkranks) == None
    assert kind(2, fkranks) == None
    assert kind(1, fkranks) == 7
    assert two_pair(fkranks) == None
    assert two_pair(tpranks) == (9, 5)
    assert straight([9, 8, 7, 6, 5]) == True
    assert straight([9, 8, 8, 6, 5]) == False
    assert flush(sf) == True
    assert flush(fk) == False
    assert card_ranks(sf) == [10, 9, 8, 7, 6]
    assert card_ranks(fk) == [9, 9, 9, 9, 7]
    assert card_ranks(fh) == [10, 10, 10, 7, 7]
    assert poker([sf, fk, fh]) == sf
    assert poker([fk, fh]) == fk
    assert poker([fh, fh]) == fh
    assert poker([sf]) == sf
    assert poker([sf] + 99*[fh]) == sf
    assert hand_rank(sf) == (8, 10)
    assert hand_rank(fk) == (7, 9, 7)
    assert hand_rank(fh) == (6, 10, 7)
    return 'tests pass'

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

simulator

edges = {(1,'a'):2,
	(2, 'a'): 2,
	(2, '1'): 3,
	(3, '1'): 3}
	accepting = [ 3 ]

	def fsmsim(string, current, edges, accepting):
		if string == ""
			return current in accepting
		else:
			letter = string[0]
			if (current, letter) in edges:
				destination = edges[(current,letter)]
				remaining_string = string[1:]
				return fsmsim(remaining_string,destination,edges,accepting)
			else:
				return False
	print fsmsim("aaa111",1,edges,accepting)
import re

def umnums(sentence):
	r = r"[0-9]+"
	sum = 0
	for found in re.findall(r,sentence):
		sum = sum + int(found)
	return sum
(?:[a-z]+-[a-z]+)|(?:[a-z]+)
def nfsmsim(string, current edges, accepting):
	if string == "":
		return current in accepting
	else:
		letter = string[0:1]
		if (current, letter) in edges:
			remainder = string[1:]
			newstates = edges[(current, letter)]
			for newstate in newstates:
				if nfsmsim(remainder, newstate, edges, accepting):
					return True
	if current in visited:
		return None
	elif current in accepting:
		return ""
	else:
		newvisited = visited + [current]
		for edge in edges:
			if edge[0] == curent:
				for newstate in edges[edge]:
					foo = nfsmaccepts(nestate, edges, accepting, newvisited)
					if foo != None:
						return edge[1] + foo
		return None

breaking points

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> "Ada Lovelace".find(" ")
3
>>> "Alan Turing".find("n",4)
9
def myfirst_yoursecond(p,q):
	pindex = p.find(" ")
	qindex = q.find(" ")
	return p[ :pindex] == q[qindex+1:]
>>> "Python is fun".split()
['Python', 'is', 'fun']
>>> "July-August 1842".split()
['July-August', '1842']
>>> "6*9==42".split()
['6*9==42']

Regular expression [1-3][4-8][a-b]

>>> r"[0-9][0-9]"
>>> re.findall(r"[0-9][0-9]", "July 28, 1821")
>>> re.findall(r"[0-9][0-9]", "12345")

r”a+”, r”[0-1]+”
regular expression rule is maximum match eat single match
re.findall(r”[0-9][ ][0-9]+”, “a1 2b cc3 44d”)
r”[0-9]+%”
r”[a-z]+|[0-9]+”,”Goothe 1798″

regexp = r”[a-z]+-?[a-z]+”

>>> re.findall(r”[0-9].[0-9]”, “1a1 222 cc3”)
[‘1a1’, ‘222’]

edges = {(1,'a'):2,
	(2, 'a'): 2,
	(2, '1'): 3,
	(3, '1'): 3}