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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值