Finding the closest number in a random set

前端 未结 6 1960
长情又很酷
长情又很酷 2021-01-01 05:23

Say I got a set of 10 random numbers between 0 and 100.

An operator gives me also a random number between 0 and 100. Then I got to find the number in the set that is

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 05:48

    python example:

    #!/usr/bin/env python
    import random
    from operator import itemgetter
    
    sample = random.sample(range(100), 10)
    pivot = random.randint(0, 100)
    
    print 'sample: ', sample
    print 'pivot:', pivot
    print 'closest:', sample[
        sorted(
            map(lambda i, e: (i, abs(e - pivot)), range(10), sample), 
            key=itemgetter(1)
        )[1][0]]
    
    # sample:  [61, 2, 3, 85, 15, 18, 19, 8, 66, 4]
    # pivot: 51
    # closest: 66
    

提交回复
热议问题