Python 競賽程式設計技巧


Python 是大多數競賽程式設計挑戰中程式設計師首選的語言之一。大多數問題都可以在合理的時間範圍內使用 Python輕鬆計算。

對於一些複雜的問題,編寫足夠快的 Python 程式碼通常是一個挑戰。以下是幫助提高競賽程式設計中程式碼效能的一些 Python 式程式碼結構:

1. 字串連線: 不要使用以下結構。

str1 = ""
some_list = ["Welcome ", "To ", "Tutorialspoint "]
for x in some_list:
   str1 += x
print(str1)

以上方法會造成巨大的時間開銷。 相反,嘗試使用這個(join 方法):

str1 = ""
some_list = ["Welcome ", "To ", "Tutorialspoint "]
print(str1.join(some_list))

2. map 函式

通常,在競賽程式設計中,你會有這樣的輸入:

1234567

要將它們作為數字列表,只需:

list(map (int, input().split()))

始終使用 input() 函式,無論輸入型別如何,然後使用 map 函式進行轉換。

>>> list(map(int, input("enter numbers:").split()))
enter numbers:1 2 3 4 5 6 7
[1, 2, 3, 4, 5, 6, 7]
>>>

map 函式是 Python 的一個非常實用的內建函式,在很多情況下都非常有用。值得學習。

3. collections 模組

如果我們想從列表中刪除重複項。在 Java 等其他語言中,你可能需要使用 HashMap 或其他方法,但在 Python 中,它很簡單:

>>> print(list(set([1,2,3,4,3,4,5,6])))
[1, 2, 3, 4, 5, 6]

此外,在合併兩個或多個列表時,要注意使用 extend() 和 append()。

>>> a = [1, 2, 3,4] # list 1
>>> b = [5, 6, 7] # list 2
>>> a.extend(b)#gives one list
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> a.append(b) # gives list of list
>>> a
[1, 2, 3, 4, [5, 6, 7]]

4. 語言結構

最好在函式內編寫程式碼,儘管 Python 支援過程式程式碼。

def main():
   for i in range(2**3):
      print(x)
main()

比這要好得多:

for x in range(2**3):
   print(x)

由於底層的 CPython 實現,儲存區域性變數比全域性變數更快。

5. 使用標準庫

最好儘可能多地使用內建函式和標準庫包。在那裡,而不是:

newlist = []
for x in somelist:
   newlist.append(myfunc(x))

使用這個:

newlist = map(myfunc, somelist)

同樣,嘗試使用 itertools(標準庫),因為它們對於常見任務來說速度要快得多。例如,你可以用幾行程式碼實現排列迴圈。

>>> import itertools
>>> iter = itertools.permutations(["a","b","c"])
>>> list(iter)
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

6. 生成器

生成器是減少記憶體佔用和已編寫程式碼的平均時間複雜度的優秀結構。

def fib():
   a, b = 0, 1
   while 1:
      yield a
      a, b = b, a+b

更新於:2019年7月30日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.