Python program to find a series in an array consisting of characters

Here, we are going to learn how to find a series in an array consisting of characters using python program?
By Suryaveer Singh Last updated : January 14, 2024

In this article, we would learn weather our array contains a mentioned series or not like a, b, c or 1, 2, 3 etc.

Beginning with a simple question,

Question/Problem statement

We are given with an array of char, return True if the sequence of char a, b, c appears in the array somewhere.

Example

Array_abc(['a', 'x', 'a', 'b', 'c']) = True
Array_abc(['f', 'x', 'a', 'i', 'c', 't']) = True
Array_abc(['k', 'x', 'a', 'e', 'c']) = True

Code

def Array_abc(char):
    for i in range(len(char) - 2):
        if char[i] == 'a' and char[i + 1] == 'b' and char[i + 2] == 'c':
            return True
    return False


print (Array_abc(['a', 'x', 'a', 'b', 'c']))

Output

True

Explanation

Here one can easily be confused in the second line as we have taken range(len(char)-2), in almost all questions we use -1, but here we have used -2. This can be explained because with length-2, we can use i+1 and i+2 in the loop. As we have to find a sequence for three numbers.

Further, the code is very simple as we have to write an if statement to check the three conditions and if all the three conditions satisfied return True.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.