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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
# @return a string | |
def convert(self, s, nRows): | |
row_len = 2 * nRows - 2 | |
string = ["" for _ in range(nRows)] | |
if nRows <= 2: | |
for i in range(len(s)): | |
string[i % nRows] += s[i] | |
else: | |
for i in range(len(s)): | |
res = i % row_len | |
if res in range(nRows, row_len): | |
string[row_len - res] += s[i] | |
else: | |
string[res] += s[i] | |
output = "" | |
for i in range(nRows): | |
output += string[i] | |
return output |
106ms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
# @return a string | |
def convert(self, s, nRows): | |
row_len = 2 * nRows - 2 | |
string = ["" for _ in range(nRows)] | |
if nRows <= 2: | |
for i in range(len(s)): | |
string[i % nRows] += s[i] | |
else: | |
for i in range(len(s)): | |
res = i % row_len | |
if res >= nRows and res < row_len: # I just replaced the range() function here | |
string[row_len - res] += s[i] | |
else: | |
string[res] += s[i] | |
output = "" | |
for i in range(nRows): | |
output += string[i] | |
return output |
No comments:
Post a Comment