1-liners Python


  • 12

    My maybe best:

    def isStrobogrammatic(self, num):
        return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)/2+1))
    

    Some others:

    def isStrobogrammatic(self, num):
        return all(c + d in '696 00 11 88' for c, d in zip(num, num[::-1]))
    
    def isStrobogrammatic(self, num):
        return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)))
    
    def isStrobogrammatic(self, num):
        return all(map('696 00 11 88'.count, map(operator.add, num, num[::-1])))
    
    def isStrobogrammatic(self, num):
        return all(p in '696 00 11 88' for p in map(operator.add, num, num[::-1]))
    
    def isStrobogrammatic(self, num):
        return set(map(operator.add, num, num[::-1])) <= set('69 96 00 11 88'.split())
    
    def isStrobogrammatic(self, num):
        return set(map(operator.add, num, num[::-1])) <= {'69', '96', '00', '11', '88'}
    
    def isStrobogrammatic(self, num):
        return set(map(''.join, zip(num, num[::-1]))) <= {'69', '96', '00', '11', '88'}

  • 0
    O

    omg...never think of using ~i !!


  • 0

    Why not? Is something bad about it? I like it.


  • 0
    O

    yep! so cooool! You remind me what 2's complement should be ha, fantastic!


  • 0
    B

    i & ~i, the idea is really awesome!!


  • 0
    I

    Do they require python 3.0 to run? My python 2.7 always complains "TypeError: 'dict' object is not callable" for the last five solutions.


  • 0

    @iwatch LeetCode uses 2.7 (see the FAQ), so they do work there. No idea what you're doing. There's not a single dict involved in those solutions.


  • 0
    I

    After I restarted my python interpreter, the error message is gone. No idea what happened


  • 0
    S

    Oh yes. ~ trick is awesome. Always have new insights from your code here.


  • 1
    Z

    We got similar solution again! and len(n) + 1 >> 1 can save one iteration in even number case ;) Actually I leaned "~i" technique from a median related question you posted.

    This is mine:
    all([n[i] + n[~i] in "11 88 00 696" for i in range(len(n) + 1 >> 1)])


  • 0

    @zhongyuan9817 Oh, right, I should've used (len(num)+1)/2. Using >> is slightly shorter but I can never remember all the operator precedences :-)


  • 0
    J

    @StefanPochmann Hi, thanks for the nice solution. I am wondering what does ~ really mean in array indexing?


  • 0
    J

    @StefanPochmann Hi, I found the nice answer on StackOverflow. For example, the table is like this:

    i ~i
    0 -1
    1 -2
    2 -3
    3 -4
    4 -5
    5 -6

    Thanks for your excellent answer as always anyway.


Log in to reply
 

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