1-liner Python


  • 21

    Solution:

    def validWordSquare(self, words):
        return map(None, *words) == map(None, *map(None, *words))
    

    Or saving some work but taking two lines:

    def validWordSquare(self, words):
        t = map(None, *words)
        return t == map(None, *t)
    

    Explanation:

    The map(None, ...) transposes the "matrix", filling missing spots with None. For example:

    ["abc",           [('a', 'd', 'f'),
     "de",     =>      ('b', 'e', None),
     "f"]              ('c', None, None)]
    

    And then I just need to check whether transposing it once more changes it.


  • 0
    F

    That's really awesome! I didn't know map could be used in this way.


  • 0

    Very nice! I had the same idea, but my code is much more pedestrian

    def validWordSquare(self, words):
        transpose = []
        for w in words:
            while len(w) > len(transpose): transpose.append([])
            for i in xrange(len(w)): transpose[i].append(w[i])
        for i in xrange(len(words)):
            if words[i] != ''.join(transpose[i]): return False
        return True
    

  • 1

    This is cool, I never thought map could be used for transposing matrix.
    I got another one-liner but really ugly compared to your solution;

    from itertools import izip_longest as izip
    
    class Solution(object):
        def validWordSquare(self, words):
            return map("".join, izip(*words, fillvalue='')) == words
    

  • 0
    M

    @waigx Also an excellent idea


  • 0

    Doesn't work in Python 3.x. One must use itertools.zip_longest to transpose, as done by @waigx.


  • 0
    W

    Can you do it 1 - liner by java?


  • 0
    L

    OMG. This exists


  • 0
    O

    My longer 1-liner:

    return all(j<len(words) and i<len(words[j]) and c==words[j][i] for i,w in enumerate(words) for j,c in enumerate(w))
    

  • 0
    P

    @StefanPochmann That is a really cool idea , but throws an error saying that the parameter of map must be an iterable not a map


  • 0

    @parime said in 1-liner Python:

    throws an error saying that the parameter of map must be an iterable not a map

    That's not true.

    But if you provide details about what exactly you did, maybe we'll find your mistake.


  • 0
    P

    @StefanPochmann Runs fine here on leetcode but throws an error in my system. I checked with online compiler too.0_1501195512516_leetcode_error.PNG


  • 0

    @parime Ah, you're using the wrong Python :-P

    map changed significantly from Python 2 to Python 3. My solution is Python 2. It doesn't make sense to try this in Python 3, and Python 3 isn't even supported for this problem.

    That particular error message appears to be very new. My Python 3.5.2 complains about 'NoneType' object is not callable (as expected). But in Python 3.6.1 I now get ... must be an iterable, not map as well. Which, frankly, is very irritating. Because a map is an iterable. I'll investigate a bit further...


  • 0

  • 0
    P

    @StefanPochmann Ahh. Thanks I did not know that.
    I tried doing this

    def validWordSquare(self, words):
    """
    :type words: List[str]
    :rtype: bool
    """
    n = len(words)
    i = 0
    compare = ["" for _ in range (n)]
    for w in words:
    l = len(w)
    for j in range(l):
    try:
    compare[j] = compare[j] + w[j]
    except IndexError:
    continue

        for i in range(n):
            if compare[i] != words[i]:
                return False
            
            
        return True
    

  • 0

    @parime Does your code look properly formatted and readable to you? To me it doesn't...


  • 0
    P

    @StefanPochmann Ah. I missed out at while posting the previous reply. Can i do better than this?

    
    
        def validWordSquare(self, words):
            """
            :type words: List[str]
            :rtype: bool
            """
            n = len(words)
           # i = 0
            compare = ["" for _ in range (n)]
            for w in words:
                l = len(w)
                for j in range(l):
                    try:
                        compare[j] = compare[j] + w[j]
                    except IndexError:
                        continue
                    
            for i in range(n):
                if compare[i] != words[i]:
                    return False
                
                
            return True
    

  • 0
    S

    @StefanPochmann each time I see an amazing solution, I know you are there bro~


  • 0
    Y

    @StefanPochmann Could you explain why/how map(None, *list) transposes the matrix and also fills the empty spots with None?


  • 0

    @yujiehuang Did you check out the documentation?


Log in to reply
 

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