问题是要编写一个程序来解决青蛙和蟾蜍的难题,这个特定的程序必须使用递归函数,因此它必须没有for/while循环。谜题基本上是左边的青蛙和右边的蟾蜍,这两组被一个空格隔开,获胜的状态是所有蟾蜍都在左边,青蛙在右边,空格再次位于两者之间。程序的预期结果是,用户输入他们想要的青蛙和蟾蜍的数量后,程序将显示拼图的初始状态,然后通过递归打印已解决的拼图,但从已解决状态打印到初始状态,即:
|Toad|Toad|Frog| |
|Toad| |Frog|Toad|
|Toad|Frog| |Toad|
| |Frog|Toad|Toad|
|Frog| |Toad|Toad|
def make_state(num_frogs, num_toads):
state=['Frog']*num_frogs+['']+['Toad']*num_toads
return state
def find_space(state):
return state.index('')
def is_frog(state, index):
if state[index]=='Frog':
return True
else:
return False
def is_toad(state, index):
if state[index]=='Toad':
return True
else:
return False
def move(state, index):
newState=list(state)
newState[newState.index('')]=newState[index]
newState[index]=''
return newState
def print_state(state):
print(*state,sep='|')
def is_win(state):
if state==state[::-1]:
return True
else:
return False
def solvable(state):
if is_win(state) == True:
print(state)
return True
elif is_win(state) == False:
return False
else:
N=find_space(state)
if is_frog(state,N-1):
newState=move(state,N-1)
print(newState)
return solvable(newState)
elif is_frog(state,N-2):
newState=move(state,N-2)
print(newState)
return solvable(newState)
elif is_toad(state,N-1):
newState=move(state,N-1)
print(newState)
return solvable(newState)
elif is_toad(state,N-2):
newState=move(state,N-2)
print(newState)
return solvable(newState)
else:
print('False')
def main():
num_frogs=int(input('Enter the number of frogs: \n'))
num_toads=int(input('Enter the number of toads: \n'))
print()
print('Here is the intial state:')
state=make_state(num_frogs,num_toads)
print_state(state)
print()
print('Here is the solution (in reverse):')
print(solvable(state))
main()```
I have tried changing the solvable function() to be able to print the expected outcome but the actual outcome that I get is always False.
在比较False、True或None时,应始终使用
is
看看这个试试吧
但那不是你的问题。。。win返回的是真还是假。。。因此,除了前两个if语句之外,没有其他语句是可访问的(例如,在else中没有任何语句被命中)
相关问题 更多 >
编程相关推荐