GithubHelp home page GithubHelp logo

leetcode-py's Introduction

Leetcode

This is my solution to Leetcode Online Judge's problems. Currently I am revamping the problems all over again towards more idiomatic Python. Stay tuned for updates.

Feel free to submit pull requests for submitting more elegant solution.

###List of idiomatic Python I prefer (as of now)

  • Prefer list comprehension over map / filter.
	# from Gray Code

	# Bad
	def grayCode(self, n):
        return map(lambda x: (x / 2) ^ x, range(1 << n))

	# Idiomatic
	def grayCode(self, n):
        return [(x / 2) ^ x for x in range(1 << n)]
  • Prefer using in keyword over repetitive variable in conditional statement.
	# from Post Order Traversal

	# Bad
	if parent.right == None or parent.right == prev

	# Idiomatic
	if parent.right in (None, prev):
  • Prefer using docstring over single line comment when describing functionality of a method.
	# from Search Insert Position

	# Bad
	# Iterative solution is also fine.
	def searchInsert(self, A, target):

	# Idiomatic
	def searchInsert(self, A, target):
    	"""Iterative solution is also fine.
    	"""
  • Prefer implicit evaluation of condition (e.g. if, while, etc.) over explicit comparison in condition.
    Notice empty list and dictionary will be evaluated to False, so that is very handy.
	# from Binary Tree Preorder Traversal

	# Bad
	while len(stack) > 0:
		current = stack.pop()

	# Idiomatic
	while stack:
		current = stack.pop()
  • Prefer is None over == None. Notice is looks for referential equality, and None is a singleton.
    The fundamental reason for this preference is much improved speed, and == can be overriden by __eq__.
	# from Binary Tree Preorder Traversal

	# Bad
	if root == None:

	# Idiomatic
	if root is None:

One interesting side note in Python regarding this is on Stackoverflow. Trust me, that is worth your 60 seconds of time. But that only works in REPL though, not on a executable python file.

READ THIS or above two rules will only do you harm:
Sometimes you have to use if foo is not None over if foo. For example, if foo is 0, then if foo will become False. But 0 is not None. Just watch out. A rule of the thumb is if you want to check if the default argument of a function is None, then use if foo is not None, otherwise you can most likely use if foo if you know what you are doing.

  • Consider using enumerate when index accessing looks verbose
	# from Two Sum

	# Bad
	for i in range(len(nums)):
        if target - nums[i] in lookup:
            return (lookup[target - nums[i]] + 1, i + 1)
        lookup[nums[i]] = i

    # Idiomatic
    for i, num in enumerate(nums):
        if target - num in lookup:
            return (lookup[target - num] + 1, i + 1)
        lookup[num] = i
  • Readability counts.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." Martin Fowler is right.

	# from Edit Distance

	# Bad
	def minDistance(self, word1, word2):
        distance = [[i] for i in range(len(word1) + 1)]
        distance[0] = [i for i in range(len(word2) + 1)]
        for i in range(1, len(word1) + 1):
            for j in range(1, len(word2) + 1):
                distance[i].append(min(distance[i - 1][j] + 1, distance[i][j - 1] + 1, distance[i - 1][j - 1] + (word1[i - 1] != word2[j - 1])))
        return distance[-1][-1]

    # Idiomatic
    def minDistance(self, word1, word2):
        distance = [[i] for i in range(len(word1) + 1)]
        distance[0] = [i for i in range(len(word2) + 1)]
        for i in range(1, len(word1) + 1):
            for j in range(1, len(word2) + 1):
                deletion = distance[i - 1][j] + 1
                addition = distance[i][j - 1] + 1
                substitution = distance[i - 1][j - 1]
                if word1[i - 1] != word2[j - 1]:
                    substitution += 1
                distance[i].append(min(deletion, addition, substitution))
        return distance[-1][-1]

leetcode-py's People

Contributors

defipanda avatar resorcap avatar yjc801 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leetcode-py's Issues

Reach out for Cross rollup NFT project

Hey Zhe. Sorry I didn't find a better way to reach out. I currently work at a social media company and is onboarding NFTs to the platform. Would love to chat & learn more about the NFT project.
Do you mind syncing up on wechat? Thank you!

python bit

An easy solution for Single number I and II is based on 32 bit presentation which python do not naturally support. Is there a way to transform this to python? Thanks

class Solution {
public:
int singleNumber(vector& nums) {
int digits[32]={0};
for( int k=0;k<nums.size();k++)
for ( int i =0;i<32;i++)
if ( nums[k]>>i&1)
digits[i]+=1;
int res=0;
for ( int i =0;i<32;i++)
res+=(digits[i]%2)<<i;
return res;
}
};

Palindrome Number

Solution for Palindrome Number encounter an unexpected error message on LeetCode on 7 Aug 2014.
1

Insertion Sort List

This one will get TLE on larger test case, but it seems there is no way to improve its performance with python since it asks to use insertion explicitly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.