Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,656 questions

55,396 answers

573 users

How to get common letters that appear in every word in a list of words with Python

1 Answer

0 votes
"""
Efficient algorithm using Python sets:
--------------------------------------
Each word is converted into a set of its unique letters.

Example:
    "algebraic" -> {'a', 'l', 'g', 'e', 'b', 'r', 'i', 'c'}

Then:
    - Start with the set of letters from the first word.
    - Intersect with each subsequent word's letter set.
    - The final set contains letters common to all words.

This uses Python's built-in:
    - set()
    - set.intersection()
    - clear, idiomatic functional decomposition
"""

def letters_of(word):
    """Return a set of unique letters in the word."""
    return set(word)


def common_letters(words):
    """Return letters that appear in *every* word."""
    if not words:
        return set()

    # Start with letters of the first word
    common = letters_of(words[0])

    # Intersect with each subsequent word
    for word in words[1:]:
        common &= letters_of(word)

    return common


def print_letters(letters):
    """Print letters in sorted order."""
    print(" ".join(sorted(letters)))


def main():
    words = [
        "algebraic",
        "alphabetic",
        "ambiance",
        "abacus",
        "metabolic",
        "parabolic",
        "playback",
        "drawback",
        "fabricate",
        "flashback",
        "syllabic"
    ]

    result = common_letters(words)

    print("Common letters across all words:")
    print_letters(result)


if __name__ == "__main__":
    main()



"""
run:

Common letters across all words:
a b c

"""

 



answered Jul 10 by avibootz

Related questions

...