Generate 200 Random Activation Codes in Python and Count Character Frequencies Instantly
This tutorial shows how to quickly generate 200 activation codes in the xxxx-xxxx-xxxx-xxxx format using a Python generator and then tally the occurrence of each character with a dictionary, providing both the code and sample output.
Student question: Generate 200 activation codes in the format xxxx-xxxx-xxxx-xxxx using Python and count the occurrence of each character.
Coach analysis highlights: the problem requires fast generation and statistics, suggests using a generator and a dictionary for counting.
Solution
import string
import random
class CreateString:
def __init__(self):
self.chars = string.ascii_letters + string.digits
def __iter__(self):
for _ in range(200):
codes = []
for _ in range(4):
codes.append("".join(random.choices(self.chars, k=5)))
yield "-".join(codes)
codes = CreateString()
for code in codes:
print('code:', code)
result = "".join([x.strip("-") for x in codes])
count_tmp = {}
for k in result:
count_tmp[k] = count_tmp.get(k, 0) + 1
print(count_tmp)Running the script prints each generated code and a dictionary showing how many times each character appears.
The implementation leverages the string and random modules; reviewing their source code can be insightful.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
