简体   繁体   English

在list-python中找到-1s,1s和0s的多数票

[英]Finding majority votes on -1s, 1s and 0s in list - python

How to find the majority votes for a list that can contain -1s, 1s and 0s? 如何找到包含-1s,1s和0s的列表的多数票?

For example, given a list of: 例如,给出一个列表:

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

The majority is -1 , so the output should return -1 大多数是-1,因此输出应返回-1

Another example, given a list of: 另一个例子,给出一个列表:

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

The majority vote would be 1 多数票数为1

And when we have a tie, the majority vote should return 0, eg: 当我们有平局时,多数投票应该返回0,例如:

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

This should also return zero: 这也应该返回零:

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

The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. 获得多数投票的最简单案例似乎是将列表加起来并检查它是否为负数,正数或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

After the sum, I could do this check to get the majority vote, ie: 总结之后,我可以做这个检查以获得多数投票,即:

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

But as noted previously, it's ugly: Python putting an if-elif-else statement on one line and not pythonic. 但如前所述,它很丑陋: Python将if-elif-else语句放在一行而不是pythonic。

So the solution seems to be 所以解决方案似乎是

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

EDITED EDITED

But there are cases that sum() won't work, @RobertB's eg 但是有些情况下sum()不起作用,@ RobertB就是这样

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

But in this case the majority vote should be 0!! 但在这种情况下,多数票应为0 !!

I am assuming that votes for 0 count as votes. 我假设0票作为票数。 So sum is not a reasonable option. 所以sum不是一个合理的选择。

Try a Counter: 尝试一个柜台:

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

So you could write code like: 所以你可以编写如下代码:

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'

You could use statistics.mode if you were using python >= 3.4 ,catching a StatisticsError for when you have no unique mode: 如果使用python> = 3.4,则可以使用statistics.mode ,当没有唯一模式时捕获StatisticsError

from statistics import mode, StatisticsError

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

The statistics implementation itself uses a Counter dict: 统计实现本身使用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')

Another way using a Counter and catching an empty list: 另一种使用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]

You can count occurences of 0 and test if they are majority. 您可以计算 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

This solution is based on counting occurrences and sorting: 此解决方案基于计数事件和排序:

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

Additionally, there is one if statements. 此外,还有一个if语句。 As mentioned in the comments it is undefined what happens with 正如评论中所提到的那样,未定义会发生什么

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

from collections import Counter

result = Counter(votes).most_common(2)

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

Error handling for empty votes lists or votes lists with a set cardinality of 1 is trivial and left as an exercise for the reader. 错误处理的空白votes名单或votes名单有1一组基数是琐碎而作为练习留给读者。

I believe this works for all provided test cases. 我相信这适用于所有提供的测试用例。 Please let me know if I did something wrong. 如果我做错了,请告诉我。

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

This works with any number of candidates. 这适用于任何数量的候选人。 If there is a tie between two candidates it returns zero else it returns candidate with most votes. 如果两个候选人之间存在平局,则返回零,否则返回最多投票的候选人。

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]

We compare only two candidates because if there is a tie between two candidates it should return 0 and it doesn't depend on third candidate value 我们仅比较两个候选者,因为如果两个候选者之间存在关联,则它应该返回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. 在上面的示例中,输出将为-1,但是如果存在平局,则将打印两个键。

An obvious approach is making a counter and updating it according to the data list x . 一种显而易见的方法是制作计数器并根据数据列表x更新。 Then you can get the list of numbers (from -1, 0, 1) that are the most frequent. 然后你可以得到最常见的数字列表(从-1,0,1)。 If there is 1 such number, this is what you want, otherwise choose 0 (as you requested). 如果有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

You don't need anything but built-in list operators and stuff, no need to import anything. 你不需要任何内置的列表操作符和东西,不需要导入任何东西。

  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 puts counts of respective votes in a new list, and counts.index() shows us which list position we find the max votes. 3d line将相应投票的计数放入新列表中,counts.index()向我们显示我们找到最大投票的列表位置。

I would dare to say that this should be about as pythonic as it can, without getting into eye-gouging oneliners. 我敢说这应该是尽可能的pythonic,而不是进入眼睛刨眼的oneliners。

Upd: rewrote without text strings and updated to return 0 in case of several equal results (didnt notice this in the original post), added an IF for case if only one vote, eg votes=[-1] 更新:重写没有文本字符串并更新为在几个相同结果的情况下返回0(在原始帖子中没有注意到这一点),如果只有一个投票,例如投票= [ - 1],则为案例添加IF

from collections import Counter

def find_majority_vote(votes):
  counter = Counter(votes)
  most_common = counter.most_common(2)
  if len(most_common)==2:
    return 0 if most_common[0][1] == most_common[1][1] else most_common[0][0]
  else:
    return most_common[0][0]
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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM