商人过河问题的Python实现

# -*- coding: cp936 -*-
#定义允许存在的状态集合
def allowexistset():
    merchants=int(raw_input("请输入商人数: "))
    slivers=int(raw_input("请输入随从数: "))
    allowset=[]
    for i in range(merchants+1):
        for j in range(slivers+1):
            #商人数为0
            if i==0:
                allowset.append([i,j])
            #全部商人在一起
            elif i==merchants:
                allowset.append([i,j])
            #一岸商人数大于等于随从数,并且要保证另一岸商人数大于等于随从数
            elif i>=j and ((merchants-i)>=(slivers-j)):
                allowset.append([i,j])
                #print allowset
    return allowset,merchants,slivers
"""
运行返回结果:
>>> allowexistset()
请输入商人数: 3
请输入随从数: 3
[[0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [2, 2], [3, 0], [3, 1], [3, 2], [3, 3]]
"""

#定义允许行动集合
def allowmoveset(merchants,slivers):
    boat_num=int(raw_input("请输入船的最大承载人数: "))
    allowacset=[]
    for i in range(merchants+1):
        for j in range(slivers+1):
            if (i+j)<=boat_num:
                allowacset.append([i,j])
    allowacset.pop(0)
    return allowacset
"""
运行返回结果:
>>> allowset,merchants,slivers=allowexistset()
请输入商人数: 3
请输入随从数: 3
>>> allowactionset(merchants,slivers)
请输入船的最大承载人数: 2
[[0, 1], [0, 2], [1, 0], [1, 1], [2, 0]]
"""

#开始行动啦
def move(merchants,slivers):
        k=1#设定初始移动次数
        current=[merchants,slivers]#设定此岸初始状态
        current1=[0,0]#设定对岸初始状态
        #首先从所有的allowacset 里面随机选取一个行动方案进行执行
        import random
        move=random.choice(allowacset)
        #将move集合列表的两个元素拆分为商人数和随从数
        #测试一下行动后是否处于安全状态,这里先假设一个
        trys=[current[0]+((-1)**k)*move[0],current[1]+((-1)**k)*move[1]]
        #如果执行了行动后的状态属于allowset,则更新current
        print "第" ,k ,"次行动:"
        while current!=[0,0] and current1!=[3,3]:
            if trys in allowset:
                current[0]=current[0]+((-1)**k)*move[0]
                current[1]=current[1]+((-1)**k)*move[1]
                current1[0]=current[1]-((-1)**k)*move[0]
                current1[1]=current[1]-((-1)**k)*move[1]
                
                if k %2 ==1:
                    print [move[0],move[1]],"到对岸"
                    print current

                else:
                    print [move[0],move[1]],"返回本岸"
                    print current
            else:
                continue
       
            k+=1
            

你可能感兴趣的:(数学算法)