Python随机数匹配程序优化:避免重复计数相同匹配数字
修改后的Python程序:统计不重复的匹配数字对
要实现统计不重复的匹配数字对,可以利用Python的set(集合)特性——集合会自动忽略重复元素。只需要把每次匹配成功的数字对存入集合,最后集合的长度就是不同匹配的次数,再把集合元素格式化成你需要的字符串即可。
修改后的代码
from random import randint total = int(input('Enter the number of iterations: ')) # 用集合存储不重复的匹配对 matched_pairs = set() for i in range(1, total + 1): print('i', i) number1 = randint(1, 5) print('num1', number1) number2 = randint(1, 5) print('num2', number2) if number1 == number2: # 将匹配对转为字符串存入集合,避免重复 matched_pairs.add(f"{number1} {number2}") # 统计不同匹配的次数 unique_count = len(matched_pairs) # 格式化输出匹配记录 record = ' ; '.join(matched_pairs) print(f'The number of unique matches: {unique_count}') print(f'Match records: {record}')
示例运行结果
假设迭代20次后,输出可能如下:
Enter the number of iterations: 20 i 1 num1 2 num2 1 i 2 num1 5 num2 3 i 3 num1 5 num2 5 ...(中间迭代过程省略) The number of unique matches: 3 Match records: 5 5 ; 1 1 ; 3 3
关键修改点
- 把原来的
count变量换成set类型的matched_pairs,利用集合自动去重的特性 - 匹配成功时,将数字对转为字符串加入集合
- 最后通过
len(matched_pairs)得到不同匹配的次数,用join方法格式化输出记录
内容的提问来源于stack exchange,提问作者Luiza
相关产品推荐
相关产品推荐

