Home > Enterprise >  Using Python, Divide a String into Two halves if specific characters are in center of String
Using Python, Divide a String into Two halves if specific characters are in center of String

Time:12-10

A 101-String is a String that contains 1s and 0s where the substring '101' is located in the center of string. A 101 string has at least 3 characters i-e the shortest 101-string is '101'

For example the String '110101001' is a 101-String because the substring 101 divides the original string in two equal halves. In other words, if we take the substring 101 out from the original string, we have two strings 110 and 001 of equal length.

Write a program, that asks user to enter a string and print True if the string is 101-string and False if it's not. if the string contains any characters other than 1s and 0s, program should print False. if the String's length is less than 3 characters, the program should print False as well.

CodePudding user response:

We can check if it's a 101 String using sets. We can check if the string contains 101 using .find() function. Finally, we will split the string using String slicing.

def check(string) :


    p = set(string)

    # declare set of '0', '1' .
    s = {'0', '1'}

    if s == p or p == {'0'} or p == {'1'}:
        print("True")
    else :
        print("False")


if __name__ == "__main__" :

    string = input("Enter 101-string")
    # function calling
    check(string)
    substring = "101"
    if len(string)<2:
        print("False")
    if substring in string:
            print("101 String found")
    print("length of String is: ",len(string))
    find_101 = string.find('101')
    print("Location of 101 is", find_101)
    end_101 = find_101 2;
    print("String 101 ends at index:",end_101)
    s1 = string[:find_101]
    second_part = end_101 1; 
    s2 = string[second_part:]
    print(s1,s2)
    if len(s1) == len(s2):
        print("True")
    else:
        print("Not a 101 String")
        print("False")

CodePudding user response:

You need only 3 conditions for a valid 101 string:

  1. The string length is odd (checked using modulo)
  2. It is composed of '0'/'1' only (checked using set.issubset)
  3. There is '101' in the middle (checked using slicing):
def is101(s):
    x = (len(s)-2)//2
    return bool(len(s)%2) & set(s).issubset('01') &  (s[x:x 3] == '101')

Example:

>>> is101('110101001')
True

>>> is101('')
False

>>> is101('11010100')
False

>>> is101('xxx101xxx')
False
  • Related