中级农民
- 积分
- 111
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-11-7
- 最后登录
- 1970-1-1
|
本帖最后由 johnnywsd 于 2020-9-11 16:20 编辑
下面是这个的代码实现。 - # -*- coding: utf-8 -*-# -*- coding: utf-8 -*-"""
- 一个list a, 里面是每段绳子的长度,可以裁剪绳子,一个整数k, 表示最后需要的绳子根数,
- 求返回每根绳子可能的最长长度。e.g. a = [7, 2, 3, 4, 9], k = 5, 返回3
- """
- def cut_rope(arr, k):
- if not arr:
- if k != 0:
- return -1
- else:
- return
- min_len = min(arr)
- max_len = max(arr)
- # binary search
- l = min_len
- r = max_len
- while l + 1 < r:
- m = (l + r) / 2
- if lte_count(arr, m) >= k:
- l = m
- else:
- r = m
- if lte_count(arr, r) >= k:
- return r
- if lte_count(arr, l) >= k:
- return l
- return -1
- def lte_count(arr, limit):
- count = 0
- for it in arr:
- count += it // limit
- return count
- import unittest
- class Test(unittest.TestCase):
- def test_1(self):
- self.assertEqual(
- cut_rope([7, 2, 3, 4, 9], 5),
- 3
- )
- def test_2(self):
- self.assertEqual(
- cut_rope([7, 2, 3, 4, 9], 2),
- 7
- )
- def test_3(self):
- self.assertEqual(
- cut_rope([7, 2, 3, 4, 9], 6),
- 3
- )
- def test_4(self):
- self.assertEqual(
- cut_rope([7, 2, 3, 4, 9], 1),
- 9
- )
- def test_5(self):
- self.assertEqual(
- cut_rope([], 1),
- -1
- )
- if __name__ == '__main__':
- unittest.main(verbosity=2)
复制代码
|
|