Random Word Generator with Length Constraints

  • Share this:

Code introduction


This function generates a random word within a specified length range. It defines an inner function `generate_word` to create a random word and then uses `is_valid_word` to check if the generated word meets the length requirements. If it doesn't, it continues generating until it finds a valid word.


Technology Stack : Python

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_word_generator(min_length, max_length):
    import random
    import string

    def generate_word(length):
        return ''.join(random.choices(string.ascii_lowercase, k=length))

    def is_valid_word(word):
        return len(word) >= min_length and len(word) <= max_length

    while True:
        word = generate_word(random.randint(min_length, max_length))
        if is_valid_word(word):
            return word                
              
Tags: