The right way to Carry out Frog Leaping in Python

0
9
Adv1


Adv2

The problem

You’ve an array of integers and have a frog on the first place

[Frog, int, int, int, ..., int]

The integer itself might inform you the size and the route of the bounce

For example:

 2 = bounce two indices to the precise
-3 = bounce three indices to the left
 0 = keep on the identical place

Your goal is to seek out what number of jumps are wanted to leap out of the array.

Return -1 if Frog can’t bounce out of the array

Instance:

array = [1, 2, 1, 5]; 
jumps = 3  (1 -> 2 -> 5 -> <bounce out>)

The answer in Python code

Choice 1:

def answer(a):
    if not a: return -1
    posSet, i = set(), 0
    whereas i not in posSet:
        posSet.add(i)
        i += a[i]
        if not (0 <= i < len(a)):
            return len(posSet)
    return -1

Choice 2:

def answer(a):
    steps = 0
    index = 0
    size = len(a)
    indexes = set()
    whereas 0 <= index < size:
        if index in indexes:
            return -1
        indexes.add(index)
        index += a[index]
        steps += 1
    return steps

Choice 3:

def answer(a):
    c = i = 0
    whereas i >= 0 and that i < len(a) and c<20 : i += a[i] ; c += 1
    return [c,-1][c==20]

Take a look at circumstances to validate our answer

import take a look at
from answer import answer

@take a look at.describe("Pattern checks")
def _():
    @take a look at.it("Exams")
    def __():
        take a look at.assert_equals(answer([1, 2, 2, -1]), 4)
        take a look at.assert_equals(answer([1, 2, 1, 5]), 3)
        take a look at.assert_equals(answer([1, -1]), -1)
Adv3