Skip to content

How to Perform Frog Jumping in Python

The challenge

You have an array of integers and have a frog at the first position

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

The integer itself may tell you the length and the direction of the jump

For instance:

2 = jump two indices to the right -3 = jump three indices to the left 0 = stay at the same position
Code language: plaintext (plaintext)

Your objective is to find how many jumps are needed to jump out of the array.

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

Example:

array = [1, 2, 1, 5]; jumps = 3 (1 -> 2 -> 5 -> <jump out>)
Code language: plaintext (plaintext)

The solution in Python code

Option 1:

def solution(a): if not a: return -1 posSet, i = set(), while i not in posSet: posSet.add(i) i += a[i] if not ( <= i < len(a)): return len(posSet) return -1
Code language: Python (python)

Option 2:

def solution(a): steps = index = length = len(a) indexes = set() while <= index < length: if index in indexes: return -1 indexes.add(index) index += a[index] steps += 1 return steps
Code language: Python (python)

Option 3:

def solution(a): c = i = while i >= and i < len(a) and c<20 : i += a[i] ; c += 1 return [c,-1][c==20]
Code language: Python (python)

Test cases to validate our solution

import test from solution import solution @test.describe("Sample tests") def _(): @test.it("Tests") def __(): test.assert_equals(solution([1, 2, 2, -1]), 4) test.assert_equals(solution([1, 2, 1, 5]), 3) test.assert_equals(solution([1, -1]), -1)
Code language: Python (python)

See also  How to Append a Python Dictionary to a Pandas DataFrame
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x