-3

我正在尝试创建一个程序,该程序将创建一个 10 元素数组,然后为每个元素分配随机值。然后我希望程序判断阵列是否平衡。平衡我的意思是,数组值中是否存在在某个元素处元素中的值的总和等于大于当前元素的元素中的数组值的总和。

例子

元素 (1,2,3,4) 值 (2,1,3,0) 然后程序将显示元素 1-2 与元素 3-4 平衡,因为它们都等于 4。

到目前为止我有

import random

size = 10
mean = 0
lists = [0] * size
for i in range(size):
    var = random.randint(0,4)
    lists[i] = var

for i in lists:
    mean += i

avg = (mean)/(size)

我认为平衡元素的唯一方法是平均值等于 2,所以我认为这就是我应该开始的方式。

我将不胜感激在正确方向上的任何帮助。

4

2 回答 2

5

如果我理解这个问题,最简单的解决方案是这样的:

def balanced(numbers):
    for pivot in range(len(numbers)):
        left_total = sum(numbers[:pivot])
        right_total = sum(numbers[pivot:])
        if left_total == right_total:
            return pivot
    return None

例如:

>>> numbers = [2, 1, 3, 0]
>>> balanced(numbers)
2
>>> more_numbers = [2, 1, 3, 4]
>>> balanced(numbers)

(这没有打印任何东西,因为它返回了None,这意味着没有枢轴来平衡列表。)


虽然这是最简单的解决方案,但它显然不是最有效的,因为您不断地重复添加相同的数字。

如果您考虑一下,应该很容易弄清楚如何继续计算 and 的总计left_totalright_total只调用sum一次。

def balanced(numbers):
    left_total, right_total = 0, sum(numbers)
    for pivot, value in enumerate(numbers):
        if left_total == right_total:
            return pivot
        left_total += value
        right_total -= value
    return None

最后,这是围绕它构建程序的方法:

size = 10
numbers = [random.range(4) for _ in range(size)]
pivot = balanced(numbers)
if pivot is None:
    print('{} is not balanced'.format(numbers))
else:
    print('{} is balanced, because elements 1-{} equal {}-{}'.format(
        numbers, pivot+1, pivot+2, size+1))
于 2013-05-08T00:32:55.960 回答
0

对于此类问题,需要了解的一个很好的数据结构是具有累积和的数组。是原始系列中从到element[j] - element[i]的总和。如果你有原始系列,累积系列是。原始系列中位置的总和是。对于这个问题,我们只对从 0 开始的总和感兴趣,所以这有点矫枉过正,但同样对其他问题更有用。ij[1, 2, 3, 4][0, 1, 3, 6, 10]ielement[i] - element[0]

这是进行累积总和的代码:

def cumulative_sum(series):
    s = [0]
    for element in series:
        s.append(element + s[-1])
    return s

鉴于此,我们可以使用以下代码找到枢轴点:

def find_pivot(series):
    cs = cumulative_sum(series)
    total = cs[-1]
    even_total = not (total & 1)
    if even_total:
        target = total // 2
        for i, element in enumerate(cs[1:]):
            if element == target:
                return i + 1
    return -1

请注意,如果我们知道系列总和为奇数,则没有必要尝试除以系列:那么就不存在枢轴点。

或者,您可以find_pivot这样写:

def find_pivot(series):
    cs = cumulative_sum(series)
    total = cs[-1]
    even_total = not (total & 1)
    if even_total:
        target = total // 2
        try:
            return cs.index(target)
        except ValueError:
            return -1
    return -1

它的优点是循环不是在 python 中显式完成,而是在标准库的 C 代码中完成。

试用代码:

def test():
    for i in range(1, 30):
        test_values = range(i)
        j = find_pivot(test_values)
        if j >= 0:
            print "{0} == {1}".format(test_values[:j], test_values[j:])

我们得到这个输出:

[0] == []
[0, 1, 2] == [3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] == [15, 16, 17, 18, 19, 20]
于 2013-05-08T03:17:06.497 回答