Banana-Leopard/TASTY huggingface dataset:
# Python3 program to count ways to divide
# a string in two parts a and b such that
# b/pow(10, p) == a
 
def calculate( N ):
    length = len(N)
    l = int((length) / 2)
    count = 0
     
    for i in range(l + 1):
        print(i)
         
        # substring representing int a
        s = N[0: 0 + i]
         
        # no of digits in a
        l1 = len(s)
        print(s,l1)
         
        # consider only most significant
        # l1 characters of remaining
        # string for int b
        t = N[i: l1 + i]
         
        # if any of a or b contains
        # leading 0s discard this
        try:
            if s[0] == '0' or t[0] == '0':
                continue
        except:
            continue
         
        # if both are equal
        if s == t:
            count+=1
        print(i,N[i],count)
    return count
     
# driver code to test above function
N = str("2202200")
print(calculate(N))
 
# This code is contributed by "Sharad_Bhardwaj".

Time complexity: quadratic
Space complexity: linear
# Python program to print n equal parts of string
 
# Function to print n equal parts of string
 
 
def divideString(string, n):
    str_size = len(string)
 
    # Check if string can be divided in n equal parts
    if str_size % n != 0:
        print ("Invalid Input: String size is not divisible by n")
        return
 
    # Calculate the size of parts to find the division points
    part_size = str_size/n
    k = 0
    for i in string:
        if k % part_size == 0:
            print ()
        print (i,end='')
        k += 1
 
 
# Driver program to test the above function
# Length of string is 28
string = "a_simple_divide_string_quest"
 
# Print 4 equal parts of the string
divideString(string, 4)
 
# This code is contributed by Bhavya Jain

Time complexity: linear
Space complexity: constant
# Python code for the same approach
def divide(Str,n):
 
    if (len(Str) % n != 0):
        print("Invalid Input: String size",end="")
        print(" is not divisible by n")
        return
 
    parts = len(Str) // n
    start = 0
 
    while (start < len(Str)):
        print(Str[start: start + parts])
        start += parts
        # if(start < len(Str)) cout << endl; to ignore
        # final new line
     
# driver code
Str = "a_simple_divide_string_quest"
divide(Str, 4)
 
# This code is contributed By shinjanpatra

Time complexity: linear
Space complexity: linear
# Python program to find minimum breaks needed
# to break a string in dictionary words.
 
import sys
 
 
class TrieNode:
 
    def __init__(self):
     
        self.endOfTree = False
        self.children = [None for i in range(26)]
         
 
 
root = TrieNode()
minWordBreak = sys.maxsize
 
# If not present, inserts a key into the trie
    # If the key is the prefix of trie node, just
    # marks leaf node
def insert(key):
 
    global root,minWordBreak
 
    length = len(key)
 
    pcrawl = root
 
    for i in range(length):
 
        index = ord(key[i])- ord('a')
 
        if(pcrawl.children[index] == None):
            pcrawl.children[index] = TrieNode()
        pcrawl = pcrawl.children[index]
         
        # mark last node as leaf
        pcrawl.endOfTree = True
 
# function break the string into minimum cut
# such the every substring after breaking
# in the dictionary.
def _minWordBreak(key):
 
    global minWordBreak
 
    minWordBreak = sys.maxsize
         
    minWordBreakUtil(root, key, 0, sys.maxsize, 0)
 
def minWordBreakUtil(node,key,start,min_Break,level):
 
    global minWordBreak,root
 
    pCrawl = node
 
    # base case, update minimum Break
    if (start == len(key)):
            min_Break = min(min_Break, level - 1)
            if(min_Break<minWordBreak):
                minWordBreak = min_Break
             
            return
         
 
    # traverse given key(pattern)
    for i in range(start,len(key)):
        index = ord(key[i]) - ord('a')
        if (pCrawl.children[index]==None):
            return
 
        # if we find a condition were we can
        # move to the next word in a trie
        # dictionary
        if (pCrawl.children[index].endOfTree):
            minWordBreakUtil(root, key, i + 1,min_Break, level + 1)
 
        pCrawl = pCrawl.children[index]
         
 
 
# Driver code
keys=["cat", "mat", "ca", "ma", "at", "c", "dog", "og", "do" ]
 
for i in range(len(keys)):
    insert(keys[i])
 
_minWordBreak("catmatat")
 
print(minWordBreak)
 
# This code is contributed by shinjanpatra

Time complexity: quadratic
Space complexity: linear
class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        Author : @amitrajitbose
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        """CREATING THE TRIE CLASS"""
 
        class TrieNode(object):
 
            def __init__(self):
                self.children = []  # will be of size = 26
                self.isLeaf = False
 
            def getNode(self):
                p = TrieNode()  # new trie node
                p.children = []
                for i in range(26):
                    p.children.append(None)
                p.isLeaf = False
                return p
 
            def insert(self, root, key):
                key = str(key)
                pCrawl = root
                for i in key:
                    index = ord(i)-97
                    if(pCrawl.children[index] == None):
                        # node has to be initialised
                        pCrawl.children[index] = self.getNode()
                    pCrawl = pCrawl.children[index]
                pCrawl.isLeaf = True  # marking end of word
 
            def search(self, root, key):
                # print("Searching %s" %key) #DEBUG
                pCrawl = root
                for i in key:
                    index = ord(i)-97
                    if(pCrawl.children[index] == None):
                        return False
                    pCrawl = pCrawl.children[index]
                if(pCrawl and pCrawl.isLeaf):
                    return True
 
        def checkWordBreak(strr, root):
            n = len(strr)
            if(n == 0):
                return True
            for i in range(1, n+1):
                if(root.search(root, strr[:i]) and checkWordBreak(strr[i:], root)):
                    return True
            return False
 
        """IMPLEMENT SOLUTION"""
        root = TrieNode().getNode()
        for w in wordDict:
            root.insert(root, w)
        out = checkWordBreak(s, root)
        if(out):
            return "Yes"
        else:
            return "No"
 
 
print(Solution().wordBreak("thequickbrownfox",
                           ["the", "quick", "fox", "brown"]))
print(Solution().wordBreak("bedbathandbeyond", [
      "bed", "bath", "bedbath", "and", "beyond"]))
print(Solution().wordBreak("bedbathandbeyond", [
      "teddy", "bath", "bedbath", "and", "beyond"]))
print(Solution().wordBreak("bedbathandbeyond", [
      "bed", "bath", "bedbath", "and", "away"]))

Time complexity: quadratic
Space complexity: quadratic
# A recursive program to print all possible
# partitions of a given string into dictionary
# words
 
# A utility function to check whether a word
# is present in dictionary or not.  An array of
# strings is used for dictionary.  Using array
# of strings for dictionary is definitely not
# a good idea. We have used for simplicity of
# the program
def dictionaryContains(word):
    dictionary = {"mobile", "samsung", "sam", "sung", "man",
                  "mango", "icecream", "and", "go", "i", "love", "ice", "cream"}
    return word in dictionary
 
# Prints all possible word breaks of given string
def wordBreak(string):
   
    # Last argument is prefix
    wordBreakUtil(string, len(string), "")
 
# Result store the current prefix with spaces
# between words
def wordBreakUtil(string, n, result):
 
    # Process all prefixes one by one
    for i in range(1, n + 1):
       
        # Extract substring from 0 to i in prefix
        prefix = string[:i]
         
        # If dictionary contains this prefix, then
        # we check for remaining string. Otherwise
        # we ignore this prefix (there is no else for
        # this if) and try next
        if dictionaryContains(prefix):
           
            # If no more elements are there, print it
            if i == n:
 
                # Add this element to previous prefix
                result += prefix
                print(result)
                return
            wordBreakUtil(string[i:], n - i, result+prefix+" ")
 
# Driver Code
if __name__ == "__main__":
    print("First Test:")
    wordBreak("iloveicecreamandmango")
 
    print("\nSecond Test:")
    wordBreak("ilovesamsungmobile")
 
# This code is contributed by harshitkap00r

Time complexity: np
Space complexity: quadratic
# Python 3 code to calculate the minimum cost
# to make the given parentheses balanced
def costToBalance(s):
    if (len(s) == 0):
        print(0)
 
    # To store absolute count of
    # balanced and unbalanced parenthesis
    ans = 0
 
    # o(open bracket) stores count of '(' and
    # c(close bracket) stores count of ')'
    o = 0
    c = 0
 
    for i in range(len(s)):
        if (s[i] == '('):
            o += 1
        if (s[i] == ')'):
            c += 1
 
    if (o != c):
        return -1
 
    a = [0 for i in range(len(s))]
    if (s[0] == '('):
        a[0] = 1
    else:
        a[0] = -1
 
    if (a[0] < 0):
        ans += abs(a[0])
 
    for i in range(1, len(s)):
        if (s[i] == '('):
            a[i] = a[i - 1] + 1
        else:
            a[i] = a[i - 1] - 1
        if (a[i] < 0):
            ans += abs(a[i])
 
    return ans
 
# Driver code
if __name__ == '__main__':
    s = ")))((("
 
    print(costToBalance(s))
    s = "))(("
    print(costToBalance(s))
     
# This code is contributed by
# Surendra_Gangwar

Time complexity: linear
Space complexity: linear
# Python3 program to find length of
# the longest balanced subsequence
 
def maxLength(s, n):
     
    dp = [[0 for i in range(n)]
             for i in range(n)]
              
    # Considering all balanced
    # substrings of length 2
    for i in range(n - 1):
        if (s[i] == '(' and s[i + 1] == ')'):
            dp[i][i + 1] = 2
 
    # Considering all other substrings
    for l in range(2, n):
        i = -1
        for j in range(l, n):
            i += 1
            if (s[i] == '(' and s[j] == ')'):
                dp[i][j] = 2 + dp[i + 1][j - 1]
            for k in range(i, j):
                dp[i][j] = max(dp[i][j], dp[i][k] +
                                         dp[k + 1][j])
    return dp[0][n - 1]
 
# Driver Code
s = "()(((((()"
n = len(s)
print(maxLength(s, n))
 
# This code is contributed
# by sahishelangia

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to find length of
# the longest balanced subsequence
 
def maxLength(s, n):
             
    # As it's subsequence - assuming first
    # open brace would map to a first close
    # brace which occurs after the open brace
    # to make subsequence balanced and second
    # open brace would map to second close
    # brace and so on.
     
    # Variable to count all the open brace
    # that does not have the corresponding
    # closing brace.
    invalidOpenBraces = 0;
 
    # To count all the close brace that does
    # not have the corresponding open brace.
    invalidCloseBraces = 0;
     
    # Iterating over the String
    for i in range(n):
        if( s[i] == '(' ):
                 
                # Number of open braces that
                # hasn't been closed yet.
                invalidOpenBraces += 1
        else:
            if(invalidOpenBraces == 0):
                # Number of close braces that
                # cannot be mapped to any open
                # brace.
                invalidCloseBraces += 1
            else:
                # Mapping the ith close brace
                # to one of the open brace.
                invalidOpenBraces -= 1
 
    return (
n - (
invalidOpenBraces + invalidCloseBraces))
 
# Driver Code
s = "()(((((()"
n = len(s)
print(maxLength(s, n))

Time complexity: linear
Space complexity: constant
# Python3 program to evaluate value
# of an expression.
import math as mt
 
def evaluateBoolExpr(s):
 
    n = len(s)
     
    # Traverse all operands by jumping
    # a character after every iteration.
    for i in range(0, n - 2, 2):
 
        # If operator next to current
        # operand is AND.'''
        if (s[i + 1] == "A"):
 
            if (s[i + 2] == "0" or s[i] == "0"):
                s[i + 2] = "0"
            else:
                s[i + 2] = "1"
 
        # If operator next to current
        # operand is OR.
        else if (s[i + 1] == "B"):
            if (s[i + 2] == "1" or s[i] == "1"):
                s[i + 2] = "1"
            else:
                s[i + 2] = "0"
 
        # If operator next to current operand
        # is XOR (Assuming a valid input)
        else:
            if (s[i + 2] == s[i]):
                s[i + 2] = "0"
            else:
                s[i + 2] = "1"
 
    return ord(s[n - 1]) - ord("0")
 
# Driver code
s = "1C1B1B0A0"
string=[s[i] for i in range(len(s))]
print(evaluateBoolExpr(string))
 
# This code is contributed
# by mohit kumar 29

Time complexity: linear
Space complexity: linear
# Python3 Program to find all combinations of Non-
# overlapping substrings formed from given
# string
 
# find all combinations of non-overlapping
# substrings formed by input string str
# index – index of the next character to
#          be processed
# out - output string so far
def findCombinations(string, index, out):
    if index == len(string):
        print(out)
 
    for i in range(index, len(string), 1):
 
        # append substring formed by str[index,
        # i] to output string
        findCombinations(string, i + 1, out + "(" +
                         string[index:i + 1] + ")")
 
# Driver Code
if __name__ == "__main__":
 
    # input string
    string = "abcd"
    findCombinations(string, 0, "")
 
# This code is contributed by
# sanjeev2552

Time complexity: quadratic
Space complexity: quadratic
# Method to find an equal index
def findIndex(str):
    l = len(str)
    open = [0] * (l + 1)
    close = [0] * (l + 1)
    index = -1
     
    open[0] = 0
    close[l] = 0
    if (str[0]=='('):
        open[1] = 1
    if (str[l - 1] == ')'):
        close[l - 1] = 1
     
    # Store the number of
    # opening brackets
    # at each index
    for i in range(1, l):
        if (str[i] == '('):
            open[i + 1] = open[i] + 1
        else:
            open[i + 1] = open[i]
     
    # Store the number
    # of closing brackets
    # at each index
    for i in range(l - 2, -1, -1):
        if ( str[i] == ')'):
            close[i] = close[i + 1] + 1
        else:
            close[i] = close[i + 1]
     
    # check if there is no
    # opening or closing brackets
    if (open[l] == 0):
        return len
    if (close[0] == 0):
        return 0
     
    # check if there is any
    # index at which both
    # brackets are equal
    for i in range(l + 1):
        if (open[i] == close[i]):
            index = i
     
    return index
     
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
 
# This code is contributed
# by ChitraNayal

Time complexity: linear
Space complexity: linear
# Method to find an equal index
def findIndex(str):
    cnt_close = 0
    l = len(str)
    for i in range(1, l):
        if(str[i] == ')'):
            cnt_close = cnt_close + 1
 
    for i in range(1, l):
        if(cnt_close == i):
            return i
    # If no opening brackets
    return l
 
 
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
 
# This code is contributed by Aditya Kumar (adityakumar129)

Time complexity: linear
Space complexity: constant
# Python3 program to find sum of given
# array of string type in integer form
 
# Function to find the sum of given array
def calculateSum(arr, n):
 
    # if string is empty
    if (n == 0):
        return 0
 
    s = arr[0]
 
    # stoi function to convert
    # string into integer
    value = int(s)
    sum = value
 
    for i in range(2 , n, 2):
     
        s = arr[i]
 
        # stoi function to convert
        # string into integer
        value = int(s)
 
        # Find operator
        operation = arr[i - 1][0]
 
        # If operator is equal to '+',
        # add value in sum variable
        # else subtract
        if (operation == '+'):
            sum += value
        else:
            sum -= value
     
    return sum
 
# Driver Function
arr = ["3", "+", "4", "-","7", "+", "13"]
n = len(arr)
print(calculateSum(arr, n))
 
# This code is contributed by Smitha

Time complexity: linear
Space complexity: constant
# Python3 implementation to print the bracket number
 
# function to print the bracket number
def printBracketNumber(exp, n):
 
    # used to print the bracket number
    # for the left bracket
    left_bnum = 1
 
    # used to obtain the bracket number
    # for the right bracket
    right_bnum = list()
 
    # traverse the given expression 'exp'
    for i in range(n):
 
        # if current character is a left bracket
        if exp[i] == '(':
 
            # print 'left_bnum',
            print(left_bnum, end = " ")
 
            # push 'left_bnum' on to the stack 'right_bnum'
            right_bnum.append(left_bnum)
 
            # increment 'left_bnum' by 1
            left_bnum += 1
 
        # else if current character is a right bracket
        elif exp[i] == ')':
 
            # print the top element of stack 'right_bnum'
            # it will be the right bracket number
            print(right_bnum[-1], end = " ")
 
            # pop the top element from the stack
            right_bnum.pop()
 
# Driver Code
if __name__ == "__main__":
    exp = "(a+(b*c))+(d/e)"
    n = len(exp)
 
    printBracketNumber(exp, n)
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: linear
# Python3 program to construct string from binary tree
 
# A binary tree node has data, pointer to left
# child and a pointer to right child
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to construct string from binary tree
def treeToString(root: Node, string: list):
 
    # base case
    if root is None:
        return
 
    # push the root data as character
    string.append(str(root.data))
 
    # if leaf node, then return
    if not root.left and not root.right:
        return
 
    # for left subtree
    string.append('(')
    treeToString(root.left, string)
    string.append(')')
 
    # only if right child is present to
    # avoid extra parenthesis
    if root.right:
        string.append('(')
        treeToString(root.right, string)
        string.append(')')
 
# Driver Code
if __name__ == "__main__":
 
    # Let us construct below tree
    #         1
    #     / \
    #     2     3
    #     / \     \
    # 4 5     6
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)
    string = []
    treeToString(root, string)
    print(''.join(string))
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: linear
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
 
def preOrder(node):
    if (node == None):
        return
    print(node.data, end=" ")
    preOrder(node.left)
    preOrder(node.right)
 
 
def treeFromStringHelper(si, ei, arr, root):
 
    if si[0] >= ei:
        return None
 
    if arr[si[0]] == "(":
 
        if arr[si[0]+1] != ")":
            if root.left is None:
                if si[0] >= ei:
                    return
                new_root = newNode(arr[si[0]+1])
                root.left = new_root
                si[0] += 2
                treeFromStringHelper(si, ei, arr, new_root)
 
        else:
            si[0] += 2
 
        if root.right is None:
            if si[0] >= ei:
                return
 
            if arr[si[0]] != "(":
                si[0] += 1
                return
 
            new_root = newNode(arr[si[0]+1])
            root.right = new_root
            si[0] += 2
            treeFromStringHelper(si, ei, arr, new_root)
        else:
            return
 
    if arr[si[0]] == ")":
        if si[0] >= ei:
            return
        si[0] += 1
        return
 
    return
 
 
def treeFromString(string):
 
    root = newNode(string[0])
 
    if len(string) > 1:
        si = [1]
        ei = len(string)-1
 
        treeFromStringHelper(si, ei, string, root)
 
    return root
 
# Driver Code
if __name__ == '__main__':
    Str = "4(2(3)(1))(6(5))"
    root = treeFromString(Str)
    preOrder(root)
 
# This code is contributed by dheerajalimchandani

Time complexity: quadratic
Space complexity: linear
# Simple Python3 program to convert
# all substrings from decimal to given base.
import math
 
def substringConversions(s, k, b):
     
    l = len(s);
    for i in range(l):
         
        if((i + k) < l + 1):
             
            # Saving substring in sub
            sub = s[i : i + k];    
             
            # Evaluating decimal for current
            # substring and printing it.
            sum, counter = 0, 0;
            for i in range(len(sub) - 1, -1, -1):
     
                sum = sum + ((ord(sub[i]) - ord('0')) *    
                              pow(b, counter));
                counter += 1;
             
            print(sum , end = " ");
 
# Driver code
s = "12212";
b, k = 3, 3;
substringConversions(s, b, k);
 
# This code is contributed
# by Princi Singh

Time complexity: quadratic
Space complexity: linear
# Simple Python3 program to convert all
# substrings from decimal to given base.
import math as mt
 
def substringConversions(str1, k, b):
 
    for i in range(0, len(str1) - k + 1):
     
        # Saving substring in sub
        sub = str1[i:k + i]
         
        # Evaluating decimal for current
        # substring and printing it.
        Sum = 0
        counter = 0
        for i in range(len(sub) - 1, -1, -1):
            Sum = (Sum + ((ord(sub[i]) - ord('0')) *
                           pow(b, counter)))
            counter += 1
                 
        print(Sum, end = " ")
     
# Driver code
str1 = "12212"
b = 3
k = 3
substringConversions(str1, b, k)
 
# This code is contributed by
# Mohit Kumar 29

Time complexity: linear
Space complexity: linear
# Python3 program to demonstrate above steps
# of binary fractional to decimal conversion
 
# Function to convert binary fractional 
# to decimal
def binaryToDecimal(binary, length) :
     
    # Fetch the radix point
    point = binary.find('.')
 
    # Update point if not found
    if (point == -1) :
        point = length
 
    intDecimal = 0
    fracDecimal = 0
    twos = 1
 
    # Convert integral part of binary
    # to decimal equivalent
    for i in range(point-1, -1, -1) :
         
        # Subtract '0' to convert
        # character into integer
        intDecimal += ((ord(binary[i]) -
                        ord('0')) * twos)
        twos *= 2
 
    # Convert fractional part of binary
    # to decimal equivalent
    twos = 2
     
    for i in range(point + 1, length):
         
        fracDecimal += ((ord(binary[i]) -
                         ord('0')) / twos);
        twos *= 2.0
 
    # Add both integral and fractional part
    ans = intDecimal + fracDecimal
     
    return ans
 
# Driver code :
if __name__ == "__main__" :
    n = "110.101"
    print(binaryToDecimal(n, len(n)))
     
    n = "101.1101"
    print(binaryToDecimal(n, len(n)))
 
# This code is contributed
# by aishwarya.27

Time complexity: linear
Space complexity: linear