liveBook · Manning

Random_string

As explained in Learn AI-Assisted Python Programming, Second Edition

random_string is a book-specific Python function that generates a secret digit string of a requested length without repeated digits.

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

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains the contract, representation, two implementations, and test properties, but does not develop exact random-output tests.
Examples
Uses Bulls and Cows secret codes, a four-digit leading-zero example, and two Python implementations.
What it assumes
Uses Python functions, parameters, strings, indexing, loops, membership checks, and the random module.
What you can do after
Build it from scratch in Python and test its length, uniqueness, digit validity, and random-range behavior.
How it connects
Connects function design with parameters, strings, indexing, randomness, validation, and top-down design.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.