簡體   English   中英

如何處理在Python中根據用戶輸入創建字典的時間或內存限制錯誤?

[英]How to handle time or memory limit error creating dictionary from user input in Python?

我正在嘗試解決硬件編程中的問題。 用戶輸入名稱或名稱的首字母。 重復的名字越多,一個人擁有的朋友越多。 該程序應輸出一個擁有最多朋友的人(如果有相同數量朋友的人,則可以輸出任何人)。 輸入中的單詞“ END”不計在內。 用戶輸入的長度未指定,但是任務說明如下:

“請在6秒內處理50,000個或更少的朋友。如果您使用列表而不使用dict進行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";
}

要確定是否是您的內存已用完,請使用memory_profiler庫。 您可以使用@profile裝飾器,該裝飾器會將每行的內存使用量輸出到stdout。

我不認為您甚至可以在6秒內使for循環從1到50000運行,但是一種好的啟動方法是查找給定輸入名稱的字典,如果查找成功則遞增,否則,添加KV對。

您無法指定某項內容需要花費多長時間,而只能盡可能地對其進行編碼並查看。 Python實際上也沒有提供限制時間或內存使用的功能。 我懷疑此分級工具使用的是某種容器。

但是我可以看到一個問題:

names = input()

任何人都很難在六秒鍾內輸入50,000個名字! 即使可以,平地機也允許交互式輸入嗎?

相反,您應該預創建朋友列表(可能只是作為文本文件),然后將其讀入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM