【发布时间】:2018-09-10 23:00:41
【问题描述】:
我正在参加 Google foo.bar 挑战,我编写了这个 python 代码来回答它。问题是当输入数字超过 16 位时,答案总是不可能返回。这对我来说似乎很清楚,这是不正确的,因为当我测试数字时,我发现一些输入数字和重复次数中有重复,其中添加另一个数字将始终返回另一个位值数字。
例如:
输入 3 和 94 将返回 33
输入 3 和 994 将返回 333
输入 3 和 99999999994 将返回 33333333333
输入 3 和 99999999999999994 将返回“不可能”
我不明白为什么超过一定数量的地方会在我的代码中返回“不可能”。
此代码将两个最大为 10^50 的随机数作为字符串作为输入,表示为 M 和 F。使用这些数字,您必须找到达到这两个数字所需的最少循环数。每个循环执行 F 功能或 M 功能。 F 函数等于 currentFnum + currentMnum,M 函数等于 currentMnum + currentFnum。
例如,如果您有 3 M 和 2 F,您可以得到 5 M 和 2 F 或 3 M 和 5 F。
def answer(M, F):
count = 0
currentM = int(M)
currentF = int(F)
listCycleType = []
def getGreater(currentF, currentM):
if currentM > currentF:
greater = [currentM, "M"]
return greater
elif currentM == currentF:
greater = [currentM, "M"]
return greater
else:
greater = [currentF, "F"]
return greater
def getLesser(currentF, currentM):
if currentM < currentF:
lesser = [currentM, "M"]
return lesser
elif currentM == currentF:
lesser = [currentM, "M"]
return lesser
else:
lesser = [currentF, "F"]
return lesser
greater = getGreater(currentF, currentM)
lesser = getLesser(currentF, currentM)
for x in range(1000000):
greater = getGreater(currentF, currentM)
lesser = getLesser(currentF, currentM)
if currentF > 1 and currentM > 1 and currentF == currentM:
return "impossible"
if currentM < 1 or currentF < 1:
return "impossible"
if currentM == 1:
count = count + currentF - 1
return str(count)
elif currentF == 1:
count = count + currentM - 1
return str(count)
yes = float(greater[0]) / lesser[0]
if not yes.is_integer():
yes = greater[0] / lesser[0]
count = count + yes
if greater[1] == "M":
currentM = currentM - yes * currentF
continue
else:
currentF = currentF - yes * currentM
continue
if greater[1] == "M":
currentM = currentM - currentF
count = count + 1
elif greater[1] == "F":
currentF = currentF - currentM
count = count + 1
else:
currentM = currentM - currentF
count = count + 1
if currentM == 1 and currentF == 1:
return str(count)
return "impossible"
print answer("3", "99999999999999994")
【问题讨论】:
-
为什么不能调试?跟随代码的执行。第一步是更改
return语句,以便您可以看到返回的是哪个"impossible"。 -
我刚刚检查过,它在最后一个 return 语句中失败了。这意味着代码循环了 1000000 次并且没有找到解决方案。我试过增加循环的数量,但没有任何效果。无论如何,我认为它不应该循环那么多次。
-
在你的代码中放一个随机的大数字并希望它能工作似乎不是一个好主意,而且会在某个时候中断。目前我们不能说更多,因为您实际上并没有描述您的代码在您的问题中应该做什么。
-
更新:我认为它与浮点数和浮点数的数字长度或类似的东西有关。
标签: python function loops combinations