# Program to find number of optimal steps needed to reach destination by baby and giant steps in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of queries Q, where each query Q[i] contains a triplet [a_i, b_i and d_i]. Consider we are at position (0, 0) initially, then in one step we can move from some position (x1, y1) to (x2, y2) where Euclidean distance between these two points is at least a and at most b. Now for each queries we have to find minimum number of steps needed to reach (d_i, 0) from (0, 0).

So, if the input is like Q = [(2,3,1), (1,2,0), (3,4,11)], then the output will be [2, 0, 3] because for the first query from (0, 0) with a = 2 we can go $\left(\frac{1}{2},\frac{\sqrt{15}}{2}\right)$ then (1, 0) so we need two steps, so output is 2, for the next query d is 0, so we do not need to move any step so output is 0. And for the third one b = 4 and a = 3 move (0, 0) to (4, 0) then to (8, 0) then then (11, 0).

To solve this, we will follow these steps −

• Define a function steps() . This will take a, b, d
• mmin := minimum of a, b
• mmax := maximum of a, b
• if d is 0, then
• return 0
• if d is either mmin or mmax, then
• return 1
• if d < mmax, then
• return 2
• return the ceiling of (d / mmax)
• From the main method, do the following −
• res := a new list
• for each q in Q, do
• (a, b, d) := q
• insert result of steps(a, b, d) at the end of res
• return res

## Example

Let us see the following implementation to get better understanding −

from math import ceil

def steps(a, b, d):
mmin = min(a, b)
mmax = max(a, b)
if d is 0:
return 0
if d in [mmin, mmax]:
return 1
if d < mmax:
return 2
return ceil(d / mmax)

def solve(Q):
res = []
for q in Q:
a, b, d = q
res.append(steps(a, b, d))
return res

Q = [(2,3,1), (1,2,0), (3,4,11)]
print(solve(Q))

## Input

[(2,3,1), (1,2,0), (3,4,11)]

## Output

[2, 0, 2.0]
Updated on 11-Oct-2021 06:57:45