K = [, 0],, 0]]
for i in li:
if i == K:
K += 1
elif i == K:
K += 1
elif K == 0:
K = i
K = 1
elif K == 0:
K = i
K = 1
else:
K -= 1
K -= 1
if li.count(K) > len(li) / 3 and li.count(K) > len(li) / 3:
print(f'列表中出现次数超过1/3的元素为{K},{K}')
elif li.count(K) > len(li) / 3:
print(f'列表中出现次数超过1/3的元素为{K}')
elif li.count(K) > len(li) / 3:
print(f'列表中出现次数超过1/3的元素为{K}')
else:
print(f'列表中没有出现次数超过1/3的元素')
zhangyuesd 发表于 2021-6-23 16:09
li = eval(input('请输入列表:'))
K = [, 0],, 0]]
for i in li:
不错! 用桶排序可以最简化吧{:10_266:} 看看 本帖最后由 与森逐鹿 于 2022-2-12 20:04 编辑
list =
count = 0
major = 0
for i in list:
if count == 0:
major = i
count += 1
elif i == major:
count += 1
else:
count -= 1
if count == 0 or (list.count(major)<= (len(list)/2)):
print("没有那个数字")
else:
print("那个数字是{}".format(major)) 请女神解惑 # ********** 摩尔投票法进阶 **********
# 题干
# 现有列表:,找出占比数量最多的两个元素,而且这两个元素的数量还需要超过总数的三分之一
testlist =
# testlist =
# testlist =
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('该列表不存在主要元素!') 鱼C有你更精彩^_^ 沙发 {:5_103:} 学习一下下
页:
[1]