Common Characters

May 14, 2019

Today’s exercise comes from a coding challenge site:

Given a list of words containing only lower-case letters, return a list of characters that appear in all the words, with multiplicity. For instance, given the words BELLA, LABEL and ROLLER, the characters E, L and L appear in all three words.

Your task is to return a list of characters that appear in all words of an input list. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisements

Pages: 1 2

2 Responses to “Common Characters”

  1. Globules said

    A Haskell version.

    import Data.List (foldr1, intersect)
    
    common :: Eq a => [[a]] -> [a]
    common []  = []
    common xss = foldr1 intersect xss
    
    main :: IO ()
    main = do
      print $ common ([] :: [String])
      print $ common ["BELLA"]
      print $ common ["BELLA", "LABEL"]
      print $ common ["BELLA", "LABEL", "ROLLER"]
    
    $ ./commchar
    ""
    "BELLA"
    "BELLA"
    "ELL"
    
  2. Paul said

    In Python.

    from collections import Counter
    from functools import reduce
    from operator import and_
    
    def common(listofwords):
        return list(reduce(and_, (Counter(w) for w in listofwords)).elements())
    
    print(common(["BELLA", "LABEL"]))  # -> ['B', 'E', 'L', 'L', 'A']
    print(common(["BELLA", "LABEL", "ROLLER"]))  # -> ['E', 'L', 'L']
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: