在列表中查找-1s,1s和0s的多数票 - python

时间:2015-11-03 23:43:59

标签: python list if-statement binary voting

如何找到包含-1s,1s和0s的列表的多数票?

例如,给出一个列表:

x = [-1, -1, -1, -1, 0]

多数为-1,因此输出应返回-1

另一个例子,给出一个列表:

x = [1, 1, 1, 0, 0, -1]

多数票将是1

当我们有平局时,多数投票应该返回0,例如:

x = [1, 1, 1, -1, -1, -1]

这也应该返回零:

x = [1, 1, 0, 0, -1, -1]

获得多数投票的最简单案例似乎是对列表进行求和,并检查它是否为负,正或0.

>>> x = [-1, -1, -1, -1, 0]
>>> sum(x) # So majority -> 0
-4
>>> x = [-1, 1, 1, 1, 0]
>>> sum(x) # So majority -> 1
2
>>> x = [-1, -1, 1, 1, 0]
>>> sum(x) # So majority is tied, i.e. -> 0
0

总和之后,我可以做这个检查以获得多数投票,即:

>>> x = [-1, 1, 1, 1, 0]
>>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0
>>> majority
1
>>> x = [-1, -1, 1, 1, 0]
>>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0
>>> majority
0

但如前所述,它很难看:Python putting an if-elif-else statement on one line而不是pythonic。

所以解决方案似乎是

>>> x = [-1, -1, 1, 1, 0]
>>> if sum(x) == 0:
...     majority = 0
... else:
...     majority = -1 if sum(x) < 0 else 1
... 
>>> majority
0

EDITED

但有些情况sum()不会起作用,@ RobertB&amp; s

>>> x = [-1, -1, 0, 0, 0, 0]
>>> sum(x) 
-2

但在这种情况下,多数投票应为0 !!

13 个答案:

答案 0 :(得分:10)

我假设0票作为票数。所以sum不是一个合理的选择。

尝试一个计数器:

>>> from collections import Counter
>>> x = Counter([-1,-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0])
>>> x
Counter({0: 8, 1: 4, -1: 3})
>>> x.most_common(1)
[(0, 8)]
>>> x.most_common(1)[0][0]
0

所以你可以写代码如下:

from collections import Counter

def find_majority(votes):
    vote_count = Counter(votes)
    top_two = vote_count.most_common(2)
    if len(top_two)>1 and top_two[0][1] == top_two[1][1]:
        # It is a tie
        return 0
    return top_two[0][0]

>>> find_majority([1,1,-1,-1,0]) # It is a tie
0
>>> find_majority([1,1,1,1, -1,-1,-1,0])
1
>>> find_majority([-1,-1,0,0,0]) # Votes for zero win
0
>>> find_majority(['a','a','b',]) # Totally not asked for, but would work
'a'

答案 1 :(得分:5)

如果您使用的是python&gt; = 3.4,则可以使用statistics.mode,当您没有唯一模式时,可以使用StatisticsError

from statistics import mode, StatisticsError

def majority(l):
    try:
        return mode(l)
    except StatisticsError:
        return 0

statistics实现本身使用Counter dict:

import  collections
def _counts(data):
    # Generate a table of sorted (value, frequency) pairs.
    table = collections.Counter(iter(data)).most_common()
    if not table:
        return table
    # Extract the values with the highest frequency.
    maxfreq = table[0][1]
    for i in range(1, len(table)):
        if table[i][1] != maxfreq:
            table = table[:i]
            break
    return table

def mode(data):
    """Return the most common data point from discrete or nominal data.

    ``mode`` assumes discrete data, and returns a single value. This is the
    standard treatment of the mode as commonly taught in schools:

    >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
    3

    This also works with nominal (non-numeric) data:

    >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
    'red'

    If there is not exactly one most common value, ``mode`` will raise
    StatisticsError.
    """
    # Generate a table of sorted (value, frequency) pairs.
    table = _counts(data)
    if len(table) == 1:
        return table[0][0]
    elif table:
        raise StatisticsError(
                'no unique mode; found %d equally common values' % len(table)
                )
    else:
        raise StatisticsError('no mode for empty data')

使用Counter并捕获空列表的另一种方法:

def majority(l):
    cn = Counter(l).most_common(2)
    return 0 if len(cn) > 1 and cn[0][1] == cn[1][1] else next(iter(cn),[0])[0]

答案 2 :(得分:1)

你可以count occurences为0并测试他们是否占多数。

>>> x = [1, 1, 0, 0, 0]
>>> if sum(x) == 0 or x.count(0) >= len(x) / 2.0:
...     majority = 0
... else:
...     majority = -1 if (sum(x) < 0) else 1
... majority
0

答案 3 :(得分:1)

此解决方案基于计算事件和排序:

import operator
def determineMajority(x):
    '''
    >>> determineMajority([-1, -1, -1, -1, 0])
    -1

    >>> determineMajority([1, 1, 1, 0, 0, -1])
    1

    >>> determineMajority([1, 1, 1, -1, -1, -1])
    0

    >>> determineMajority([1, 1, 1, 0, 0, 0])
    0

    >>> determineMajority([1, 1, 0, 0, -1, -1])
    0

    >>> determineMajority([-1, -1, 0, 0, 0, 0])
    0
    '''

    # Count three times
    # sort on counts
    xs = sorted(
        [(i, x.count(i)) for i in range(-1,2)],
        key=operator.itemgetter(1),
        reverse=True
    )

    if xs[0][1] > xs[1][1]:
        return xs[0][0]
    else:
        # tie
        return 0


if __name__ == '__main__':
    import doctest
    doctest.testmod()

此外,还有一个if语句。如评论中所述,未定义

会发生什么
  

x = [1,1,0,0,-1]

答案 4 :(得分:0)

from collections import Counter

result = Counter(votes).most_common(2)

result = 0 if result[0][1] == result[1][1] else result[0][0]

设置基数为1的空votes列表或votes列表的错误处理是微不足道的,并留给读者练习。

答案 5 :(得分:0)

我相信这适用于所有提供的测试用例。如果我做错了,请告诉我。

from collections import Counter

def fn(x):
    counts = Counter(x)
    num_n1 = counts.get(-1, 0)
    num_p1 = counts.get(1, 0)
    num_z = counts.get(0, 0)
    if num_n1 > num_p1:
        return -1 if num_n1 > num_z else 0
    elif num_p1 > num_n1:
        return 1 if num_p1 > num_z else 0
    else:
        return 0

答案 6 :(得分:0)

# These are your actual votes
votes = [-1, -1, -1, -1, 0]

# These are the options on the ballot
ballot = (-1, 0, 1)

# This is to initialize your counters
counters = {x: 0 for x in ballot}

# Count the number of votes
for vote in votes:
    counters[vote] += 1

results = counters.values().sort()

if len(set(values)) < len(ballot) and values[-1] == values [-2]:
    # Return 0 if there's a tie
    return 0
else:
    # Return your winning vote if there isn't a tie
    return max(counters, key=counters.get)

答案 7 :(得分:0)

这适用于任何数量的候选人。如果两个候选人之间存在平局,则返回零,否则返回的选票最多。

from collections import Counter
x = [-1, -1, 0, 0, 0, 0]
counts = list((Counter(x).most_common())) ## Array in descending order by votes
if len(counts)>1 and (counts[0][1] == counts[1][1]): ## Comparing top two candidates 
   print 0
else:
   print counts[0][0]

我们仅比较两位候选人,因为如果两位候选人之间存在平局,则应该返回0并且不依赖于第三候选人值

答案 8 :(得分:0)

A very simple approach.

a = [-1, -1, -1, -1, 0]   # Example
count = {}
for i in a:
    if i not in count:
        count[i] = 1
    else:
        count[i] += 1
m_count = max(count.values())
for key in count:
    if count[key] == m_count:
        print key

In the above example the output will be -1, however if there is a tie, both the keys will be printed.

答案 9 :(得分:0)

一种显而易见的方法是制作计数器并根据数据列表x进行更新。然后你可以得到最常见的数字列表(从-1,0,1)。如果有1个这样的数字,这就是你想要的,否则选择0(按照你的要求)。

counter = {-1: 0, 0: 0, 1: 0}
for number in x:
    counter[number] += 1
best_values = [i for i in (-1, 0, 1) if counter[i] == max(counter.values())]
if len(best_values) == 1:
    majority = best_values[0]
else:
    majority = 0

答案 10 :(得分:-1)

除了内置列表操作符和内容之外,您不需要任何其他内容,无需导入任何内容。

  votes = [ -1,-1,0,1,0,1,-1,-1] # note that we don't care about ordering

    counts = [ votes.count(-1),votes.count(0),votes.count(1)] 

    if (counts[0]>0 and counts.count(counts[0]) > 1) or (counts[1]>0 and counts.count(counts[1])>1):
         majority=0
    else:
         majority=counts.index(max(counts))-1 # subtract 1 as indexes start with 0

    print majority

3d line将相应投票的计数放入新列表中,counts.index()显示我们找到最多投票的列表位置。

我敢说,这应该尽可能地像pythonic一样,而不会陷入眼睛凿眼的oneliners。

更新:重写没有文本字符串并更新为在几个相同结果的情况下返回0(在原始帖子中没有注意到这一点),如果只有一个投票添加了IF案例,例如votes = [ - 1]

答案 11 :(得分:-1)

<div id="postMessage" style="height:30px;"></div>
    <div style="height:1500px;background:#333;"></div>
    <script src="jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
            var eventer = window[eventMethod];
            var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

            eventer(messageEvent,function(e) {
                var key = e.message ? "message" : "data";
                var data = e[key];

                window.scrollTo(0, data);
            },false);
        });
</script>

答案 12 :(得分:-2)

import numpy as np

def fn(vote):
   n=vote[np.where(vote<0)].size
   p=vote[np.where(vote>0)].size
   ret=np.sign(p-n)
   z=vote.size-p-n
   if z>=max(p,n):
      ret=0
   return ret

# some test cases
print fn(np.array([-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0]))
print fn(np.array([-1, -1, -1, 1,1,1,0,0]))
print fn(np.array([0,0,0,1,1,1]))
print fn(np.array([1,1,1,1, -1,-1,-1,0]))
print fn(np.array([-1, -1, -1, -1, 1, 0]))