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.
for - else
breakitertools.accumulate
tuple + @lru_cache
enumerate
defaultdict
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
Instead of
while Q:
el = Q.pop_left()
Q.append(x)do
for el in Q:
Q+= x, # note the , in the endMax fuction with key
max([10,25,11,19], key= lambda x: x%10)
#19mulitiple comparision operator
a>10 and a<20
10 <a <20~
~ : 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