我正在嘗試在 python 中創建一個函式,它可以計算最有效的打包專案的方法。大包裝可容納 25 件物品,小包裝可容納 5 件物品。
def packages_needed (items, large_pack, small_pack)
我真的很糾結如何定義/設定推理
我在想的是建立一個條件,其中 x/a 是一個整數,然后 z 就是那個。如果余數不為 0,則 z 為整數加余數。
我不確定我的推理是否有意義,但我非常感謝任何建議/幫助。
到目前為止我所擁有的是:
z = 0
x = large_pack
y= small_pack
for a in items:```
uj5u.com熱心網友回復:
您可以使用標準的磁區運算子 (//) 來確定物品數量適合大小包裝的次數。
def division_ceiling(a: int, b: int) -> int:
"""
Accepts number of items. Returns how many small packs are needed.
"""
return -1 * (-a // b)
def packages_needed(items: int) -> (int, int):
"""
Accepts number of items. Returns tuple (large pack, small pack)
"""
large_size = 25
small_size = 5
large_packs = items // large_size
small_packs = division_ceiling(items - large_packs * large_size, small_size)
return (large_packs, small_packs)
"""
if you want 1-25 items to be 1 large pack then do this:
if items <= 25:
return (1, 0)
else:
large_packs = items // large_size
small_packs = division_ceiling(items - large_packs * large_size, small_size)
return (large_packs, small_packs)
"""
print(packages_needed(int(input("Number of items?"))))
Input: 31
Output: (1, 2)
Input: 6
Output: (0, 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477047.html
標籤:Python python-3.x
上一篇:如何解決錯誤“IndexError:串列索引超出范圍”
下一篇:如何對圖的路徑進行排序
