随机生成 2 个字符组成的字符串(只使用 a,b,c,d 四个字母)1000 个,求其中字符串的重 复总次数。例如有:”ab”, ”ac”, ”bc”, ”ab”, ”ac”, ”bb”, ”ac”,则 ab 重复 1 次,ac 重复 2 次, 总的字符串重复次数为 3。
3条回答 默认 最新
- zpba 2021-12-13 10:40关注
#!/usr/bin/env python # -*- coding: utf-8 -*- import random # 随机一个字符串 def randStr(): chArr = ['a', 'b', 'c', 'd'] # 在数组中随机出一个字符 s1 = chArr[random.randint( 0, 3)] s2 = chArr[random.randint( 0, 3)] return ""+s1+s2 def main(): # 生成1000个字符串 strArr = [] for i in range(1000): strArr.append( randStr()) # 遍历字符串,判断重复 countObj = {} for s in strArr: if countObj.get( s) is None: countObj[s] = 0 countObj[s] = countObj[s] + 1 # 遍历打印所有的数量 totalCount = 0 for s in countObj: print( "%s:%d"%(s, countObj[s])) totalCount = totalCount + countObj[s] print( " 总的字符串重复次数:%d"%(totalCount)) main()
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报