You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现:在含重复数值的vector中找重复最多的质数(禁用指定工具)

解决:找出列表中重复次数最多的质数

需求与限制

给定一个包含重复数值的列表,确定其中重复次数最多的质数;禁止使用Python内置sort函数,也不能用字典、集合和元组。

用户原代码(运行失败)

cd = int(input("enter the quantity of data: "))
v = []
vp = []
for i in range(cd):
    v.append(int(input("input an elment: ")))

for j in range(cd):
    m = 0
    for x in range(v[j]):
        if v[j] % x == 0:
            m += 1
    if m == 2:
        vp.append(v[j])

for k in range(len(vp)):
    for s in range(1,vp):
        if vp[k] == vp[s]:
            sp = sp + 1

原代码问题分析

  1. 质数判断逻辑错误:
    • range(v[j])会生成从0开始的序列,执行v[j] % 0会触发除以零错误;
    • 质数定义是大于1、仅能被1和自身整除的数,原代码未排除小于2的数,且计数逻辑不符合质数判断规则。
  2. 重复统计逻辑错误:
    • sp未初始化就直接累加;
    • range(1, vp)参数错误,vp是列表,range的第二个参数必须是整数;
    • 统计方式会重复计数,无法准确得到每个质数的出现次数。

修正后的代码

# 获取输入数据
count = int(input("请输入数据数量: "))
nums = []
for _ in range(count):
    nums.append(int(input("请输入一个元素: ")))

# 筛选所有质数
primes = []
for num in nums:
    # 小于2的数直接排除
    if num < 2:
        continue
    is_prime = True
    # 从2到num的平方根遍历,优化判断效率
    for x in range(2, int(num ** 0.5) + 1):
        if num % x == 0:
            is_prime = False
            break
    if is_prime:
        primes.append(num)

# 处理无质数的情况
if not primes:
    print("列表中没有质数")
else:
    max_count = 0
    most_freq_prime = primes[0]
    # 逐个统计每个质数的出现次数
    for i in range(len(primes)):
        current_num = primes[i]
        current_count = 0
        for j in range(len(primes)):
            if primes[j] == current_num:
                current_count += 1
        # 更新最大次数及对应质数
        if current_count > max_count:
            max_count = current_count
            most_freq_prime = current_num
        # 次数相同时,保留先出现的质数
        elif current_count == max_count:
            # 找到两个数的首次出现位置
            first_pos_current = 0
            while first_pos_current < len(primes) and primes[first_pos_current] != current_num:
                first_pos_current += 1
            first_pos_most = 0
            while first_pos_most < len(primes) and primes[first_pos_most] != most_freq_prime:
                first_pos_most += 1
            if first_pos_current < first_pos_most:
                most_freq_prime = current_num

    print(f"重复次数最多的质数是: {most_freq_prime},共出现{max_count}次")

关键说明

  • 质数判断优化:通过遍历到num的平方根减少循环次数,同时直接排除小于2的数,避免无效判断;
  • 次数统计方式:用双重循环逐个比较计数,不依赖字典等受限结构;
  • 边界处理:加入无质数时的提示,同时处理次数相同的情况(保留先出现的质数)。

内容的提问来源于stack exchange,提问作者SirMrpirateroberts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:43:38