我需要帮助的能力,把一个未知的整数分成一个给定数目的偶数部分-或至少,即使他们可以。部分的和应该是原始值,但是每个部分应该是一个整数,并且它们应该尽可能接近。
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.这就是我所拥有的
def split_integer(num,parts):
    if (num < parts):
      print(-1)
    elif (num % parts == 0):
      for i in range(parts):
        print(num // parts),
    else: 
      parts_remaining = parts - (num % parts)
      quotient = num // parts 
      for i in range(parts):
        if (i >= parts_remaining):
          print(quotient + 1),
        else:
          print(quotient),
split_integer(10, 1)这是样本测试
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])预期产出实例
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]我收到错误了
Failure
AssertionError: None != [10]发布于 2019-04-02 02:09:16
第一个问题是,您正在打印结果,而不是返回结果。默认情况下,在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发布于 2019-06-01 17:32:27
这个问题非常类似于“给予改变”的问题。
让我们从split(10, 1)最简单的场景开始,在这里您处理的分区大小为1,即parts = 1,一个直观的解决方案是:partition = [10]。当然,这假定remainder = 0和parts = 1 or 0。
如果这是基本情况的一般概念,那么可以通过递归的方式计算总分区,其中num和parts都被连续地缩减,如下所示:
def split_integer(num, parts):
    """
    split_integer(integer, parts) -> [ value[, values] ]
    divides an integer into an ""even as can be"" number of parts.
    >>> split_integer(10, 1)
    [10]
    >>> split_integer(2, 2)
    [1, 1]
    >>> split_integer(20, 5)
    [4, 4, 4, 4, 4]
    >>> split_integer(10, 5)
    [2, 2, 2, 2, 2]
    >>> split_integer(20, 6)
    [3, 3, 3, 3, 4, 4]
    >>> split_integer(5, 4)
    [1, 1, 1, 2]
    """
    lower_bound, remainder = divmod(num, parts)
    sub_partition = [lower_bound ] * (parts - remainder)
    num -= len(sub_partition) * lower_bound
    if remainder:
        sub_partition += split_integer(num, remainder)
    return sub_partition
if __name__ == "__main__":
    import doctest
    doctest.testmod()发布于 2019-10-13 05:35:35
或者简单地说,
In [1]: n,p=20,6                                                                
In [2]: c,r=divmod(n,p)                                                         
In [3]: [c]*(p-r) + [c+1]*r                                                     
Out[3]: [3, 3, 3, 3, 4, 4]https://stackoverflow.com/questions/55465884
复制相似问题