useful python tricks for interviews and leetcode

I switched from using java to python for doing leetcode. Here are some of the tricks i discovered, I am hoping to learn more tricks from people here.

  1. for - else

    • code block in else caluse executes when for finishes without break
  2. itertools.accumulate

    • For prefix sums, prefix products ect.
  3. tuple + @lru_cache

    • Sometimes you need to pass in a list as an agrument to method that you want to memoize, lists are mutable so convert list to tuple to make it memoizable.
  4. enumerate

    • traverse list with its index
  5. defaultdict

    • default values if key is missing from the dictionary
  6. neighbors and bound checking in a matrix:

        for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1):
          if 0 <= I < len(rooms) and 0 <= J < len(rooms[0]): continue
       
  7. Instead of

      while Q:		 
        el = Q.pop_left()
        Q.append(x)

    do

     for el in Q:
       Q+=	x,   #  note the , in the end
  8. Max fuction with key

    max([10,25,11,19], key= lambda x: x%10) 
    #19
  9. mulitiple comparision operator

    a>10 and a<20
    10 <a <20
  10. ~
    ~ : logical not inverts all bits in a number, useful for traversing a list in reverse.

      def is_palindrome(s):
         return all([s[i] == s[~i] for i in range(len(s)//2)])

I will keep updating this list if i can think of more or from comments here.

contributers : @user2708P

references:
https://leetcode.com/problems/walls-and-gates/discuss/72753/6-lines-O(mn)-Python-BFS

Thank you <3

Comments (9)