Tuesday, April 23, 2024
HomeSoftware EngineeringLearn how to Carry out Frog Leaping in Python

Learn how to Carry out Frog Leaping in Python


The problem

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

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

The integer itself could inform you the size and the course of the bounce

For example:

 2 = bounce two indices to the correct
-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

Possibility 1:

def resolution(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

Possibility 2:

def resolution(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

Possibility 3:

def resolution(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]

Check circumstances to validate our resolution

import take a look at
from resolution import resolution

@take a look at.describe("Pattern exams")
def _():
    @take a look at.it("Assessments")
    def __():
        take a look at.assert_equals(resolution([1, 2, 2, -1]), 4)
        take a look at.assert_equals(resolution([1, 2, 1, 5]), 3)
        take a look at.assert_equals(resolution([1, -1]), -1)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments