马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
nums = [1, 1, 2, 1, 3, 2, 3, 2]
major1 = major2 = nums[0]
count1 = count2 = 0
# 对抗阶段
for each in nums:
if major1 == each:
count1 += 1
continue
if major2 == each:
count2 += 1
continue
if count1 == 0:
major1 = each
count1 = 1
continue
if count2 == 0:
major2 = each
count2 = 1
continue
count1 -= 1
count2 -= 1
# 统计阶段
if nums.count(major1) > len(nums) / 3:
print(major1)
if nums.count(major2) > len(nums) / 3:
print(major2)
这里面,如何避免major1和major2相同的情况呢???
本帖最后由 傻眼貓咪 于 2022-1-22 09:23 编辑
试试这个: nums = [1, 1, 2, 1, 3, 2, 3, 2]
major1 = major2 = nums[0]
count1 = count2 = 0
for each in nums:
if count1 == 0:
major1 = each
elif each == major1:
count1 += 1
else:
count1 -= 1
if count2 == 0 and each != major1:
major2 = each
elif each == major2:
count2 += 1
else:
count2 -= 1
if nums.count(major1) > len(nums)/3:
print(major1)
if nums.count(major2) > len(nums)/3:
print(major2)
|