Check if the given number K is enough to reach the end of an array in Python



Suppose we have an array nums and another value k. We have to check whether it is possible to reach the end of the array by performing these operations or not Operation: Traverse nums and, if any non-prime value is there then decrement the value of k by 1. Now if any value is prime then refill the value of k to its initial value.

So, if the input is like nums = [8, 5, 6, 7, 8], k = 2, then the output will be True as nums[0] is not prime, then make k = 1, then nums[1] is prime so k = 2, then nums[2] is not prime so k = 1, again nums[3] is prime so k = 2 and finally nums[4] is not prime and k = 1 and we are at last index.

To solve this, we will follow these steps −

  • temp := k
  • for i in range 0 to size of arr - 1, do
    • if arr[i] is prime, then
      • k := temp
    • otherwise,
      • k := k - 1
    • if k <= 0 and i < size of arr - 1 and arr[i + 1] is not prime, then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def isPrime(num):    if num > 1:       for i in range(2, num):          if num % i == 0:            return False       return True    return False   def solve(arr,k):    temp = k    for i in range(len(arr)):       if isPrime(arr[i]):          k = temp           else:          k -= 1                 if k <= 0 and i < (len(arr) - 1) and isPrime(arr[i + 1]) == False:          return False              return True nums = [8, 5, 6, 7, 8] k = 2 print(solve(nums, k))

Input

[8, 5, 6, 7, 8], 2

Output

True
Updated on: 2021-01-15T06:52:11+05:30

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements