comparison python/example/slice.py @ 745:6194eec4e3b7

mv to example
author Jeff Hammel <k0scist@gmail.com>
date Sun, 28 Jun 2015 15:42:50 -0700
parents python/slice.py@de7bf9523e21
children
comparison
equal deleted inserted replaced
744:6667850817bf 745:6194eec4e3b7
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 slice a arbitrarily sized list
6 """
7
8 # imports
9 import argparse
10 import os
11 import subprocess
12 import sys
13
14 __all__ = ['slice', 'main', 'Parser']
15
16 def slice(container, n_chunks):
17 size = int(len(container)/(n_chunks-1))
18 retval = []
19 start = 0
20 for i in range(n_chunks-1):
21 retval.append(container[start:start+size])
22 start += size
23 retval.append(container[start:])
24 return retval
25
26 class Parser(argparse.ArgumentParser):
27 """CLI option parser"""
28 def __init__(self, **kwargs):
29 kwargs.setdefault('description', __doc__)
30 argparse.ArgumentParser.__init__(self, **kwargs)
31 self.add_argument('N', type=int,
32 help="number of chunks")
33 self.add_argument('-M', '--len', dest='length', type=int, default=29,
34 help="length of list [DEFAULT: %(default)s]")
35 self.options = None
36
37 def parse_args(self, *args, **kw):
38 options = argparse.ArgumentParser.parse_args(self, *args, **kw)
39 self.validate(options)
40 self.options = options
41 return options
42
43 def validate(self, options):
44 """validate options"""
45
46 def main(args=sys.argv[1:]):
47 """CLI"""
48
49 # parse command line options
50 parser = Parser()
51 options = parser.parse_args(args)
52
53 # generate list
54 seq = range(options.length)
55
56 # chunk list
57 output = slice(seq, options.N)
58
59 # print output
60 for chunk in output:
61 print (",".join([str(i) for i in chunk]))
62
63 if __name__ == '__main__':
64 main()
65