题目如下:
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?
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!