首页 > 解决方案 > 如何处理从 Python 中的用户输入创建字典的时间或内存限制错误?

问题描述

我正在尝试解决编程硬件中的问题。用户输入姓名或姓名的首字母。重复的名字越多,一个人的朋友就越多。程序应该输出一个拥有最多朋友的人(如果有相同数量的朋友,他们中的任何一个都可以作为输出)。输入中的“END”一词不应计算在内。未指定用户输入的长度,但任务说:

“请在 6 秒内处理 50,000 个或更少的朋友。如果不使用 dict 使用 list 进行 O(n ^ 2) 处理,可能会判断错误答案超过时间限制?”。

我编写了一个程序,直接从用户输入创建字典并输出最大键值对。

#!/usr/bin/env python

friendships = {}
count = 0

while True:
    try:
    names = input()

    if names != 'END':

        if not friendships.get(names):
             friendships[names] = 1
        else:
            friendships[names] += 1 

    if names == '':
        break

except EOFError:
    print('ERROR')

max_key = max(friendships, key = friendships.get)
print(max_key, friendships[max_key])

自动评分器不断显示 [错误:超出时间限制或超出内存限制(我不知道是哪个)]。如何指定“应在 6 秒内处理 50000 个或更少的朋友”?

标签: pythondictionarymemory

解决方案


您有缩进错误和无限循环。您可能还应该指定您想要python3的 . 此外,在循环之前安装异常处理程序,而不是在每次迭代中重新安装它。用于pylint获得一些有价值的提示。

#!/usr/bin/env python3

'''
friendship program
'''

def main():
    '''
    a func
    '''
    friendships = {}

    try:
        while True:
            name = input()

            if name not in ['END', '']:
                if name not in friendships:
                    friendships[name] = 1
                else:
                    friendships[name] += 1
            else:
                break

    except EOFError as ex:
        print('ERROR ' + str(ex))

    max_key = max(friendships, key=friendships.get)
    print(max_key, friendships[max_key])

main()

虽然上面在 6 秒内处理 50000 个名称应该没有任何问题,但您可以尝试用另一种语言(如果您不必使用 python)做同样的事情,看看是否有帮助。一个 C++ 示例:

#include <iostream>
#include <unordered_map>
#include <algorithm>

int main() {
    std::unordered_map<std::string, unsigned long> friends;
    std::string name;
    while(std::cin >> name) {
        if(name == "END" || name.size() == 0) break;
        ++friends[name];
    }
    auto max_it = std::max_element(
        friends.begin(), friends.end(),
        [](const auto& a, const auto& b) { return a.second < b.second; });

    std::cout << max_it->first << " " << max_it->second << "\n";
}

推荐阅读