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

时间:2019-04-02 01:58:32

标签: 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.

这就是我所拥有的

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]

3 个答案:

答案 0 :(得分:2)

第一个问题是您要打印结果而不是返回结果。默认情况下,在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

答案 1 :(得分:0)

此问题与“给予更改”问题非常相似。

让我们首先看一下split(10, 1)的最简单情况,其中您要处理的分区大小为1,即parts = 1,一个直观的解决方案是:partition = [10]。当然,这是假设remainder = 0parts = 1 or 0

如果这是基本情况的一般概念,则可以通过递归的方式来计算总分区,其中numparts都会不断减少,如下所示:

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()

答案 2 :(得分:0)

或者简单地

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]