My Common Python Coding Mistakes

My common mistakes when solving code problems.

Trying to write more bug-free code, if I can. LOL

My Common Python Coding Mistakes



Similar Posts:


Common Mistakes:

  • Typo issue: used a wrong variable

  • Use a wrong function name

ERROR:

if s[left].lower() == s[right].lower:
    left, right = left+1, right-1

OK:

if s[left].lower() == s[right].lower():
    left, right = left+1, right-1

  • Initialize an array by reference
#!/usr/bin/env python
dp = [{}]*(3)
dp[0] = {0:1}

dp[1][1] = 1
print(dp[2][1]) # which one you will get? 1 or None?

dp[1] == dp[2]

  • Syntax error for Key data structures.
# set/collection
set1.append() # error
set1.add() # ok
# list
l = l.sort() # unexpected
sorted(l) # in-place change or generate a new list?
# array
array1.push() # ok
array1.pop(1) # ok
array1.pop() # error
# string
str[2:4] = 'ab' # error. Can't change string
  • Forget to add this. decorator for class function members.
# From:
self.ch = self.string[index]

# To:
self.ch = self.string[self.index]

# Errmsg: UnboundLocalError: local variable 'index' referenced before assignment

  • array index: For l[left:right], the right element is not excluded.
  • Cornder case: Forgot to process the initial state.

ERROR:

## Blog link: https://brain.dennyzhang.com/design-twitter
def getNewsFeed(self, userId):
        l = self.tweet_dict[userId]
        for followee in self.follow_dict[userId]:
            l += self.tweet_dict[followee]
        l.sort(reverse=True) 
        return l[0:10]

OK:

## Blog link: https://brain.dennyzhang.com/design-twitter
def getNewsFeed(self, userId):
        l = copy.deepcopy(self.tweet_dict[userId])
        for followee in self.follow_dict[userId]:
            l += self.tweet_dict[followee]
        l.sort(reverse=True) 
        return l[0:10]

  • Adding to set, we will remove duplicate; Meanwhile adding to list, we will keep the duplicate

Error:

## Blog link: https://brain.dennyzhang.com/design-snake-game
if len(self.foods) == 0 or [x2, y2] != self.foods[0]:
    self.snake_points_set.add((x2, y2))
    self.snake_points.append((x2, y2))

    self.snake_points_set.remove(self.snake_points[0])
    self.snake_points.popleft()
    return self.food_index

OK:

if len(self.foods) == 0 or [x2, y2] != self.foods[0]:
    first_point = self.snake_points.popleft()
    self.snake_points.append((x2, y2))

    self.snake_points_set.add((x2, y2))
    self.snake_points_set.remove(first_point)
    return self.food_index

linkedin
github
slack

PRs Welcome

Blog URL: https://www.dennyzhang.com/python-mistakes


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.