您的位置:首页 > 其它

hackerrank DefaultDict Tutorial

2017-11-10 12:01 253 查看
题目:https://www.hackerrank.com/challenges/defaultdict-tutorial/problem

题意:给你n个字符串,然后输入m个字符串ask,对于每个ask输出其位置

思路:defaultdict就相当于C++的map(怎么那么多类似的…),然后可以放各种东西,用来统计

dict[key]:如果访问不存在的key,会有KeyError

dict.get(key):如果不存在的key,会返回None

dict.has_key():不存在返回False

代码:

'''
-*- coding: utf-8 -*-
@Author  : PlayerGuan
@Time    : 2017/10/14 23:12
@Software: PyCharm Community Edition
@File    : main.py
'''

from collections import defaultdict

n,m = map(int,input().split())

d = defaultdict(list)
for i in range(n):
s = input()
d[s].append(i+1)

for i in range(m):
x = input()
if x in d:
print(' '.join(map(str,d[x])))
else:
print(-1)


看评论发现if好像没什么用了…

for i in range(m):
x = input()
print(' '.join(map(str,d[x])) or -1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: