Python random unique values from two non overlapping ranges -
as title says 100 random unique values 2 ranges or more accurate there 1 range , subrange excluded valid values.
example have range 0 10000, random 100 numbers not in range 10 20
requirements:
- the subrange can @ beginning or @ end.
- memory overhead absolute minimum.
- randomization close random.shuffle() possible.
i know random.sample(xrange(0,10000),100) gives 100 unique values.
setup store 3 values [start,end,total]
- start = start of subrange
- end = end of subrange
- total = length of range
best can come with:
randlist=[] while len(randlist)<100: temp=random.randint(0,total) if temp < start or temp > end: if temp not in randlist: randlist.append(temp)
is true random(pseudorandom) or affecting in way?
randlist = [r + (end - start + 1) * (r >= start) r in random.sample(range(total - end + start), 100)]
example / "proof":
- total=10, start=2, end=5
- there 7 allowed numbers: 0, 1, 6, 7, 8, 9, 10
- range(total-end+start) = range(7) picks 7 numbers 0..6 (so far good)
- numbers larger or equal start=2 shifted upwards end-start+1=4
- resulting numbers in 0, 1, 6, 7, 8, 9, 10.
demo:
>>> sorted(randlist2(2000000000, 10000000, 1900000000)) [176827, 3235435, 3278133, 3673989, 5148447, 8314140, 8885997, 1900189345, 1902880599, ... 1997494057, 1997538971, 1997854443, 1997907285]
this works until on 2 billion, beating required upper limit of "the number of wikipedia english wikipedia pages, whatever many million is" :-). after gets overflowerror: python int large convert c ssize_t
. see no spike in memory usage of pc , result instant. using python 3, obviously.
Comments
Post a Comment