Leetcode Climbing Stairs Solution (Python)

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Constraints:

  • 1 <= n <= 45

Solution (Python)

class Solution:
    # dp[i] denotes number of ways for stairs with i steps
    dp = [-1 for i in range(45+1)]
        
    def climbStairs(self, n: int) -> int:
        # Base case
        if n<=1:
            return 1
        if self.dp[n]!=-1:
            return self.dp[n]
        # Recursive step
        self.dp[n] = self.climbStairs(n-1) + self.climbStairs(n-2)
        return self.dp[n]

Elements of Programming Interviews in Python: The Insiders’ Guide

Implement strStr() Leetcode Solution Python

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Leetcode Solution (Python)

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        #print(needle)
        
        for i in range(0,len(haystack)-n+1):
            substr = haystack[i:i+n]
            #print(substr)
            if substr == needle:
                return i
            
        return -1

Elements of Programming Interviews in Python: The Insiders’ Guide

First Unique Character in a String Leetcode Solution Python

Leetcode Question

Given a string sfind the first non-repeating character in it and return its index. If it does not exist, return -1.

Solution (Python)

class Solution:
    def firstUniqChar(self, s: str) -> int:
        chardict = {}
        for i in range(0,len(s)):
            #print(s[i])
            if s[i] in chardict:
                value = chardict[s[i]][0]
                index = chardict[s[i]][1]
                chardict.update({s[i]:[value+1,index]})
            else:
                chardict.update({s[i]:[1,i]})
        #print(chardict)
        ans = len(s)
        for key,value in chardict.items():
            if value[0]==1 and value[1]<ans:
                ans = value[1]
        if ans!=len(s):
            return ans
        return -1

Cracking the Coding Interview: 189 Programming Questions and Solutions

Valid Sudoku Leetcode Solution Python

Question

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

Solution (Python)

class Solution:
    def checkRep(self, checklist):
        #print(checklist)
        for i in range(1,9+1):
            count = checklist.count(str(i))
            #print(i,count)
            if count>1:
                return False
        else:
            return True
        
    def getSquare(self,i_start,j_start,board):
        square_list = []
        for i in range(i_start,i_start+3):
            for j in range(j_start,j_start+3):
                square_list.append(board[i][j])
        return square_list
        
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        # Check Rows
        for i in range(0,9):
            if self.checkRep(board[i])==False:
                return False
        
        # Check Columns
        for j in range(0,9):
            if self.checkRep([x[j] for x in board])==False:
                return False
        
        # Check Squares
        square_coords = []
        for i in range(0,3):
            for j in range(0,3):
                square_coords.append([i*3,j*3])
        #print(square_coords)
        for coord in square_coords:
            square_list = self.getSquare(coord[0],coord[1],board)
            if self.checkRep(square_list)==False:
                return False
        return True

Cracking the Coding Interview: 189 Programming Questions and Solutions

Move Zeroes Leetcode Python Solution

Question

Given an integer array nums, move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Python Solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i=0
        num_zeros = 0
        while i<len(nums):
            #print(i)
            if i<=len(nums)-num_zeros:
                if nums[i]==0:
                    nums.pop(i)
                    nums.append(0)
                    num_zeros+=1
                else:
                    i+=1
            else:
                break

Cracking the Coding Interview: 189 Programming Questions and Solutions

Remove Duplicates From Sorted Array Leetcode Solution in Python

Question

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

Solution (Python)

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        final_list = []
        for num in nums:
            if num not in final_list:
                final_list.append(num)
        nums[:] = final_list
        k = len(nums)
        return k

Cracking the Coding Interview: 189 Programming Questions and Solutions

How to speed up R code in RStudio

I just found out by trial and error that the suppressing of print statements in RStudio greatly speeds up the R code.

In my case, code that was originally estimated to take around 40 hours to run,  just ran in under an hour after I suppressed all the print statements in the for loops.

This is supported by evidence in other forums, for example in StackOverflow: R: Does the use of the print function inside a for loop slow down R?

Basically, if your code prints too much output to the console, it will slow down RStudio and your R code as well. It may be due to all the output clogging up the memory in RStudio. R is known to be “single thread” so it can only use 1 CPU at a time, even if your computer has multiple cores.

Hence, the tips are to:

  • Reduce the number of print statements in the code manually.
  • Set quiet=TRUE in all scan statements. Basically, the default behavior is that scan() will print a line, saying how many items have been read.

This is especially true with for loops, since the amount of printed output can easily number to the millions, and overwhelm RStudio.

How to keep Python / R Running on Mac (without screen lock or sleep)

When the Mac (or MacBook) is running for a long time, it is very liable to do one of the following things:

  • sleep
  • screen saver
  • lock screen

The problem is that your Python program or R program running in the background will most likely stop completely. Sure, it can resume when you activate the Mac again, but that is not what most people want! For one, it may impact the accurate calculation of elapsed time of your Python code.

Changing settings via System Preferences -> Energy Saver is a possible solution, but it is troublesome and problematic:

  • Have to switch it on and off again when not in use (many steps).
  • Preventing sleep may still run into screen saver, screen lock, etc.
  • Vice versa, preventing screen lock may still run into Mac sleeping, etc.

The solution is to install this free App called Amphetamine. Despite its “drug” name, it is a totally legitimate program that has high reviews everywhere. What this app does is to prevent your Mac from stopping, locking or sleeping. Hence, whatever program you are running will not halt till the program is done (or when you switch off Amphetamine).

It is a great program that does its job well! Highly recommended for anyone doing programming, video editing or downloading large files on Mac.

Best way to time algorithms in Python

There are tons of ways to calculate elapsed time (in seconds) for Python code. But which is the best way?

So far, I find that the “timeit” method seems to give good results, and is easy to implement. Source: https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python

Use timeit.default_timer instead of timeit.timeit. The former provides the best clock available on your platform and version of Python automatically:

from timeit import default_timer as timer

start = timer()
# ...
end = timer()
print(end - start) # Time in seconds, e.g. 5.38091952400282

This is the answer by the user “jfs” on Stack Overflow.

Benefits of the above method include:

  • Using timeit will produce far more accurate results since it will automatically account for things like garbage collection and OS differences (comment by user “lkgarrison”)

Please comment below if you know other ways of measuring elapsed time on Python!

Other methods include:

  • time.clock()  (Deprecated as of Python 3.3)
  • time.time() (Is this a good method?)
  • time.perf_counter() for system-wide timing,
  • or time.process_time() for process-wide timing

 

How to write Bash file to run multiple Python scripts simultaneously

Step 1 is to create a Bash file (using any editor, even Notepad). Sample code:

#!/usr/bin/env bash
python testing.py &
python testingb.py &

The above code will run two Python files “testing.py” and “testingb.py” simultaneously. Add more python scripts if needed. The first line is called the “shebang” and signifies the computer to run bash (there are various versions but according to StackOverflow the above one is the best).

The above bash file can be saved to any name and any extension, say “bashfile.txt”.

Step 2 is to login to Terminal (Mac) or Putty (Windows).

Type:

chmod +x bashfile.txt

This will make the “bashfile.txt” executable.

Follow up by typing:

nohup ./bashfile.txt

This will run the “bashfile.txt” and its contents. The output will be put into a file called “nohup.out”. The “nohup” option is preferred for very long scripts since it will keep running even if the Terminal closes (due to broken connection or computer problems).

Python Online Courses for Teenagers/Adults

If your child is interested in a Computer Science/Data Science career in the future, do consider learning Python beforehand. Computer Science is getting very popular in Singapore again. To see how popular it is, just check out the latest cut-off point for NUS computer science, it is close to perfect score (AAA/B) for A-levels.

According to many sources, the Singapore job market (including government sector) is very interested in skills like Machine Learning/ Deep Learning/Data Science. It seems that Machine Learning can be used to do almost anything and everything, from playing chess to data analytics. Majors such as accountancy and even law are in danger of being replaced by Machine Learning. Python is the key language for such applications.

I just completed a short course on Python: Python A-Z™: Python For Data Science With Real Exercises! The course fee is payable via Skillsfuture for Singaporeans, i.e. you don’t have to pay a single cent. (You have to purchase it first, then get a reimbursement from Skillsfuture.) At the end, you will get a Udemy certificate which you can put in your LinkedIn profile.

The course includes many things from the basic syntax to advanced visualization of data. It teaches at quite a basic level, I am sure most JC students (or even talented secondary students) with some very basic programming background can understand it.

The best programming language for data science is currently Python. Try not to learn “old” languages like C++ as it can become obsolete soon. Anyway the focus is on the programming structure, it is more or less universal across different languages.icon

Udemy URL: Python A-Z™: Python For Data Science With Real Exercises!

Related posts on Python:

Python Math Programming

Recently, I am thinking of learning the Python language for Math programming.

An advantage for using Python for Math Programming (e.g. testing out some hypothesis about numbers), is that the Python programming language theoretically has no largest integer value that it can handle. It can handle integers as large as your computer memory can handle. (Read more at: http://userpages.umbc.edu/~rcampbel/Computers/Python/numbthy.html)

Other programming languages, for example Java, may have a maximum integer value beyond which the program starts to fail. Java integers can only have a maximum value of 2^{31}-1 \approx 2.15 \times 10^9, which is pretty limited if you are doing programming with large numbers (for example over a trillion). For instance, the seventh Fermat number is already 18446744073709551617. I was using Java personally until recently I needed to program larger integers to test out some hypothesis.

How to install Python (free):

Hope this is a good introduction for anyone interested in programming!


Featured book:

Learning Python, 5th Edition

Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz’s popular training course, this updated fifth edition will help you quickly write efficient, high-quality code with Python. It’s an ideal way to begin, whether you’re new to programming or a professional developer versed in other languages.

Complete with quizzes, exercises, and helpful illustrations, this easy-to-follow, self-paced tutorial gets you started with both Python 2.7 and 3.3— the latest releases in the 3.X and 2.X lines—plus all other releases in common use today. You’ll also learn some advanced language features that recently have become more common in Python code.

  • Explore Python’s major built-in object types such as numbers, lists, and dictionaries
  • Create and process objects with Python statements, and learn Python’s general syntax model
  • Use functions to avoid code redundancy and package code for reuse
  • Organize statements, functions, and other tools into larger components with modules
  • Dive into classes: Python’s object-oriented programming tool for structuring code
  • Write large programs with Python’s exception-handling model and development tools
  • Learn advanced Python tools, including decorators, descriptors, metaclasses, and Unicode processing