Program to check if a string can become empty by recursive deletion of sub-string using Python

by | Mar 6, 2021 | Python Programs

Home » Python » Python Programs » Program to check if a string can become empty by recursive deletion of sub-string using Python

Introduction

The task is to check whether the string will get empty on recursive deletion of the given sub-string.

Program to check if a string can become empty by recursive deletion of sub-string

Program

def str_empty(ip_str, ip_pattern):
    if len(ip_str) == 0 and len(ip_pattern) == 0:
        return 'true'
    if len(ip_pattern) == 0:
        return 'true'
    while (len(ip_str) != 0):
        pos = ip_str.find(ip_pattern)
        if(pos == (-1)):
            return 'false'
        ip_str = ip_str[0:pos] + ip_str[pos + len(ip_pattern):]
    return 'true'
   
ip_str = input("Enter the string : ")
ip_pattern = input("Enter the sub-string : ")
print(str_empty(ip_str, ip_pattern))

Output

Program to check if a string can become empty by recursive deletion of sub-string Output

Explanation

In the above python code, firstly we have checked whether the input string and the pattern is empty or not. If the given strings are not empty, we checked whether the sub-string is found in the given input or not. If the sub-string is found, we have sliced the input strings into two parts. The first parts is from the start till the index of the found sub-string and the second part is from the index of found sub-string till the length of sub-string. Then concatenate the sliced parts.

This step is repeated until there is no sub-string left.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author