python字典在一些OJ题上的妙用

字典是一个无序的数据集合,字典所有元素放在一对花括号"{}"中,Python中使用键(key)-值(value)存储,每个键值对之间用逗号分隔开。用python解算法和思维题经常会用到字典。本文缓慢更新其在题目中经常出现的解法。

文章标题

  • 1.计数
  • 2.结合lambda匿名函数

1.计数

无论在文本分析还是做题时用来统计数字/字符出现次数经常用到字典。

核心代码

d={
     }
for item in ls:
	d[item]=d.get(item,0)+1

其中dict.get(key, default=None)返回指定键的值,如果键不在字典中返回默认值 None 或者设置的默认值。

或者调用库

from collections import Counter
cnt=Counter(ls)

举例

ls=[1,2,3,4,5,4,3,4,4,3,4,5,6,7,3,2,4]
d={
     }
for item in ls:
	d[item]=d.get(item,0)+1
print(d)
"""{1: 1, 2: 2, 3: 4, 4: 6, 5: 2, 6: 1, 7: 1}"""
from collections import Counter
ls=[1,2,3,4,5,4,3,4,4,3,4,5,6,7,3,2,4]
cnt=Counter(ls)
print(cnt.items())
"""dict_items([(1, 1), (2, 2), (3, 4), (4, 6), (5, 2), (6, 1), (7, 1)])"""
print(cnt)
"""Counter({4: 6, 3: 4, 2: 2, 5: 2, 1: 1, 6: 1, 7: 1})"""

2.结合lambda匿名函数

根据key值排序

ls=[4,3,6,4,2,3,6,7,5,4,7,8,9,2]
d={
     }
for item in ls:
	d[item]=d.get(item,0)+1
d=sorted(d.items(),key=lambda x:x[0])
print(d)
"""[(2, 2), (3, 2), (4, 3), (5, 1), (6, 2), (7, 2), (8, 1), (9, 1)]"""

根据values值排序

ls=[4,3,6,4,2,3,6,7,5,4,7,8,9,2]
d={
     }
for item in ls:
	d[item]=d.get(item,0)+1
d=sorted(d.items(),key=lambda x:x[1])
print(d)
"""[(5, 1), (8, 1), (9, 1), (3, 2), (6, 2), (2, 2), (7, 2), (4, 3)]"""

从最小的values值选取最小的key值

ls=[4,3,6,4,2,3,6,9,5,4,5,8,7,2]
d={
     }
for item in ls:
	d[item]=d.get(item,0)+1
d=sorted(d.items(),key=lambda x:(x[1],x[0]))
print(d)
"""[(7, 1), (8, 1), (9, 1), (2, 2), (3, 2), (5, 2), (6, 2), (4, 3)]"""

拿一道水题举例
There is a game called “Unique Bid Auction”. You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don’t have to do it to solve this problem).

Let’s simplify this game a bit. Formally, there are n participants, the i-th participant chose the number ai. The winner of the game is such a participant that the number he chose is unique (i. e. nobody else chose this number except him) and is minimal (i. e. among all unique values of a the minimum one is the winning one).

Your task is to find the index of the participant who won the game (or -1 if there is no winner). Indexing is 1-based, i. e. the participants are numbered from 1 to n.

You have to answer t independent test cases.

Input
6
2
1 1
3
2 1 3
4
2 2 2 3
1
1
5
2 3 2 4 2
6
1 1 5 5 4 4
Output
-1
2
4
1
2
-1

题目大意
找只出现过一次的数的位置,有多个值就输出最小的,没有答案返回-1

for _ in range(int(input())):
    number=int(input())
    ls=list(map(int,input().split()))
    d={
     }
    for word in ls:
        d[word]=d.get(word,0)+1
    d=sorted(d.items(),key=lambda k:(k[1],k[0]))
    if d[0][1]==1:
        print(ls.index(d[0][0])+1)
    else:
        print(-1)

你可能感兴趣的:(python字典在一些OJ题上的妙用)