Python随机字符串重复问题

随机生成 2 个字符组成的字符串(只使用 a,b,c,d 四个字母)1000 个,求其中字符串的重 复总次数。例如有:”ab”, ”ac”, ”bc”, ”ab”, ”ac”, ”bb”, ”ac”,则 ab 重复 1 次,ac 重复 2 次, 总的字符串重复次数为 3。


#!/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()
import itertools as it
import random
from collections import Counter
a = 'abcd'
s = it.permutations(a, 2)
s = [''.join(i) for i in s]
res = [random.choice(s) for i in range(1000) ]
result = Counter(res )

result = sorted(result.items(), key=lambda x: x[1])
print(dict(result))

import random

gen_str_list = []
l = ['a','b','c','d']
for i in range(1000):
    gen_str_list.append(random.choice(l) + random.choice(l))
res = {}
for key in gen_str_list:
    if key not in res:
        res[key] = 1
    else:
        res[key] += 1
count = 0
for r in res:
    if res[r] > 1:
        count += res[r]
print(count)