Python程式:計算可容納所有朋友的巴士大小
假設有n個學生組在等待乘坐學院校車回家。每個學生組有m個學生。學生組希望一起乘坐校車,不分開。他們只有在他們小組的所有成員都能上車的情況下才上車。此外,如果他們之前的小組尚未上車或已到達目的地,則該小組不上車。如果我們已知小組的數量和每個小組的學生數量,我們需要找出校車的大小,以便校車能夠運送所有小組,並且每次校車從學院出發時都沒有空位。
所以,如果輸入類似於組數 gr_no = [3, 4, 2, 2, 1, 4, 3, 5],則輸出將是 [12, 24]。
如果校車大小為12,它可以在第一次行程中容納1-5組,在第二次行程中容納其餘小組。
如果校車大小為24,它可以容納所有小組並在一次行程中運送它們。
為了解決這個問題,我們將遵循以下步驟:
- 定義一個函式 factor_ret()。它將接收n。
- 對於 i in range (0 到 n ^ 0.5),執行:
- 如果 n mod i 等於 0,則:
- 將一個元組 (i, floor(n/i)) 新增到 output_list 中。
- 如果 n mod i 等於 0,則:
- 對列表 output_list 進行排序。
- 返回 output_list 作為集合。
- 對於 i in range (0 到 n ^ 0.5),執行:
- 現在執行以下步驟:
- total := 一個包含專案 gr_no[0] 的新列表。
- 對於 i in range 1 到 gr_no 的大小,執行:
- 在 total 的末尾插入 total[i - 1] + gr_no[i]。
- b_sizes := 一個新列表。
- 對於 factor_ret(gr_no 列表的總和) 中的每個大小,執行:
- temp_list := 從 total 中所有非零元素生成的新列表。
- index := 1
- indicator := True
- 對於 temp_list 中的每個點,執行:
- 如果點不等於 size * index,則:
- indicator := False
- 跳出迴圈。
- index := index + 1
- 如果點不等於 size * index,則:
- 如果 indicator 為 True,則:
- 在 b_sizes 的末尾插入 size。
- 返回 b_sizes。
示例
讓我們看看下面的實現以更好地理解:
from functools import reduce def solve(gr_no): total = [gr_no[0]] for i in range(1, len(gr_no)): total.append(total[i - 1] + gr_no[i]) b_sizes = [] for size in factor_ret(sum(gr_no)): temp_list = list(filter(lambda x : x % size == 0, total)) index = 1 indicator = True for point in temp_list: if point != size * index: indicator = False break index += 1 if indicator: b_sizes.append(size) return b_sizes def factor_ret(n): return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) print(solve([3, 4, 2, 2, 1, 4, 3, 5]))
輸入
[3, 4, 2, 2, 1, 4, 3, 5]
輸出
[12, 24]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP