Random 5-Letter Word Generator

  • Share this:

Code introduction


This function generates a random 5-letter word, where all letters must be lowercase. It first checks if the word is valid, and then randomly selects a word from a dictionary file.


Technology Stack : random, collections.deque, isalpha, islower, len, open, strip, readlines

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zebra(arg1, arg2):
    import random
    from collections import deque

    def is_valid(s):
        return s.isalpha() and s.islower() and len(s) == 5

    def get_random_word():
        with open('/usr/share/dict/words', 'r') as file:
            words = [line.strip() for line in file.readlines() if is_valid(line.strip())]
            return random.choice(words)

    return get_random_word()