|
发表于 2022-5-6 22:10:40
|
显示全部楼层
# ********** 摩尔投票法进阶 **********
# 题干
# 现有列表:[1, 1, 2, 1, 3, 2, 3, 2],找出占比数量最多的两个元素,而且这两个元素的数量还需要超过总数的三分之一
testlist = [1, 1, 2, 1, 3, 2, 3, 2]
# testlist = [1, 1, 1, 1, 3, 2, 3, 2, 1]
# testlist = [1, 1, 1, 2, 2, 2, 3, 3, 3]
preelement1 = 0
preelement2 = 0
count1 = 0
count2 = 0
for each in testlist:
if count1 == 0:
preelement1 = each
count1 += 1
continue
if count2 == 0:
if each == preelement1:
count1 += 1
if each != preelement1:
preelement2 = each
count2 += 1
continue
elif count1 != 0 or count2 != 0:
if each == preelement1:
count1 += 1
continue
if each == preelement2:
count2 += 1
continue
if (each != preelement1) and (each != preelement2):
count1 -= 1
count2 -= 1
count1 = 0
count2 = 0
for each in testlist:
if each == preelement1:
count1 += 1
if each == preelement2:
count2 += 1
else:
pass
if (count1 > len(testlist)/3) and (count2 > len(testlist)/3):
print('该列表存在两个主要元素,分别是:%s,%s' % (preelement1, preelement2))
elif count1 > len(testlist)/2:
print('该列表仅存在一个主要元素为:%s' % preelement1)
elif count2 > len(testlist)/2:
print('该列表仅存在一个主要元素为:%s' % preelement2)
else:
print('该列表不存在主要元素!') |
|