首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最大化列表中相等元素个数的Python算法

最大化列表中相等元素个数的Python算法
EN

Stack Overflow用户
提问于 2014-12-17 04:10:24
回答 4查看 1.1K关注 0票数 1

我正在尝试用Python编写一个算法,它将获取一个从0到1,000,000的随机数列表,长度不超过100个元素,并将尽可能多地将此数组平均,以获得相等元素的最大数量。这就是我到目前为止所知道的:

代码语言:javascript
复制
def answer(x):
    diff = max(x) - min(x)
    while diff > 1:
        x[x.index(max(x))] = x[x.index(max(x))] - (diff / 2)
        x[x.index(min(x))] = x[x.index(min(x))] + (diff / 2)
        diff = max(x) - min(x)
    return count(x)

def count(x):
    from collections import Counter
    c = Counter(x)
    return max(c.values())

这将采用一个数组,例如0,50,并创建一个数组25,25并返回整数2,因为该数组中有两个相等的元素。我知道一个事实,这个算法在大多数情况下都有效,但它在所有情况下都不起作用。谁能指出任何整数数组,这不会产生正确的答案?谢谢

编辑:

对于那些不想阅读while循环的人来说,代码可以找到整个列表的范围。将范围一分为二,并将一半加到最小值上,然后从最大值中减去一半。它试图在保持相同总和的同时使整个列表相等

1,4,1 = 2,3,1 = 2,2,2 =(相等元素数) 3 2,1,4,9 = 2,5,4,5 = 3,4,4,5 =4,4,4,5= 4,4,4,4 =(相等元素数)4

EN

回答 4

Stack Overflow用户

发布于 2014-12-17 04:54:32

那这个呢?

代码语言:javascript
复制
l = [1, 2, 5, 10]

# "best" possible case
l_m = [sum(l) / len(l)] * len(l)

# see if lists fit (division can cause rounding errors)

if sum(l_m) != sum(l):
    # if they don't this means we can only have len(l) - 1 similar items
    print len(l) - 1
else:
    # if sums fit the first list can be spread like this
    print len(l)
票数 4
EN

Stack Overflow用户

发布于 2014-12-17 04:51:25

我可以想象,您正在尝试使数组中尽可能多的元素相等,同时保持它们的总和,并保持元素的整数。

对于N元素,您可以获得相等的N - 1元素,幸运的是,所有N元素都相等。

这是给你的一段伪代码:

代码语言:javascript
复制
average = sum(elements) / length(elements)  # a float
best_approximation = trunc(average)  # round() would also work
discrepancy = sum(elements) - best_approximation * length(elements)
discrepant_value = best_approximation + discrepancy
result = [discrepant_value] + the rest of list having best_approximation value

通过构造,您可以获得相等值的length(elements) - 1和一个discrepant_value

票数 1
EN

Stack Overflow用户

发布于 2014-12-17 05:16:35

您真正要做的是将输入归一化为整数平均值,并将剩余部分分配到结果中。

代码语言:javascript
复制
L = [1,2,3,4,5,7]

# Calc the integer average
avg = sum(L)/len(L)

# Find the remainder
mod = sum(L)%len(L)

# Create a new list length of original
# populating it first with the average
L2 = [avg] * len(L)

# Then add 1 to each element for as many
# as the remainder
for n in range(mod): L2[n] += 1

def count(x):
    from collections import Counter
    c = Counter(x)
    return max(c.values())
count(L2)
4

你不需要修改原始列表或者创建一个新的列表(不需要你的import):

代码语言:javascript
复制
L = [1,2,3,4,5,7]

# Don't even need to figure the average if you
# find the remainder of the sum of your list
# divided by the length of your list
mod = sum(L)%len(L)

result = mod if mod >= len(L)/2 else len(L) - mod
print result
4
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27513055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档