random_string generates a computer’s secret code as a string of digit characters. It accepts the requested length, preserves leading zeros, and avoids repeated digits so the result can be compared character by character. section 10.3.3 section 10.3.4
The function’s design separates the task into clear input, processing, and output:
- Input: an integer length specifying how many digits the secret code needs. section 10.3.3
- Process: repeatedly choose a random digit and add it only when it is not already present. section 10.3.4
- Output: a string of the requested length containing digit characters without repeats. section 10.3.3
Bulls and Cows secret code
In the game’s top-down design, play calls random_string to generate the computer’s secret code before collecting guesses and reporting correct or misplaced digits. The implementation starts with an empty string, uses random.randint(0, 9), checks membership with str(r) not in s, and returns s. An alternative shuffles the digits 0 through 9 and joins the requested prefix. Random output is checked through its length, uniqueness, digit validity, and plausible range rather than exact-value tests. section 10.3.2 section 10.3.4
Listing 10.1 Function random_string for generating a secret code
import random #1
def random_string(length):
'''
length is an integer.
Return a string of the given length, where each character
is a digit from 0 to 9, and with no repeated digits.
'''
s = '' #2
while len(s) < length: #3
r = random.randint(0, 9) #4
if str(r) not in s: #5
s += str(r) #6
return s #7
Shows the complete Python implementation and the loop, duplicate check, string conversion, and return operation. section 10.3.4
