如何使用 Python 将未知整数分成给定数量的偶数部分

Dan*_*eno 2 python python-2.7

我需要帮助才能将一个未知整数分成给定数量的偶数部分——或者至少尽可能均匀。各部分之和应为原始值,但各部分应为整数,且应尽可能接近。

Parameters
num: Integer - The number that should be split into equal parts

parts: Integer - The number of parts that the number should be split 
into

Return Value
List (of Integers) - A list of parts, with each index representing the part and the number contained within it representing the size of the part. The parts will be ordered from smallest to largest.
Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的

Parameters
num: Integer - The number that should be split into equal parts

parts: Integer - The number of parts that the number should be split 
into

Return Value
List (of Integers) - A list of parts, with each index representing the part and the number contained within it representing the size of the part. The parts will be ordered from smallest to largest.
Run Code Online (Sandbox Code Playgroud)

这是样本测试

import unittest

class Test(unittest.TestCase):
    def test_should_handle_evenly_distributed_cases(self):
        self.assertEqual(split_integer(10, 1), [10])
        self.assertEqual(split_integer(2, 2), [1,1])
        self.assertEqual(split_integer(20, 5), [4,4,4,4,4])
Run Code Online (Sandbox Code Playgroud)

预期输出示例

num parts   Return Value
Completely even parts example   10  5   [2,2,2,2,2]
Even as can be parts example    20  6   [3,3,3,3,4,4]
Run Code Online (Sandbox Code Playgroud)

我收到错误

Failure
AssertionError: None != [10]
Run Code Online (Sandbox Code Playgroud)

gmd*_*mds 5

第一个问题是您正在打印结果而不是返回它们。默认情况下,在 Python 中,任何未显式返回任何内容的函数都将返回None.

无论如何,有一种更简洁的方式,使用推导式:

def split_integer(num, parts):
    quotient, remainder = divmod(num, parts)
    lower_elements = [quotient for i in range(parts - remainder)]
    higher_elements = [quotient + 1 for j in range(remainder)]
    return lower_elements + higher_elements
Run Code Online (Sandbox Code Playgroud)