Camel and Banana Puzzle solved using Python

Camel and Banana Puzzle solved using Python

3 min read

Original Statement

” A person has 3000 bananas and a camel. The person wants to transport maximum number of bananas to a destination which is 1000 miles away, using only the camel as a mode of transportation. The camel cannot carry more than 1000 bananas at a time and eats a banana every mile it travels. What is the maximum number of bananas that can be transferred to the destination using only camel (no other mode of transportation is allowed)? “

Since it is not possible to transport the bananas in a single run, the idea could be to use some checkpoints between the starting point and the destination where we will leave the bananas.

Note: Camel will not move until he has bananas.

As we have 3000 bananas we have to take 3 forward and two backward trips to transfer all the bananas to a checkpoint(say, A). Now we walk with 1000 bananas and walk towards A.Also Camel can’t move more than 500 miles forward and then backward due to its load capacity. There can be more than 1 checkpoint.

For detailed solution visit:-

Implementation in Python

total=int(input('Enter no. of bananas at starting'))
distance=int(input('Enter distance you want to cover'))
load_capacity=int(input('Enter max load capacity of your camel'))
for i in range(distance):
    while start>0:
#Here if condition is checking that camel doesn't move back if there is only one banana left.
        if start==1:
            lose=lose-1#Lose is decreased because if camel try to get remaining one banana he will lose one extra banana for covering that two miles.
#Here we are increasing lose because for moving backward and forward by one mile two bananas will be lose
#Here lose is decreased as in last trip camel will not go back.
    if start==0:#Condition to check whether it is possible to take a single banana or not.
Here it doesn’t matter if we increase no. of checkpoints in between because the total cost of bananas per mile at that section will remain same.
Explanation of the code

In the code above,
There would be one or more than one checkpoint. We are breaking each section of the checkpoint in the sections of length one.
Here transportation is done in 1-mile steps. As in the example discussed above, camel walks with 1000 bananas for 1 mile left 998 bananas there and consume 2. In the last round, the camel will consume only one banana.
At each subsequent mile, we are subtracting the no. of bananas lost in travelling each mile from the total no. of bananas. To calculate the total bananas left after 1 mile we use another variable start.

Choose your Reaction!
Leave a Comment