import random,copy
for idx in range(20):
lst=
a=copy.deepcopy(lst)
b=list(set(lst))
z={}
for x in b:
z=round(a.count(x)/len(a)*100,2)
z_order=sorted(z.items(), key = lambda kv:(kv))
if float(z_order[-1])>50:
print(a,"相关数是{:4d}占比:{:.2f}".format(z_order[-1],z_order[-1]))
else:
print(a,"没有相关数") wp231957 发表于 2021-6-3 14:24
我自己造的原始数据一个过半的都没有
不错{:10_279:} 爱小师妹{:10_279:}{:10_279:} li = eval(input('请输入列表:'))
K = , 0]
for i in li:
if i == K:
K += 1
elif K == 0:
K = i
K = 1
else:
K -= 1
print(f'该列表的主要元素为{K}') if li.count(K) > len(li) / 2 else print('该列表无主要元素')
{:5_95:} 讲的太好了 .
{:10_254:} testlist =
count = 0
preelement = 0
for eachelement in testlist:
if count == 0:
preelement = eachelement
count += 1
elif count != 0:
if eachelement != preelement:
count -= 1
if eachelement == preelement:
count += 1
# 返回PK后的候选人preelement
# 重新开始计数,判断候选人preelement占比是否超过一半
count = 0
for eachelement in testlist:
if eachelement == preelement:
count += 1
if count > len(testlist)/2:
print('%s是列表中的主要元素' % preelement)
else:
print('没有占比超过一半的元素') 答案呢?
123 如果不用摩尔投票法的话,可以这样做吗?
nums =
new_nums = list(set(nums))
for i in new_nums:
if nums.count(i) > len(nums) / 2:
print(f"{i}是主要元素")
break
else:
print("不存在主要元素") 1
nums =
count = 0
major = 0
for each in nums:
if count == 0:
major = each
if each == major:
count += 1
else:
count -= 1
if nums.count(major) > len(nums)/2:
print('主要元素{}'.format(major))
else:
print('不存在主要元素') 沙发 学习一下下
页:
[1]