马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
求问,我写的最后一题动手题答案如下nums = [1, 1, 2, 1, 3, 2, 3, 2]
major1 = major2 = nums[0]
count1 = 0
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
# 统计阶段
p = nums.count(major1)
q = nums.count(major2)
if p > len(nums) / 3 and q > len(nums) / 3:
print("主要元素为",major1,"和",major2)
else:
print("无主要元素")
答案的代码如下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)
为什么我们两个的对抗阶段,major结果会不同
本帖最后由 jackz007 于 2024-4-10 21:47 编辑
第18行有错 应该改为: 使用集合可以简化代码: nums , c = [1, 1, 2, 1, 3, 2, 3, 2] , 0
for x in set(nums):
if nums . count(x) > len(nums) // 3 :
print(x)
c += 1
if c == 0:
print('无主要元素')
|