【发布时间】:2019-02-09 17:57:20
【问题描述】:
我正在尝试为uvaonlinejudge 上的 3n + 1 问题找到一个有效的解决方案。我的代码使用字典进行记忆。任何人都可以提出有助于缩短此代码执行时间的改进吗?目前,我在提交代码时收到“超出时间限制”错误。如果有人对此问题有有效的解决方案,请与我分享。请不要将此帖子标记为重复。我已经在 * 上看到了 this 和其他人的帖子,但他们没有回答此处发布的问题。我的代码如下:
import sys
def recCycleLength(n,cycLenDict):
if n==1:
return 1
if n not in cycLenDict:
if n%2==0:
cycLen = recCycleLength(n//2, cycLenDict)
cycLenDict[n] = cycLen + 1
return cycLen+1
else:
cycLen = recCycleLength(3*n+1, cycLenDict)
cycLenDict[n] = cycLen + 1
return cycLen+1
else:
return cycLenDict[n]
def maxCycle(a, b):
i = a
mydict = {}
maxLength = 1
while i <= b:
m = recCycleLength(i, mydict)
if m > maxLength:
maxLength = m
i = i + 1
return maxLength
for line in sys.stdin:
curr_line=line.split()
num1 = int(curr_line[0])
num2 = int(curr_line[1])
if num1>num2:
num1, num2 = num2, num1
m = maxCycle(num1, num2)
print("{} {} {}".format(num1, num2, m))
【问题讨论】:
-
如果您有可行的解决方案,请改用codereview.stackexchange.com。
-
可以讨论:OP不想提高可读性,而是提高速度。
-
如果您提交,请在问题中提供输入。我尝试在页面中输入示例,速度非常快。所以我错过了一些东西。
-
uvaonlinejudge 不向用户提供运行提交代码的测试用例。示例输入只是为了让用户可以在提交之前测试他们的代码是否有错误。
标签: python optimization