0

我有以下方法调用:

NCOLS = 3        
NPEGS = 4 

first_guess = []

print("calling first guess method")
first_guess = firstGuess(NCOLS, NPEGS, first_guess)
print("after method call: " + str(first_guess))

第一种猜测方法:

def firstGuess(NCOLS, NPEGS, first_guess):
"""Used for setting up the first guess of the game"""
  print("in firstGuess method")
  for c in range(1, NCOLS + 1):
     if len(first_guess) == NPEGS:
         print("about to return first guess: " + str(first_guess))
         return first_guess
     else:
         first_guess.append(c)

  print("out of for loop, first_guess len is " + str(len(first_guess)) + ", " + str(first_guess))
  if len(first_guess) <= NPEGS: #there were less color options than pegs
     firstGuess(NCOLS, NPEGS, first_guess)

None由于我无法弄清楚的原因,这似乎又回来了。

这是我的输出:

calling first guess method
in firstGuess method
out of for loop, first_guess len is 3, [1, 2, 3]
in firstGuess method
about to return first guess: [1, 2, 3, 1]
after method call: None
Traceback (most recent call last):
File "mastermind.py", line 323, in <module>
sys.exit(main())
File "mastermind.py", line 318, in main
playOnce()
File "mastermind.py", line 160, in playOnce
first_guess = first_guess + str(g[0][i])
TypeError: 'NoneType' object is not subscriptable

为什么它返回None而不是返回[1, 2, 3, 1]

4

3 回答 3

3

您遇到的问题是您的递归调用不返回其结果。

因此,它打印“out of for loop……”,然后进行递归调用。然后,该递归调用成功地返回了一些东西……但外部调用忽略了这一点并落在了最后,这意味着你得到了None.

return只需在调用之前添加一个firstGuess

print("out of for loop, first_guess len is " + str(len(first_guess)) + ", " + str(first_guess))
if len(first_guess) <= NPEGS: #there were less color options than pegs
   return firstGuess(NCOLS, NPEGS, first_guess)

这仍然会留下一条您不返回任何内容的路径(如果您“退出 for 循环”,然后len(first_guess) > NPEGS)......但是您没有任何逻辑可以在那里做任何有用的事情。您可能想要添加某种,assert或者raise如果您认为这永远不会发生。

于 2013-04-17T22:14:33.497 回答
0

这是因为通过您的代码的路径不会以您显式返回任何内容而结束。

你在哪里firstGuess递归调用,你应该做什么return firstGuess(...)?但是,仍然存在您失败并且不返回任何东西的情况。您应该在最终return first_guess声明之后添加最终if声明。

尝试这个:

def firstGuess(NCOLS, NPEGS, first_guess):
  """Used for setting up the first guess of the game"""
  print("in firstGuess method")
  for c in range(1, NCOLS + 1):
     if len(first_guess) == NPEGS:
         print("about to return first guess: " + str(first_guess))
         return first_guess
     else:
         first_guess.append(c)

  print("out of for loop, first_guess len is " + str(len(first_guess)) + ", " + str(first_guess))
  if len(first_guess) <= NPEGS: #there were less color options than pegs
     return firstGuess(NCOLS, NPEGS, first_guess)
  return first_guess
于 2013-04-17T22:12:31.330 回答
0

将最后两行更改为

if len(first_guess) <= NPEGS: #there were less color options than pegs
    return firstGuess(NCOLS, NPEGS, first_guess)
else:
    # what do you do here?  return something
    return first_guess

您不会在所有分支机构返回

于 2013-04-17T22:12:56.113 回答