Generating evenly distributed multiples/samples within a range

前端 未结 5 1720
说谎
说谎 2020-12-21 05:47

Specific instance of Problem
I have an int range from 1-100. I want to generate n total numbers within this range that are as evenly distributed

5条回答
  •  不思量自难忘°
    2020-12-21 06:20

    >>> from itertools import count
    >>> def steps(start,end,n):
            yield start
            begin = start if start>1 else 0
            c = count(begin,(end-begin)/(n-1))
            next(c)
            for _ in range(n-2):
                yield next(c)
            yield end
    
    
    >>> list(steps(1,100,2))
    [1, 100]
    >>> list(steps(1,100,5))
    [1, 25, 50, 75, 100]
    >>> list(steps(1,100,4))
    [1, 33, 66, 100]
    >>> list(steps(50,100,3))
    [50, 75, 100]
    >>> list(steps(10,100,10))
    [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    

    Can be shortened to

    >>> from itertools import islice, count
    >>> def steps(start,end,n):
            yield start
            begin = start if start>1 else 0
            c = islice(count(begin,(end-begin)/(n-1)),1,None)
            for _ in range(n-2):
                yield next(c)
            yield end
    

提交回复
热议问题