Python easy understanding solution in 1 line


  • 1
    def findWords(self, words):
        return [word for word in words if any(set(word.upper()).issubset(row) for row in [set('QWERTYUIOP'), set('ASDFGHJKL'), set('ZXCVBNM')])]
    

  • 3

    Just made it a bit shorter and faster...

    def findWords(self, words):
        return [word for word in words if any(set(word.upper()) <= set(row) for row in ('QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM'))]

  • 0

    @StefanPochmann Thank you, that's helpful for me.


  • 0

    Similar idea:

     def findWords(self, words):
            keyboard = [
                set("qwertyuiopQWERTYUIOP"),
                set("asdfghjklASDFGHJKL"),
                set("zxcvbnmZXCVBNM")
            ]
            has_row = lambda word: any(all(c in row for c in word) for row in keyboard)
            return filter(has_row, words)
    

Log in to reply
 

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