Getting the endpoints of sets across a range
For th开发者_开发技巧e life of me, I can't see how to do this. I need to collect the non-overlapping endpoints of several sets within a range of numbers with python.
For example the user could input a range of 10
and two sets 2
and 3
. I need to get the end points of these sets within this range such that:
set 2 groupings: 1-2,6-7
set 3 groupings: 3-5,8-10
The range, number of sets, and size of any individual set is arbitrary. I cannot fall outside the range, so no half sets.
I keep thinking there should be a simple formula for this, but I can't come up with it.
Edit
As requested for an example input of range 12, and sets 1, 2, and 3 the output should be:
set 1: 1,7
set 2: 2-3,8-9
set 3: 4-6,10-12
As near as I can figure, I'm looking at some kind of accumulator pattern. Something like this psuedo code:
for each miniRange in range:
for each set in sets:
listOfCurrSetEndpoints.append((start, end))
I don't think there's a good built-in solution to this. (It would be easier if there were a built-in equivalent to Haskell's scan
function.) But this is concise enough:
>>> import itertools
>>> from collections import defaultdict
>>> partition_lengths = [1, 2, 3]
>>> range_start = 1
>>> range_end = 12
>>> endpoints = defaultdict(list)
>>> for p_len in itertools.cycle(partition_lengths):
... end = range_start + p_len - 1
... if end > range_end: break
... endpoints[p_len].append((range_start, end))
... range_start += p_len
...
>>> endpoints
defaultdict(<type 'list'>, {1: [(1, 1), (7, 7)], 2: [(2, 3), (8, 9)], 3: [(4, 6), (10, 12)]})
You can now format the endpoints
dictionary for output however you like.
As an aside, I'm really confused by your use of "set" in this question, which is why I used "partition" instead.
I'm not exactly happy with it, but I did get a working program. If someone can come up with a better answer, I'll be happy to accept it instead.
import argparse, sys
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Take a number of pages, and the pages in several sets, to produce an output for copy and paste into the print file downloader', version='%(prog)s 2.0')
parser.add_argument('pages', type=int, help='Total number of pages to break into sets')
parser.add_argument('stapleset', nargs='+', type=int, help='number of pages in each set')
args = parser.parse_args()
data = {}
for c,s in enumerate(args.stapleset):
data[c] = []
currPage = 0
while currPage <= args.pages:
for c,s in enumerate(args.stapleset):
if currPage + 1 > args.pages:
pass
elif currPage + s > args.pages:
data[c].append((currPage+1,args.pages))
else:
data[c].append((currPage+1,currPage+s))
currPage = currPage + s
for key in sorted(data.iterkeys()):
for c,t in enumerate(data[key]):
if c > 0:
sys.stdout.write(",")
sys.stdout.write("{0}-{1}".format(t[0],t[1]))
sys.stdout.write("\n\n")
精彩评论