Python 中的分组整数
pythonserver side programmingprogramming更新于 2025/12/26 10:20:17
假设我们有一个名为 nums 的数字列表,我们必须检查是否可以将该列表拆分为 1 个或多个组,以便:1. 每个组的大小大于或等于 2。2. 所有组的大小相同。 3. 每个组中存在的所有数字都是相同的。
因此,如果输入为 [3, 4, 6, 9, 4, 3, 6, 9],则输出将为 True。
为了解决这个问题,我们将遵循以下步骤 −
- counts := 一个映射,其中每个键都是不同的元素,值是它们的频率
- temp := 0
- 对于 counts 中的每个计数,执行
- 如果 temp 与 0 相同,则
- temp := counts[count]
- 否则,
- temp := counts[count] 和 temp 的 gcd
- 如果 temp 与1、然后
- 返回 False
- 如果 temp 与 0 相同,则
- 返回 True
让我们看看下面的实现以便更好地理解 −
示例
from collections import Counter import math class Solution: def solve(self, nums): counts = Counter(nums) temp = 0 for count in counts: if temp == 0: temp = counts[count] else: temp = math.gcd(counts[count], temp) if temp == 1: return False return True ob = Solution() L = [3, 4, 6, 9, 4, 3, 6, 9] print(ob.solve(L))
输入
[3, 4, 6, 9, 4, 3, 6, 9]
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

