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

如何确保按指定范围n生成包含n个无重复元素的数组?

解决数组添加n个无重复元素的问题

需求说明

根据给定的范围n,向数组中添加无重复元素;当输入重复元素时需重新输入,最终确保数组包含n个无重复元素。

原代码及问题

原代码尝试通过for循环实现,但遇到重复元素时会跳过添加操作,导致最终数组元素数量不足n:

"""
Trying to add elements in a array without any duplicates(as per a given range n). 
As soon as a dup no comes up, i can add only upto n-1 range while avoiding the dup element entered. 

"""

arr = []
a = int(input('Enter a range: '))

for i in range(a):
    i = int(input())
    if i in arr:
        print('its a dupl,enter another')
        continue
    else:
        arr.append(i)
        
print(arr)

运行示例(问题表现)

Enter a range: 6
1
2
3
8
9
1 ---> 'the dup ele'
its a dupl,enter another
[1, 2, 3, 8, 9]----> can only enter 5(ie n-1 range)

问题原因

原代码使用for i in range(a)的固定次数循环,每一次循环不管是否成功添加元素,都会消耗一次计数。当输入重复元素时,continue跳过了append操作,但循环次数已经用掉了一次,最终数组的元素数量就会少于n。

修复方案

改用while循环,以数组长度是否达到n作为循环终止条件,这样只要数组元素不足n,就会一直请求输入,直到成功添加一个无重复的元素:

arr = []
target_count = int(input('Enter a range: '))

while len(arr) < target_count:
    num = int(input())
    if num in arr:
        print('its a dupl,enter another')
    else:
        arr.append(num)
        
print(arr)

测试示例(正确运行)

Enter a range: 6
1
2
3
8
9
1
its a dupl,enter another
10
[1, 2, 3, 8, 9, 10]

这样就能确保最终数组刚好包含n个无重复元素,不管中途输入多少次重复值,都会一直要求重新输入,直到凑够数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:20:57