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(min))
[-99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 99]
>>> qtest(PriorityQueue(max))
[99, 8, 7, 6, 5, 4, 3, 2, 1, 0, -99]
>>> qtest(PriorityQueue(min, abs))
[0, 1, 2, 3, 4, 5, 6, 7, 8, -99, 99]
>>> qtest(PriorityQueue(max, abs))
[99, -99, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> 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)
>>> 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']
>>> caller(0)
'caller'
>>> def f(): return caller()
>>> f()
'f'
>>> 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
>>> 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]
>>> 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'
>>> s = set([1,2,3])
>>> 1 in s
1
>>> 4 in s
0
>>> s.add(4)
None
>>> 4 in s
1
>>> len(s)
4
>>> s.discard(999)
None
>>> s.remove(4)
None
>>> 4 in s
0
>>> s2 = set([3,4,5])
>>> s.union(s2)
None
>>> s.intersection(s2)
None
>>> set([1,2,3]) == set([3,2,1])
0
>>> repr(s) == '{1, 2, 3}'
1
>>> for e in s: pass
>>> 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
>>> 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 0x8297a44>
>>> 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 0x8297a7c>
>>> e.run(5)
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>, 0.0), (<ReflexVacuumAgent>, 0.0), (<TableDrivenAgent>, 0.0), (<RandomAgent>, 0.0)]
>>> 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
>>> g = Fig62Game()
>>> minimax_decision('A', g)
'a1'
>>> alphabeta_full_search('A', g)
'a1'
>>> alphabeta_search('A', g)
'a1'
>>> 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) | ~(x R Fx))
>>> tt_entails(expr('P & Q'), expr('Q'))
1
>>> Lexicon(Art = "the | a | an")
{'Art': ['the', 'a', 'an']}
>>> Rules(A = "B C | D E")
{'A': [['B', 'C'], ['D', 'E']]}
>>> random_weighted_selection(range(10), 3, lambda x: x * x)
[0, 1, 5, 14, 30, 55, 91, 140, 204, 285]
[5, 7, 8]
<Test: passed all 119>