开发者

Return minimum X (that can contain Y items) for arbitrary number of items

Feeling pretty brain-dead right now. I can, of course, brute-force this, but I feel like there has to be a simple function to return this number. Concerning native functions, I'm using PHP and/or Python.

For example: there exists containers that hold X (5) 开发者_StackOverflowbreadsticks each, and I need to feed Y (25) people Z (3) breadsticks each.

I need to return the number of containers I have to acquire to feed these people. (There may or may not be remainder breadsticks).

EDIT: Clarified some intention.


It sounds like you want arithmetic:

min_containers = y*z/x

If you have situations that may give a remainder:

min_full_containers = floor(y*z/x)
remaining_items = y*z%x


def f(X, Y, Z):
  d, r = divmod(Y * Z, X)
  return d + bool(r)


In Python, use // (integer floor division, introduced in Python 2.2) and force it to round up:

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

or if you require the so-called "professional programmer" version instead of the explanatory version:

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

or if you are really afraid of carpal tunnel syndrome, chop the two redundant parentheses and the semicolon:

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

Note: this solution works on both Python 2 (where 10 / 3 -> 3) and Python 3 (where 10 / 3 -> 3.3333333333333335)

Other "solutions" not only use unnecessary function calls but also fail with large numbers:

# 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


#python
import math

int(math.ceil(float(Y) * Z / X))


Ned's answer is correct. It is also common to avoid the function call overhead to math.ceil() by doing the following:

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


($people * $breadSticksPerPerson) / $holders isn't correct?

EDIT: Sorry, misread your question, posted the correct solution in comments

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜