python - 如何处理从 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 个或更少的朋友”?
解决方案
您有缩进错误和无限循环。您可能还应该指定您想要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";
}
推荐阅读
- asp.net - ASP.NET MVC 身份检查和确认电子邮件确认(无效令牌)
- angularjs - Angular JS:找不到变量
- aws-lambda - 在无服务器框架中的多个 lambda 函数之间共享一些数据(如 dynamodb 表的文件名)的最佳方式是什么?
- codeigniter - 未定义的属性:mysqli
- excel - Excel VBA 从现有代码中保存多个工作表
- terraform-provider-azure - azurerm_app_service 创建并获取 IP 地址
- android - TypedArray 的背景颜色
- python - 如何在另一个 Django 模板变量中添加一个 Django 模板变量?
- c++ - Windows 7 和 10 是否需要不同的用户权限才能启动服务?
- ios - 在 UIProgressView 上设置最大值(swift 4)