A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page is always on the right side:
When they flip page 1 , they see pages 2 and 3. Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n pages long, and a student wants to turn to page p, what is the minimum number of pages to turn? They can start at the beginning or the end of the book. Given n and p , find and print the minimum number of pages that must be turned in order to arrive at page p .
Interesting Question it was, it took me around 2 days to figure out a very simple solution. Initially I was trying to unnecessary create a complex but I went throught the discussion section of this problem, it had a very simple, understandable solution to it.
As per Question we needed to find the minimum number of pages required to turn to reach to the p page from forward direction or backward direction.
I am using a variable front to store the number of pages turned to reached p page by dividing the number by two for obvious reasons.
if n%2==1: #step-2
The real catch or the failing edge case is present for backward direction counting in which if total number of pages is even and the required or “p” page is odd step-3 command will fail for that we will need to add 1 in (n-p) as shown in step-4.
For example-if n=6 and p=5,then (n-p)//2=(6–5)//2=1/2=0.5 i.e 0.
as we know,6 lies on the next page, so to reach 5 we will need to turn 1 page from back, so step-3 fails in such cases
so we add 1 in (n-p) to counter attack this scenario which will become (n-p+1)//2=(6–5+1)//2=1.
There will be times when you feel stuck at some point ,remember to ask for help. As Dumbledore always said….