编程实现Size: Large 点击复制后,将打开C知道体验页 | 从给定的列表[a,b,c,d,e,f,g],从给定的列表中随机挑选20次以生成随机字符串,输出在该字符串中出现了第i个只出现了j次的字母(i, j为键盘输入)
时间: 2023-05-26 16:05:44 浏览: 99
# -*- coding: utf-8 -*-
import random
def generate_string(n):
# 从给定列表中随机选择n个字符组成字符串返回
choices = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
return ''.join(random.choices(choices, k=n))
def count_char(s):
# 计算字符串中每个字符出现的次数,返回一个字典
char_count = {}
for c in s:
char_count[c] = char_count.get(c, 0) + 1
return char_count
def find_ith_jth_char(s, i, j):
# 查找在字符串s中第i个只出现了j次的字符
char_count = count_char(s)
count_count = {} # key是出现次数,value是该出现次数的字符数量
for c, count in char_count.items():
if count not in count_count:
count_count[count] = 1
else:
count_count[count] += 1
j_count = 0 # j的计数器
for c, count in char_count.items():
if count == j:
j_count += 1
if j_count == i:
return c
return None
# 主函数
if __name__ == '__main__':
s = generate_string(20)
print('随机生成的字符串:', s)
i = int(input('请输入i:'))
j = int(input('请输入j:'))
c = find_ith_jth_char(s, i, j)
if c is not None:
print('在字符串中第%d个只出现了%d次的字符是: %s' % (i, j, c))
else:
print('在字符串中不存在第%d个只出现了%d次的字符!' % (i, j))
阅读全文