判断重复数字,不使用集合和字典

随机产生2组各10个数字的列表,要求

取值范围[10,20],

统计20个数字中,多少不同的数字

2组比较,不重复的数字几个,分别是

重复的数字几个,分别是

以下方法为先开辟列表,再对应的数字的位置计数,不使用集合和字典

###repeated.3
import random
l = []#once
n = []#repeated
m = [0] * 20

for i in range(10):
    a = random.randrange(1,21)
    print('{}'.format(a),end = ' ')
    m[a-1] += 1
print()

for j in range(20):
    if m[j]:
        if m[j] == 1:
            l.append(j + 1)
        else:
            n.append(j + 1)
            
print('repeating number: {}
once number: {} '.format(n,l))

使用比较后在相应的计数列表内相应位置加一,计算出数字出现的次数。

nums = [random.randint(1,20) for _ in range(10)]
l=[0]*len(nums)
seamnum = []
diffnum = []
for i in range(len(nums)):
    if l[i] != 0:
        continue
    count=0
    for j in range(i+1,len(nums)):
        if l[j] != 0:
            continue
        if nums[i] == nums[j]:
            
            l[j] += 1
            count += 1
    if count:
        count += 1
        seamnum.append((nums[i],count))
    else:
        diffnum.append(nums[i])
print(seamnum,diffnum)
原文地址:https://www.cnblogs.com/rprp789/p/9484493.html