Example output
>>> def is_even(x): return x % 2 == 0
>>> sort([1, 2, -3])
[-3, 1, 2]
>>> sort(range(10), comparer(key=is_even))
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
>>> sort(range(10), lambda x,y: y-x)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> removeall(4, [])
[]
>>> removeall('s', 'This is a test. Was a test.')
'Thi i a tet. Wa a tet.'
>>> removeall('s', 'Something')
'Something'
>>> removeall('s', '')
''
>>> reverse([])
[]
>>> reverse('')
''
>>> count_if(is_even, [1, 2, 3, 4])
2
>>> count_if(is_even, [])
0
>>> sum([])
0
>>> product([])
1
>>> argmax([1], lambda x: x*x)
1
>>> argmin([1], lambda x: x*x)
1
>>> argmax([])
# raises TypeError as expected
>>> argmin([])
# raises TypeError as expected
# Test of memoize with slots in structures
>>> countries = [Struct(name='united states'), Struct(name='canada')]
# Pretend that 'gnp' was some big hairy operation:
>>> def gnp(country): return len(country.name) * 1e10
>>> gnp = memoize(gnp, '_gnp')
>>> map(gnp, countries)
[130000000000.0, 60000000000.0]
>>> countries # note the _gnp slot.
[Struct(_gnp=130000000000.0, name='united states'), Struct(_gnp=60000000000.0, name='canada')]
# This time we avoid re-doing the calculation
>>> map(gnp, countries)
[130000000000.0, 60000000000.0]
# Test Queues:
>>> nums = [1, 8, 2, 7, 5, 6, -99, 99, 4, 3, 0]
>>> def qtest(q): return [q.extend(nums), [q.pop() for i in range(len(q))]][1]
>>> qtest(Stack())
[0, 3, 4, 99, -99, 6, 5, 7, 2, 8, 1]
>>> qtest(FIFOQueue())
[0, 3, 4, 99, -99, 6, 5, 7, 2, 8, 1]
>>> qtest(PriorityQueue())
[-99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 99]
>>> def gt(a,b): return a > b
>>> qtest(PriorityQueue(gt))
[99, 8, 7, 6, 5, 4, 3, 2, 1, 0, -99]
>>> d = DefaultDict(0)
>>> d['x'] += 1
>>> d['x']
1
>>> d = DefaultDict([])
>>> d['x'] += [1]
>>> d['y'] += [2]
>>> d['x']
[1]
>>> Dict(a=1, b=2, c=3)
{'a': 1, 'c': 3, 'b': 2}
>>> q = FIFOQueue();q.append(1);q.append(2)
>>> q.pop(), q.pop()
(1, 2)
>>> s = Set(10, 20)
>>> s
{10: 1, 20: 1}
>>> 10 in s
1
>>> 99 in s
0
>>> del s[10]
>>> s[30] = True
>>> s
{20: 1, 30: 1}
>>> [x/5 for x in s]
[4, 6]
>>> q = Stack()
>>> q.append(1)
None
>>> q.append(2)
None
>>> q.pop(), q.pop()
(2, 1)
>>> s = Struct(a=1, b=2)
>>> s.a
1
>>> s.a = 3
>>> s
Struct(a=3, b=2)
>>> def m(): abstract() # Similar to Java's 'abstract void m()'
>>> argmax(['one', 'to', 'three'], len)
'three'
>>> argmax_list(['one', 'three', 'seven'], len)
['three', 'seven']
>>> argmin(['one', 'to', 'three'], len)
'to'
>>> argmin_list(['one', 'to', 'three', 'or'], len)
['to', 'or']
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
>>> every(callable, [min, max])
1
>>> every(callable, [min, 3])
0
>>> find_if(callable, [3, min, max])
<built-in function min>
>>> find_if(callable, [1, 2, 3])
None
>>> vals = [100, 110, 160, 200, 160, 110, 200, 200, 220]
>>> histogram(vals)
[(100, 1), (110, 2), (160, 2), (200, 3), (220, 1)]
>>> histogram(vals, 1)
[(200, 3), (160, 2), (110, 2), (100, 1), (220, 1)]
>>> histogram(vals, 1, lambda v: round(v, -2))
[(200.0, 6), (100.0, 3)]
>>> if_(2 + 2 == 4, 'ok', lambda: expensive_computation())
'ok'
>>> for i, c in indexed('abc'): print i, c
0 a
1 b
2 c
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> log2(1024)
10.0
>>> log2(1.0)
0.0
>>> log2(0)
# raises OverflowError as expected
>>> median([10, 100, 11])
11
>>> median([1, 2, 3, 4])
2.5
>>> def fib(n): return (n<=1 and 1) or (fib(n-1) + fib(n-2))
>>> fib(9)
55
# Now we make it faster:
>>> fib = memoize(fib)
>>> fib(9)
55
>>> map(method('upper'), ['a', 'b', 'cee'])
['A', 'B', 'CEE']
>>> map(method('count', 't'), ['this', 'is', 'a', 'test'])
[1, 0, 0, 2]
>>> mode([1, 2, 3, 2])
2
>>> normalize([1,2,1])
[0.25, 0.5, 0.25]
>>> num_or_str('42')
42
>>> num_or_str(' 42x ')
'42x'
>>> removeall(3, [1, 2, 3, 3, 2, 1, 3])
[1, 2, 2, 1]
>>> removeall(4, [1, 2, 3])
[1, 2, 3]
>>> reverse([1, 2, 3])
[3, 2, 1]
>>> reverse('abc')
'cba'
>>> some(callable, [min, 3])
1
>>> some(callable, [2, 3])
0
>>> sort([3, 1, 2])
[1, 2, 3]
>>> reverse(sort([3, 1, 2]))
[3, 2, 1]
>>> sort([-3, 1, 2], comparer(abs))
[1, 2, -3]
>>> sum([1, 2, 3])
6
>>> sum(range(8), lambda x: 2**x)
255
>>> timer(100, abs, -1)
{'secs': 0.0, 'val': 1}
>>> timer(1e4, Dict)
{'secs': 0.030000000000000027, 'val': {}}
>>> timer(pow, 3, 4)
{'secs': 0.0, 'val': 81}
>>> timer(Dict)
{'secs': 0.0, 'val': {}}
>>> union([1, 2, 3], [2, 3, 4])
[1, 2, 3, 4]
>>> unique([1, 2, 3, 2, 1])
[1, 2, 3]
>>> update({'a': 1}, a=10, b=20)
{'a': 10, 'b': 20}
>>> update(Struct(a=1), a=10, b=20)
Struct(a=10, b=20)
>>> vector_add((0, 1), (8, 9))
(8, 10)
>>> a = ReflexVacuumAgent()
>>> a.program
<function program at 0x82826b4>
>>> a.program((loc_A, 'Clean'))
'Right'
>>> a.program((loc_B, 'Clean'))
'Left'
>>> a.program((loc_A, 'Dirty'))
'Suck'
>>> a.program((loc_A, 'Dirty'))
'Suck'
>>> e = TrivialVacuumEnvironment()
>>> e.add_object(TraceAgent(ModelBasedVacuumAgent()))
<agents.TrivialVacuumEnvironment instance at 0x827ccdc>
>>> e.run(5)
perceives ((0, 0), 'Clean') and does Right
perceives ((1, 0), 'Dirty') and does Suck
perceives ((1, 0), 'Clean') and does NoOp
perceives ((1, 0), 'Clean') and does NoOp
perceives ((1, 0), 'Clean') and does NoOp
None
>>> agents = [ModelBasedVacuumAgent, ReflexVacuumAgent, TableDrivenVacuumAgent, RandomVacuumAgent]
# For the following set of trials, you should get results of approximately:
# ModelBased: 9, Reflex: 7, TableDriven: 4, Random: 1.7,
>>> compare_agents(TrivialVacuumEnvironment, agents, n=100, steps=4)
[(<ModelBasedVacuumAgent>, 8.5), (<ReflexVacuumAgent>, 6.4500000000000002), (<TableDrivenAgent>, 4.1699999999999999), (<RandomAgent>, 2.1299999999999999)]
>>> d = UniversalDict(42)
>>> d['life']
42
>>> len('abc')
3
>>> len(range(5))
5
>>> len(5)
# raises TypeError as expected
# You can also have statements and expressions without testing the result:
>>> print 3
3
>>> 2 + 1
3
# You can use _ if you need to do a more complex test on a result:
>>> 1./3.
0.33333333333333331
>>> 0.333 < _ < 0.334
1
# Or do this if you don't need to see the value of 1./3. printed:
>>> 0.3333 < 1./3. < 0.334
1
# Now we have a quandry. To show that Test() works, we need to try
# out failing tests. But we want the final result to be zero failures.
# So we can't put '2 + 2 ==> 5' here, but we can do this:
>>> t = Test([])
<Test: passed all 0>
>>> t.run_string('2 + 2 ='+'=> 5')
>>> 2 + 2
4
###### ERROR: expected 5 for 2 + 2
None
>>> t
<Test: #### failed 1, passed 0>
>>> t.failed
1
>>> t = Test([])
<Test: passed all 0>
>>> t.run_string('0 rai'+'ses ZeroDivisionError')
>>> 0
###### ERROR: expected ZeroDivisionError for 0
None
>>> t
<Test: #### failed 1, passed 0>
>>> t.failed
1
>>> DataSet(examples='1 2 3')
<DataSet(): 1 examples, 3 attributes>
>>> parse_csv('1 2 3 \n 0 2 na')
[[1, 2, 3], [0, 2, 'na']]
>>> parse_csv('1, 2, 3 \t 4, 5')
[[1, 2, '3 \t 4', 5]]
# More tests for Logic.
>>> A, B, C, P, Q = map(Expr, 'ABCPQ')
>>> pl_true(P, {})
None
>>> pl_true(P | Q, {'P': True})
1
# Notice that the function pl_true cannot reason by cases:
>>> pl_true(P | ~P)
None
# However, tt_entails (or equivalently, tt_true) can:
>>> tt_entails(TRUE, P | ~P)
1
>>> tt_true(P | ~P)
1
# The following are tautologies from [Fig. 7.11]:
>>> tt_true(A & B == B & A)
1
>>> tt_true(A | B == B | A)
1
>>> tt_true(((A & B) & C) == (A & (B & C)))
1
>>> tt_true(((A | B) | C) == (A | (B | C)))
1
>>> tt_true(~~A == A)
1
>>> tt_true((A >> B) == (~B >> ~A))
1
>>> tt_true((A >> B) == (~A | B))
1
>>> tt_true((A == B) == ((A >> B) & (B >> A)))
1
>>> tt_true(~(A & B) == (~A | ~B))
1
>>> tt_true(~(A | B) == (~A & ~B))
1
>>> tt_true((A & (B | C)) == ((A & B) | (A & C)))
1
>>> tt_true((A | (B & C)) == ((A | B) & (A | C)))
1
>>> expr('P & Q | ~R(x, F(x))')
((P & Q) | ~R(x, F(x)))
>>> tt_entails(expr('P & Q'), expr('Q'))
1
>>> b = Boggle()
>>> b.solve()
<Boggle: 118 words, 176 points>
>>> b.solve()
<Boggle: 59 words, 73 points>
>>> random_weighted_selection(range(10), 3, lambda x: x * x)
[0, 1, 5, 14, 30, 55, 91, 140, 204, 285]
[9, 6, 9]
<Test: passed all 110>