题目:一农夫带着一头狼,一只羊和一担草过河,小船只能一次装载农夫和一样货物,狼会吃羊,羊会吃草,只有农夫在时才安全。现欲让所有物品包括农夫都安全过道河对岸,使用程序实现求解。
学习完毕《Python编程:从入门到实践》一书,掌握的代码知识不是很多,看到这题偶然有了兴致,试着依靠书本内容完成该题目。代码水平低下,希望各位大佬不要介意,也非常感谢大家能够批评指正!
代码段
from random import choice
left = ['W','S','V']
right = []
ship = []
wosh = {'W','S'}
shve = {'S','V'}
# 检测程序,检测羊与狼、菜与羊的共存状态
def dect_program(det_list):
if wosh.issubset(det_list) or shve.issubset(det_list):
return True
else:
return False
# 函数1:从岸边取动物时保证岸上的动物能够共存
def load_ship(land_list,ship_list):
global goods_1
land_renew = land_list[:]
while dect_program(land_renew):
land_renew = land_list[:]
goods_1 =choice(land_renew)
land_renew.remove(goods_1)
land_list.remove(goods_1)
ship_list.append(goods_1)
print(f'transport {goods_1} to right')
# 函数2:判断船上的物品运送到对岸后,是否可以在对岸相互共存,如不能,则在对岸运输回导致无法共存的物品。
def sec_load_ship(land_list,ship_list,add_list,left_list):
global goods_2
land_renew = land_list[:]
add_renew = add_list[:]
while dect_program(add_renew):
add_renew = add_list[:]
goods_2 = choice(land_renew)
add_renew.remove(goods_2)
land_list.remove(goods_2)
left_list.append(goods_2)
print(f'transport {goods_2} come back')
#卸载船上的货物到岸边
def unstall_ship(ship_list,land_list):
global goods_3
goods_3 = ship_list[0]
land_list.append(goods_3)
ship_list.clear()
#运输程序
def transport(fst_land,ship_list,sec_list):
global fst_current
if len(fst_land) <= 2: #判断左岸是否已经运输一次货物,已经运输了货物。则执行以下程序
goods_5 = choice(fst_current) #随机从左岸挑选一次货物进行运输
fst_land.remove(goods_5)
ship_list.append(goods_5)
print(f'transport {goods_5} to right')
if dect_program(fst_land): #判断左按是否为共存状态,如是,则执行函数1
load_ship(fst_land,ship_list)
ship_renew = ship_list[:] #在运送完毕前设置临时列表,目的是保证不会将刚运输的货物,再次运输
rs_list = ship_list[:] + sec_list[:]
fst_current = fst_land[:]
if dect_program(rs_list) and len(rs_list) != 3: #判断船上与对岸货物状态,若存在无法共存,且未运输完毕。执行函数2
sec_load_ship(sec_list,ship_list,rs_list,fst_land)
elif len(rs_list) == 3: #判断船上与对岸货物状态,若可以运输完毕,进行卸货
unstall_ship(ship_list,sec_list)
else:
print('empyty come back') #若船上货物与对岸货物可以共存,则空船返回
if len(sec_list) !=3: #判断货物运输并进行卸货
unstall_ship(ship_renew,sec_list)
ship_list.clear()
while len(right) != 3:
transport(left,ship,right)
print(f'left land is {left}')
print(f'right land is {right}n')
结果
transport S to right empyty come back left land is ['W', 'V'] right land is ['S'] transport W to right transport S come back left land is ['V', 'S'] right land is ['W'] transport V to right empyty come back left land is ['S'] right land is ['W', 'V'] transport S to right left land is [] right land is ['W', 'V', 'S']
通过这个题目,我对while循环、if循环的用法加深了印象。
并且,也感受到,通过建立临时列表方式,解决一些问题。



