OILS / mycpp / examples / cartesian.py View on Github | oilshell.org

78 lines, 41 significant
1#!/usr/bin/env python2
2"""
3cartesian.py: Test lists of strings!
4"""
5from __future__ import print_function
6
7import os
8
9from typing import List
10from mycpp import mylib
11from mycpp.mylib import log
12
13# Operations:
14# - list literals
15# - list indexing dims[0]
16# - list slicing dims[1:]
17# - list append
18# - length of list
19# - iteration over characters in a string
20# - iteration over list
21# - recursive function calls
22# - string concatenation with +
23
24
25def Cartesian(dims, out):
26 # type: (List[str], List[str]) -> None
27 if len(dims) == 1:
28 for ch in dims[0]:
29 out.append(ch)
30 else:
31 rest = [] # type: List[str]
32 Cartesian(dims[1:], rest)
33 for ch in dims[0]:
34 for r in rest:
35 out.append(ch + r) # join strings
36
37
38def run_tests():
39 # type: () -> None
40 out = [] # type: List[str]
41
42 #Cartesian(['ab'], out)
43 tmp = ['ab']
44 Cartesian(tmp, out)
45
46 for s in out:
47 print(s)
48
49 print('--')
50
51 out = []
52
53 #Cartesian(['ab', '-|_', 'ABC'], out)
54 # Do we need a tmp variable?
55 tmp2 = ['ab', '-|_', 'ABC']
56 Cartesian(tmp2, out)
57 for s in out:
58 print(s)
59
60
61def run_benchmarks():
62 # type: () -> None
63 i = 0
64 n = 100000
65 while i < n:
66 out = [] # type: List[str]
67 Cartesian(['ab', '-|_', 'ABC'], out)
68 i = i + 1
69
70 mylib.MaybeCollect() # manual GC point
71
72
73if __name__ == '__main__':
74 if os.getenv('BENCHMARK'):
75 log('Benchmarking...')
76 run_benchmarks()
77 else:
78 run_tests()