This article is an example of the Python rabbit poison problem. Share to everyone for your reference. The specific analysis is as follows:
The problem is roughly this: 1000 bottles of colorless and tasteless liquid, one of which is poison, the other is water, poison only take a drop and water mixed into a bottle can also poison rabbits. Now there are 10 rabbits, and when the rabbits die after two hours of poison, devise a plan to find the bottle of poison within 24 hours.
................ 2 minutes later.
Before the problem you must think clearly, then slightly change: 1000 bottles of colorless and tasteless liquid, one of the bottles of poison, all other is water, poison only take a drop and water mixed into a bottle can also poison rabbits. Now there are 10 rabbits, and when the rabbits die after 20 hours of poison, devise a plan to find the bottle of poison within 24 hours.
................ 2 minutes later.
There are a number of ways, such as I give rabbits every 5 minutes to drink 100 bottles of liquid mixed together things, according to the Rabbit's death sequence, it can be judged that the bottle.
There is no better way, I only provide a time optimal method, that is, in 20 hours to find this bottle of poison. Of course there can be dead rabbits at least, in the dead rabbit and time to find an optimal compromise point optimization problem.
The method is as follows:
Give 10 rabbits number 1-10, each rabbit represents a number, the list is as follows:
No. 1 2 3 4 5 ... 10
Number 1 2 4 8 16 ... 512
The bottles are numbered, followed by 1-1000. Oh, smart you should know what I want to do, but I will go on, and write Python code to achieve.
I want to be the number for y1,y2,y3 ... When the rabbit dies, you can push the export number to x bottle for poison. For example, the number of 1,2,4 Rabbit died, that the rabbit corresponding number for 1+2+8=11, is the number 11 bottle is poison. For example, the number of 1,4,10 Rabbit died, that the rabbit corresponding number for 1+8+512=521, is the number 521 bottle is poison.
The problem now is to know which bottles of liquid each rabbit is going to drink with a different number.
The Python code is as follows:
def main (): "" "" "
Baselist is the number of rabbits numbered from 1-10,
result is the final liquid for each rabbit to drink"
""
baselist=[ 1,2,4,8,16,32,64,128,256,512]
result=[[],[],[],[],[],[],[],[],[],[]] for
water in range (1,1001):
Watertmp=water for
i in range (9,-1,-1):
if (Watertmp-baselist[i]) >=0:
watertmp-= Baselist[i]
Result[i].append (water) for
I in range (1,11):
print "The Num%d Rabit need drink the next liquid"% i+1,result[ I]
pass
if __name__== "__main__":
Main ()
I hope this article will help you with your Python programming.