The number of elements in the list that appears statistics

The number of elements in the list that appears statistics

Applications

Existing a list of numbers, the numbers to be calculated number is greater than half the length of the list appear in the list can be found after a return; (list when the number is odd, the number of list elements rounded up).

Ideas analysis

Core point above subject wherein the number of elements in the list of statistics, solving methods is to create a dictionary, the dictionary is the key element, the dictionary number corresponding to the key value of the element appears, as in the process of traversal of a key dictionary value is greater than half the length of the list, return the button corresponding dictionary.

Code

def MorelistLength(numbers):
    num_len = len(numbers) // 2
    d = {}
    max = 0

    for i in numbers:
        #当前字典d中没有i键时,插入元素
        if d.get(i) is None:
            d[i] = 1
        #当前字典d中有i键时,元素个数+1
        else:
            d[i] += 1
            
        if d[i] > max:
            max = d[i]
            
        if max > num_len:
            return i
    return None
print(MorelistLength([1,1,1,1,1,3,3,3,3,3,1,1]))

Results of the preceding code is as follows:

1

Case Promotion

Similarly, the case can also be extended to other types of list, as follows:

print(MorelistLength(['da','na','da','sa','da','da']))

执行结果如下:
da

print(MorelistLength([2,'na',2,'sa',2,2]))
执行结果如下:
2
Published 21 original articles · won praise 6 · views 7981

Guess you like

Origin blog.csdn.net/weixin_42128329/article/details/104628325
Recommended