Elegant python code using "yield"


  • 0
    M
    def break_string(s, n_ip):
        if n_ip == 1:
            if int(s) > 255 or (s[0] == '0' and len(s) > 1):
                return            
            yield s[:]
    
        for i in xrange(1, len(s)):
            if int(s[:i]) > 255 or (s[0] == '0' and i > 1):
                return
            for ip in break_string(s[i:], n_ip-1):
                yield s[:i] + '.' + ip
    
    class Solution:
        # @param {string} s
        # @return {string[]}
        def restoreIpAddresses(self, s):
            return list(break_string(s, 4))

Log in to reply
 

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