# 竞争性编码的Python技巧

Python是一种这样的编程语言, 它使一切变得简单而直接。任何精通python竞争编码的人都会对它的许多功能沉迷。以下列出了我发现的一些很酷的功能, 它们在竞争性编码环境中最有用。

1. Counter Package的most_common函数。

``````# Code to find top 3 elements and their counts
# using most_common
from collections import Counter

arr = [ 1 , 3 , 4 , 1 , 2 , 1 , 1 , 3 , 4 , 3 , 5 , 1 , 2 , 5 , 3 , 4 , 5 ]
counter = Counter(arr)
top_three = counter.most_common( 3 )
print (top_three)``````

``[(1, 5), (3, 4), (4, 3)]``

2. heapq软件包的n个最大/n个最小函数。

``````# Python code to find 3 largest and 4 smallest
# elements of a list.
import heapq

grades = [ 110 , 25 , 38 , 49 , 20 , 95 , 33 , 87 , 80 , 90 ]

``````[110, 95, 90]
[20, 25, 33, 38]``````

3. 字典和概念的压缩字典

python中的字典因其提供的独特功能而令人着迷。它们以类似数组的结构形式存储为键和值对。每个值都可以通过其对应的键访问。

zip函数用于将两个列表连接在一起, 或者我们甚至可以将字典中的键和值对作为单个列表连接在一起。在以下代码片段中将清楚说明此概念的应用。

``````# Python code to demonstrate use of zip.
import heapq

stocks = {
'Goog' : 520.54 , 'FB' : 76.45 , 'yhoo' : 39.28 , 'AMZN' : 306.21 , 'APPL' : 99.76
}

zipped_1 = zip (stocks.values(), stocks.keys())

# sorting according to values
print ( sorted (zipped_1))

zipped_2 = zip (stocks.keys(), stocks.values())
print ( sorted (zipped_2))
#sorting according to keys``````

``````[(39.28, 'yhoo'), (76.45, 'FB'), (99.76, 'APPL'), (306.21, 'AMZN'), (520.54, 'Goog')]
[('AMZN', 306.21), ('APPL', 99.76), ('FB', 76.45), ('Goog', 520.54), ('yhoo', 39.28)]``````

map功能。

。下面的示例将对此功能进行简单的应用。该函数将函数名称和需要应用函数的列表名称作为参数。

``````# Python code to apply a function on a list
income = [ 10 , 30 , 75 ]

def double_money(dollars):
return dollars * 2

new_income = list ( map (double_money, income))
print (new_income)``````

``[20, 60, 150]``

``````string = ""
lst = [ "Geeks" , "for" , "Geeks" ]
for i in lst:
string + = i
print (string)``````

``````lst = [ "Geeks" , "for" , "Geeks" ]
string = ''.join(lst)
print (string)``````

• 回顶