Pages

Mar 24, 2015

[Python] strip vs. replace

Here are some examples showing the differences between the function of "strip()" and "replace()" in Python.
Be careful! strip() will delete any character in the beginning or end of the word that matches "any" character in the word we put in the strip function. For example, we put "& quot;" as a parameter into strip(), then any character matches ('&', 'q', 'u', 'o', 't', ';') will be deleted. It doesn't have to be exactly the same "string."

Mar 15, 2015

[Python] Performance enhance by not using range() for comparison

When I was trying to enhance the performance of my Python code, the frist thing I tried is reducing the usage of functions. After I substituted the range() function, the performance had improved a lot, from 404ms to 106ms. The following is the difference between the two versions of the "ZigZag Conversion" code.

404ms
106ms Although the performance result depends on the test data, this substitution really improves the entire performance.

Mar 13, 2015

Mar 12, 2015

Apply BFS to special MST problems

Given a undirected and connected graph, and the edges have weights of either 1 or 2 (actually it is also applicable for weight larger than 2). How can we find a MST of the graph by using BFS?

Ans (I guess):
First, we can view an edge with weight of 2 as two edges with weight of 1 connected together. Then we can simply apply BFS to solve this problem. After finish the BFS algorithm, we check all the edges originally with weight of 2. If both parts of an edge are not both chosen as a path of the MST, then we delete this path. Finally, the result is a MST.

Use pdb to debug Python code

use pdb to debug python code:


some (not all) commands of pdb:
h: see the entire help list

l: l(ist) [first [,last]]
List source code for the current file.
Without arguments, list 11 lines around the current line or continue the previous listing.
With one argument, list 11 lines starting at that line.
With two arguments, list the given range; if the second argument is less than the first, it is a count. 

s:
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current function).

c
Continue execution, only stop when a breakpoint is encountered.

b
b(reak) ([file:]lineno | function) [, condition]

p: p expression
Print the value of the expression.

for more information: https://docs.python.org/2/library/pdb.html