Checkio: Feed Pigeons

題目如下:

I start to feed one of the pigeons. A minute later two more fly by and a minute after that another 3. Then 4, and so on (Ex: 1+2+3+4+...). One portion of food lasts a pigeon for a minute, but in case there's not enough food for all the birds, the pigeons who arrived first ate first. Pigeons are hungry animals and eat without knowing when to stop. If I have N portions of bird feed, how many pigeons will be fed with at least one portion of wheat?

pigeons

Input: A quantity of portions wheat as a positive integer.

Output: The number of fed pigeons as an integer.

Example:

checkio(1)==1
checkio(2)==1
checkio(5)==3
checkio(10)==6

How it is used: This task illustrates how we can model various situations. Of course, the model has a limited approximation, but often-times we don't need a perfect model.

Precondition: 0 < N < 105.

我給出的代碼是這樣的:

def checkio(number):
    sum = 0
    i = 1
    p = 0
    while(sum < number):
        p = i*(i+1)/2
        sum = sum + p
        i = i +1
    #if the new coming pigeions eat none
    if (sum - number) >= i-1:
        #just return the number of pigeions last minute
        return (i - 2+1)*(i-2)/2
    else:
        return p - (sum - number)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(1) == 1, "1st example"
    assert checkio(2) == 1, "2nd example"
    assert checkio(5) == 3, "3rd example"
    assert checkio(10) == 6, "4th example"
Checkio上面clear類別中,最火的代碼如下:

"""Determine the number of (greedy) pigeons who will be fed."""
import itertools
 
def checkio(food):
    """Given a quantity of food, return the number of pigeons who will eat."""
    pigeons = 0
    for t in itertools.count(1):
        if pigeons + t > food:
            # The food will be consumed this time step.
            # All pigeons around last time were fed, and there is enough food
            # this time step to feed 'food' pigeons, so return the max of each.
            return max(pigeons, food)
        # Increase pigeons, decrease food.
        pigeons += t
        food -= pigeons
上面的過程用很簡潔的代碼模擬了鴿子喫東西的過程,很簡潔。其中用到了一個itertools的包,itertools.count(n)的功能是創建一個迭代器生成從n開始的連續整數。

之所以把這個例子貼在這裏,是爲了說明work的代碼和漂亮代碼之間的差距。Come on!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章