Teaching Kids Programming – First Number Equal or Larger Than Target using Next Function


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given an array of numbers and a Target, we want to find out the first number that is equal or larger than the target.

Linear Search O(N) time and O(1) space:

1
2
3
4
5
6
class Solution:
    def firstLargeEqualNumber(self, arr, target):
        for i in arr:
            if i >= target:
                return i
        return -1
class Solution:
    def firstLargeEqualNumber(self, arr, target):
        for i in arr:
            if i >= target:
                return i
        return -1

Python Iterator and Next Function

The next function takes two parameters, the first one is the iterator, and the second one is optionally the default value when the iterator is beyond the end. For example:

1
2
3
4
5
a = iter([1, 2, 3])
print(next(a)) # 1
print(next(a)) # 1
print(next(a)) # 3
print(next(a, 0)) # 0
a = iter([1, 2, 3])
print(next(a)) # 1
print(next(a)) # 1
print(next(a)) # 3
print(next(a, 0)) # 0

If a default value is not specified, and the iterator has reached the end, a subsequent next call will raise an exception namely StopIteration.

We can use iter function to convert a list to iterator, alternatively, we can use (x for x in …) to define an iterator.

1
2
3
class Solution:
    def firstLargeEqualNumber(self, arr, target):
        return next((x for x in arrif x >= target), -1)
class Solution:
    def firstLargeEqualNumber(self, arr, target):
        return next((x for x in arrif x >= target), -1)

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
328 words
Last Post: Batch Script to Convert MOV Videos to MP4/MPEG using ffmpeg
Next Post: Teaching Kids Programming - Build Progressive Stairs Row by Row via Simulation, Binary Search or Math Algorithm

The Permanent URL is: Teaching Kids Programming – First Number Equal or Larger Than Target using Next Function

Leave a Reply