2 Lines Python


  • 4
    def judgeCircle(self, moves):
        c = collections.Counter(moves)
        return c['L'] == c['R'] and c['U'] == c['D']

  • 5
    Z

    it is one line and a bit efficient because count is much faster than Counter

    class Solution(object):
        def judgeCircle(self, moves):
            return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
    
    # 62 / 62 test cases passed.
    # Status: Accepted
    # Runtime: 39 ms
    

  • 0
    T

    @zqfan Using count might be slower since you have to go through the string 4 times. The original solution is only one pass.


  • 2

    Could be simpler and a little bit faster with complex number:

    def judgeCircle(self, moves):
        direct = {'U': 1, 'D': -1, 'L': 1j, 'R': -1j}
        return 0 == sum(direct[m] for m in moves)
    

    I was actually inspired by a @StefanPochmann thread years ago


  • 1

    @totolipton It is, in fact, way faster than the Counter solution. Probably because of the library call overhead.


  • 0
    Z

    Excellent!

    @waigx said in 2 Lines Python:

    Could be simpler and a little bit faster with complex number:

    def judgeCircle(self, moves):
        direct = {'U': 1, 'D': -1, 'L': 1j, 'R': -1j}
        return 0 == sum(direct[m] for m in moves)
    

    I was actually inspired by a @StefanPochmann thread years ago


  • 5

    @waigx And now you inspired me :-)

    def judgeCircle(self, moves):
        return not sum(map({'U': 1, 'D': -1, 'L': 1j, 'R': -1j}.get, moves))
    

    Or:

    def judgeCircle(self, moves):
        return not sum(1j**'RUL'.find(m) for m in moves)
    

    I'm really loving that one.

    A silly Python 3 version of it:

    def judgeCircle(self, moves):
        return not sum(map(1j.__pow__, map('RUL'.find, moves)))

Log in to reply
 

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