Python - Kth Valid String


Strings are important data types in any programming language. They are sequences of characters. Finding kth valid String is a programming technique in which we need to find the kth element out of a list of elements which is a valid String. In this article we will understand several methods like brute force, using list comprehensions and enumerate objects, filter method etc. We will also see how to use the Pandas library to deal with the same.

Understanding The Problem Statement

We will have list and the value of k as the input:

list: ["", "orange", "75", "apple"]
k: 2

Now our task is to find the kth valid String. In the list “” is not a valid String(not defined), "orange" is valid String, “75” contains a number, “apple” is valid String. Hence the kth=2nd valid String=”apple”.

Output: apple

Using The Iteration

One of the most simplest ways to find the kth valid String would be the brute force method. In this method we can simply iterate over the list of elements and for each iteration we can check if the element present is a valid String. We can keep a track of the number of valid Strings. If during the iteration we reach the kth valid String we can break the loop.

Example

In the following code we have first created the function named find_kth_valid_string, which takes the string and the value of k as the parameters. Next we initialized a variable named count to keep a track of the number of valid Strings in the list. Next we used the for loop to iterate through the list and for each iteration if the element is a valid String we have incremented the value of the variable 'count'. We have placed a condition that if the value of the variable − 'count' reaches 'k' then we need to break the loop.

def find_kth_valid_string(strings, k):
    count = 0
    for string in strings:
        if is_valid(string):
            count += 1
            if count == k:
                return string
    return None
def is_valid(string):
    return string.islower() and isinstance(string, str)
strings = ["", "def", "123", "xyz"]
k = 2
print(find_kth_valid_string(strings=strings, k=k))

Output

xyz

Using Filter Method

Filter method is popular among the Python programmers to select elements out of any iterable data types using certain conditions. It proves to be handy when we need to apply only a few conditions. Usually we use lambda functions with it to make the code more comprehensive. It takes two parameters, namely the name of the function and the iterable object.

filter(function, iterable object)

The function is the name of the function which should be applied to all the elements of the iterable object. the iterable object is the iterable on which the function should be applied. It will return the masked object containing boolean True or False at each index.

Example

In the following example we have used the filter method where we passed two parameters namely "is_valid" and the string. The is_valid function is a custom function which checks if the element is of String data type. We have checked if the length of the valid Strings is less than 'k'. If it is True then we returned the kth valid String through indexing.

def find_kth_valid_string(strings, k):
    valid_strings = list(filter(is_valid, strings))
    if k <= len(valid_strings):
        return valid_strings[k - 1]
    else:
        return None

def is_valid(string):
    return isinstance(string, str) and string.islower() 

strings = ["", "","pqr", "123", "xyz", "gh"]
k = 3
print(f"The kth valid String in the list is: {find_kth_valid_string(strings=strings, k=k)}")

Output

The kth valid String in the list is: gh

Using List comprehension And Enumerate Object

List comprehension is a technique to append the elements for a list using certain expressions and statements. This proves to be very handy when we want to combine multiple short expressions into a single line.

The enumerate on the other hand is an in−built function of Python which returns an enumerated object containing the index and element of an iterable object. Each item of the enumerated object is a tuple containing the index and the element of the iterable object.

Example

In the following example we have used the list comprehension to create the valid Strings. We have created a custom function called is_valid which takes the Strings and returns whether it is valid String. We have used the function with the list comprehension to check whether the elements of the lists are valid String. If the length of the valid String list is more than k we return the kth valid String.

def find_kth_valid_string(strings, k):
    valid_strings = [string for _, string in enumerate(strings) if is_valid(string)]
    if k <= len(valid_strings):
        return valid_strings[k - 1]
    else:
        return None

def is_valid(string):
    return isinstance(string, str) and string.islower() 

strings = ["", "", "pqr", "123", "xyz", "gh","word", "hello"]
k = 4
print(f"The kth valid String in the list is: {find_kth_valid_string(strings=strings, k=k)}")

Output

The kth valid String in the list is: word

Use Method Of The Pandas Library

Pandas is a popular data manipulation and processing library in Python. Pandas deals with data frames. We can apply lots of functions and methods to the data frames. One such important method is the 'apply' method which applies a function to all the elements of the data frame. For our use case we can create a function that can check if an element is a valid String and apply to all the elements of the data frame.

Example

In the following code we imported the pandas library. Next we created a data frame out of the String using the 'DataFrame' function of Pandas. We used the apply method to the data frame to check if the elements of the DataFrame are valid Strings. Next we used the 'tolist()' method to convert the sequence into a list and returned the kth valid String if it exists.

import pandas as pd

def find_kth_valid_string(strings, k):
    df = pd.DataFrame(strings, columns=['string'])
    df['valid'] = df['string'].apply(is_valid)
    valid_strings = df[df['valid']]['string'].tolist()
    return valid_strings[k - 1] if k <= len(valid_strings) else None

strings = ["", "", "pqr", "123", "xyz", "gh","word", "hello"]
k = 4
print(f"The kth valid String in the list is: {find_kth_valid_string(strings=strings, k=k)}")

Output

The kth valid String in the list is: word

Conclusion

In this article we understood how to find the kth valid String in Python. We have seen simple iteration techniques such as a brute force algorithm. For more readable codes we have utilized the filter method, which filters out all the valid String depending upon our custom function. Other libraries like Pandas also offer us with various methods to do the same.

Updated on: 18-Jul-2023

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements