Codingame上的MIME类型提取

时间:2017-06-27 23:45:08

标签: python

我试图解决编码方面的难题:

目标是提取某些字符串的MIME类型 输入:

2
4
html text/html
png image/png
test.html
noextension
portrait.png
doc.TXT

输出:

text/html
UNKNOWN
image/png
UNKNOWN

到目前为止,我的代码运行顺畅但是在更长的列表中,我收到了一个错误,我的进程已超时。 任何人都可以暗示我吗?

我的代码:

import sys
import math

# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.

n = int(input())  # Number of elements which make up the association table.
q = int(input())  # Number Q of file names to be analyzed.
mime = dict(input().split() for x in range(n))
fname = [input() for x in range(q)]

# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)

for b in fname:
    if '.' not in b:
        print('UNKNOWN')
        continue
    else:    
        for idx, char in enumerate(reversed(b)):
            if char == '.':
                ext = b[len(b)-idx:]
                for k, v in mime.items():
                    if ext.lower() == k.lower():
                        print(v)
                        break
                else:
                    print('UNKNOWN')
                break

1 个答案:

答案 0 :(得分:0)

我不确定这是你的代码超时的原因,但迭代你的字典的键和值来对密钥进行不区分大小写的匹配总是会相对较慢。使用字典的主要原因是查找时间O(1)。如果你没有利用这一点,你最好使用一个元组列表。

幸运的是,修复你的dict并不难,这样你就可以使用索引而不是迭代来手动检查每个键。以下是对代码的相关更改:

# set up the dict with lowercase extensions
mime = {ext.lower(): tp for ext, tp in (input().split() for _ in range(n))}

fnames = [input() for x in range(q)] # changed the variable name here, plural for a list

for filename in fnames: # better variable name than `b`
    if '.' not in filename:
        print("UNKNOWN") # no need for continue
    else:
        _, extension = filename.rsplit('.', 1) # no need to write your own split loop
        print(mime.get(extension.lower(), "UNKNOWN")) # Do an O(1) lookup in the dictionary

除了更改字典创建和查找代码之外,我还简化了用于拆分扩展的代码,尽管我的方式仍然是O(N),就像你的那样{{1是文件名的长度。)