return (num % 9 or 9) if num else 0
better one liner
W
wonderfuly
@wonderfuly
10
Reputation
66
Posts
337
Profile views
1
Followers
1
Following
Posts made by wonderfuly

RE: 3 methods for python with explains

Share my Python solution
class Solution(object): def lengthOfLongestSubstring(self, s): ret = 0 i = 0 d = {} for j, c in enumerate(s): if d.get(c, 1) >= i: i = d[c] + 1 ret = max(ret, j  i + 1) d[c] = j return ret

Python DP Solution
class Solution(object): def wiggleMaxLength(self, nums): cache = {} def _dp(i): if i == 0: return (1, 1) if i in cache: return cache[i] n = nums[i] rs = [_dp(j) for j in range(i) if nums[j] < n] r1 = max(r[0] for r in rs) if rs else 0 rs = [_dp(j) for j in range(i) if nums[j] > n] r2 = max(r[1] for r in rs) if rs else 0 ret = (r2+1, r1+1) cache[i] = ret return ret rs = [r for j in xrange(len(nums)) for r in _dp(j)] return max(rs) if rs else 0

We don't need binary search for this problem, do we?
class Solution(object): def findMin(self, nums): if nums[0] <= nums[1]: return nums[0] for i in range(len(nums)1): if nums[i+1] < nums[i]: return nums[i+1]

Concise Python generator solution
class BSTIterator(object): def __init__(self, root): def _dfs(node): if not node: return for x in _dfs(node.left): yield x yield node.val for x in _dfs(node.right): yield x self.iterator = _dfs(root) self._next = None def hasNext(self): try: self._next = next(self.iterator) return True except StopIteration: return False def next(self): return self._next

How to think it in the DFS way
we can imagine such a tree, out task is to traversal it with DFS, and collect numbers along the way: 1, 10, 100, ... you get it. When we encounter a number larger than
n
, we can return back to the previous level.Hope it helps

Straightforward Python Solution
from itertools import combinations class Solution(object): def maxProduct(self, words): ws = [(set(w), len(w)) for w in words] ret = 0 for (s1, l1), (s2, l2) in combinations(ws, 2): if not (s1 & s2): ret = max(ret, l1 * l2) return ret
the idea is to precompute
set
andlen
for each word to avoid duplicate computations 
RE: A python solution O(n) time, O(1) space
@cmc said in A python solution O(n) time, O(1) space:
A concise version
def reorderList(self, head): if not head: return # find the mid point slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next # reverse the second half inplace pre, node = None, slow while node: pre, node.next, node = node, pre, node.next # Merge inplace; Note : the last node of "first" and "second" are the same first, second = head, pre while second.next: first.next, first = second, first.next second.next, second = first, second.next return
this is a nice one