代码之家  ›  专栏  ›  技术社区  ›  anonymous coward

对于任意数量的项,返回最小X(可以包含Y项)

  •  1
  • anonymous coward  · 技术社区  · 14 年前

    现在感觉大脑已经死了。 当然,我可以,蛮力的,但我觉得有 是返回这个数字的简单函数。关于本机函数,我使用的是PHP和/或Python。

    例如:存在保存的容器 X (5)每个面包条,以及 我需要进食 Y

    6 回复  |  直到 14 年前
        1
  •  1
  •   John Machin Santi    14 年前

    //

    number_required = y * z
    container_holds = x
    reqd_containers = (number_required + container_holds - 1) // container_holds
    

    n=(y*z+(x-1))//x;
    

    n=(y*z+x-1)//x
    

    10 / 3 -> 3 10 / 3 -> 3.3333333333333335

    # wrong in Python 3; works with Python 2.3 to 2.7
    # int overflow with Pythons up to 2.2
    >>> int((100000000000000000 + 2)/3)
    33333333333333332 # last digit should be 4
    
    # wrong with Python 2.3 onwards; int overflow with earlier versions
    >>> import math
    >>> int(math.ceil(float(100000000000000000) / 3))
    33333333333333332L
    
        2
  •  3
  •   JoshD    14 年前

    min_containers = y*z/x
    

    min_full_containers = floor(y*z/x)
    remaining_items = y*z%x
    
        3
  •  2
  •   Dingo    14 年前
    def f(X, Y, Z):
      d, r = divmod(Y * Z, X)
      return d + bool(r)
    
        4
  •  1
  •   Ned Batchelder    14 年前
    #python
    import math
    
    int(math.ceil(float(Y) * Z / X))
    
        5
  •  1
  •   John Machin Santi    14 年前

    内德的回答是正确的。通过执行以下操作,还可以避免对math.ceil()的函数调用开销:

    minContainers = int((y*z+(x-1))/x);
    
        6
  •  -1
  •   GordonM    14 年前

    ($people*$breadsticksperson)/$holders不正确?

    编辑:抱歉,误读了您的问题,在评论中发布了正确的解决方案