I saw you guys enjoy Python code golf


  • 1
    S
    class Solution(object):
        def generateParenthesis(self, n):
            return solve(n, n)
    
    def solve(open, close):
        return ((open == close == 0 and ['']) or ((open and list(map('('.__add__, solve(open - 1, close))) or []) + (close > open and list(map(')'.__add__, solve(open, close - 1))) or [])))

  • 1

    You're either not really playing golf or you're really bad at it :-P

    For example, open == close == 0 and [''] could be o==c==0and[''], which uses far fewer strokes.

    Golfed version (157 strokes):

    class Solution:generateParenthesis=lambda _,n:s(n,n)
    s=lambda o,c:o+c<1and['']or(o
    and map('('.__add__,s(o-1,c))or[])+(c>o
    and map(')'.__add__,s(o,c-1))or[])
    

    Golfing my Solution 3 from here (134 strokes):

    class Solution:generateParenthesis=g=lambda s,n,o=0:n>0<=o and['('+p
    for p in s.g(n-1,o+1)]+[')'+p for p in s.g(n,o-1)]or[')'*o]*(n<1)
    

    132 strokes (saving 2) thanks to generating the strings "from right to left", see comments below:

    class Solution:generateParenthesis=g=lambda s,n,o=0:n>0<=o and[p+')'for
    p in s.g(n-1,o+1)]+[p+'('for p in s.g(n,o-1)]or['('*o]*(n<1)

  • 0
    S

    Err you're right, s/code golf/one liners/. Thanks for the golfed version, I think the map together with '('.__add__ and ')'.__add__ are too verbose for a golf version anyway.


  • 0

    Your map('('.__add__ is quite alright, a list comprehension is exactly equally long:

    map('('.__add__,x)
    ['('+s for s in x]
    

    The list comprehension has the advantage of not needing a space or so before it, but I kept that your way because I like it a lot conceptually and because it's a very characteristic part of your code.

    Ooh, I just realized I can make that list comprehension one character shorter:

    [s+')'for s in x]
    

    That's of course not the same, but I can use it if I simply generate the strings "from right to left" (as in the updated answer).


  • 0
    S

    You may also like this fancy use of map([].extend from here.


  • 0

    Oh wow, that's a nice solution, although more because of the algorithm than because of the map trick (which is also nice). It's "only" map(a.extend, though. Just saying cause I once actually used map({}.setdefault, a, b), really not keeping a reference to the dict or its method.


Log in to reply
 

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