My last week was busy. While I was attending vGHC, I also learned the programming language Python and practiced it on Leetcode. In this post, I’ll shortly share my experience in switching from Ruby to Python.
Ruby is an object-orient language. It’s interpreted and human-centric. It’s frequently used in building a web application. As we all know Ruby on Rails, a popular web framework is using language Ruby. From my personal experience, Ruby is easy to understand, and its syntax is friendly for people who never coded before.
Python is also a powerful and popular language. Python code is easy to read. It’s widely used in data analysis and machine learning. Similar to Ruby on Rails, Python can also be used to create a web framework by Django.
Both languages are powerful, and they both can meet your expectations in solving problems. You can choose any of them based on your needs, whether to create a website or to treat heavy-load of data. For me, the reason is to learn another language and maybe touch on data analysis in the future.
Is it easy to switch to python?
Yes! As long as you have some experience in any programming language, Python is not hard to pick up. The following are several tips I found useful based on my last week experience:
- Import libraries when needed. Python has tons of libraries for you to choose from. Always remember to import them at the beginning of your code to use them.
import math #provide tons of useful function like math.floor(float)
import heapq #provide heap data structure and it's functions
- Unlike other programming languages where code block is defined by
endIn python, the code block is determined by
:and spacing. The following is a basic chunk of code, you can see how code blocks are defined in python. Problem description here.
def longestPalindrome(self, s: str) -> int:
chr_set = set()
for char in s:
if char in chr_set:
if len(chr_set) != 0:
return len(s) - len(chr_set) + 1
- Remember to explicitly write the return value for non-void functions.
Practice coding problem using python:
Description: We have a list of
points on the plane. Find the
K closest points to the origin
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
(The answer [[-2,4],[3,3]] would also be accepted.)
This problem can be solved by using data structure: heap. It can help us keep records of the closest k points.
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
heap = 
for (x,y) in points:
dist = -(x * x + y * y)
if len(heap) == K:
heapq.heappushpop(heap, (dist, x, y))
heapq.heappush(heap, (dist, x, y))
return [(x, y) for (dist, x, y) in heap]
Thank you for reading! I’ll keep updating my experience in learning Python!