【发布时间】:2019-10-10 16:00:29
【问题描述】:
我很难理解 python 递归。我们遇到了一个问题,我这辈子都无法理解。
问题: 编写一个 python 程序,将解决方案打印到文本区域中提供的游戏板。文本区域中的数字创建了一个游戏板。示例:
|1|4|2|3|6|1|1|2|
要赢得比赛,您需要从头开始,准确地结束。您只能移动单元格中的数字,但只要您留在棋盘上,就可以向左或向右移动。
讨论: 所以从任何给定的位置,你可以向右走,也可以向左走。所以要求是: 1) 如果 index board length -- 返回游戏不能获胜 2) 如果单元格值为零,则游戏结束,除非它是棋盘上的最后一个单元格 3) 每个 Cell 只能被访问一次。
到目前为止我所拥有的:
def playGame(_currentIndex):
_path.append(_currentIndex)
print("Current Path --> ")
print(_path)
_currentIndex=_gameBoard[_currentIndex]
win = False
while win == False:
#Check Can win from current position directly?
if _currentIndex-1 or _currentIndex+1 == end:
print("Game can be won directly from current position!")
print(_path)
return True
#Check for Loss:
#Index Too High or Too Low
if _currentIndex < 0 or _currentIndex > end:
print("Game cannot be won")
exit(code = 0)
#Cell Value of Zero
elif _gameBoard[_currentIndex] == 0:
#If Cell Value Zero and Is Last Cell
if _currentIndex == end:
print("Game won!")
print(_path)
win = True
else:
print("Game cannot be won")
exit(code=0)
#Cell has been visited before
elif (_currentIndex in _path):
print("Game cannot be won")
exit(code = 0)
elif (playGame(-(_currentIndex))) or (playGame(-(_currentIndex))):
win = True
else:
win = False
使用 [1,1] 的游戏板时,我的递归深度超出了我的范围,但不知道为什么?
编辑---所以我理解递归,如果它只做一件事,例如:
def rec(int):
if int == 0:
return 0
else:
num = int + (int - 1)
print(num)
rec(int - 1)
rec(3)
这工作正常并打印出来: 5 3 1
但是如果我想通过加法或减法直到 int == 0 或 int == 10 来做到这一点呢?
【问题讨论】:
-
接近结尾的那一行是什么?
elif (playGame(-(_currentIndex))) or (playGame(-(_currentIndex))): -
基本上就是将索引向左或向右移动。我们得到的伪代码是:我从当前位置“可以赢”游戏如果我“可以赢”到右边或我“可以赢”到左边。 def canWin( ...current... ): # 代码返回 True 或 False 如果你能赢或不能赢直接在这里 if canWin(...left...) or canWin(...right...):返回 True 否则返回 False
-
if _currentIndex-1 or _currentIndex+1 == end:不正确。我不确定你打算在那里做什么,也许是if _currentIndex-1 == end or _currentIndex+1 == end:? -
@Fxguy1 仔细阅读,您正在测试
if X or X。 -
一般来说,
while variable == False:的风格很差。最好使用while True:,当你想停止循环时使用break。