首页 > 解决方案 > Python:Google Kickstart 2020 中的运行时错误 - A 轮

问题描述

我正在尝试使用 Python 3.7 解决 Google Kickstart 2020 第 A 轮的问题。我通过了除“捆绑”之外的所有问题。我的算法通过了样本,但测试失败并出现运行时错误。我还用我用一个简单的脚本构建的大型测试用例对其进行了测试,它可以工作,没有出现任何类型的异常。

我还认为,由于我在我的机器上使用 Python 3.8,而 Google 用 3.7 测试脚本,这可能是重点……但我无法在我的代码中发现任何错误。这是我的代码:

ans = 0
class Node:
    def __init__(self):
        self.children = {}
        self.count = 0
    
    def insert(node, key):
        for char in key:
            idx = char
            if idx not in node.children:
                node.children[idx] = Node()
            node = node.children[idx]
            
        node.count +=1

    def resetAns(self):
        global ans
        ans = 0

    def dfs(self, dep=0, k=0):
        global ans
        for c in self.children:
            self.children[c].dfs(dep+1, k)
            self.count+=self.children[c].count
        while self.count >= k:
            self.count -= k
            ans+=dep
        return ans

def bundling():
    N, K = map(int, input().split())
    _node = Node()
    _node.resetAns()
    for _ in range(0, N):
        _v = input()
        _node.insert(_v)
    return _node.dfs(0, K)            

for _ in range(int(input())):
    print("Case #{}: {}".format(_, bundling()))

欢迎任何帮助:D

标签: pythonalgorithmtime-complexityruntime-error

解决方案


由于 python 提供的默认递归深度限制较小,因此出现此问题。您可以使用以下代码明确设置限制。

import sys 
sys.setrecursionlimit(10**6)

推荐阅读