Python golf


  • 1
    A

    Python one-liner (but still ~40ms)

    "".join([y[0] for y in __import__('itertools').takewhile(lambda x: len(set(x))==1, zip(*strs))])
    

    Suppose the words are ["cat", "car", "cant"]. zip(*strs) will combine characters together according to their index in the word, i.e., [("c","c","c"),("a","a","a"),("t","r","n")]. Note that the extra letter in "cant" doesn't need to be dealt with since zip just ignores it entirely! Then, it is a simple matter to take elements from the beginning (takewhile) while they meet the criteria that len(set(["c","c","c"]))==1, for example. This will throw out the ["t","r","n"]. After, we take the first element in each triplet and join them together.


  • -1
    B

    @aminnj 40 ms is very slow.


  • 0
    B
    This post is deleted!

  • 0
    B
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.