Banana-Leopard/TASTY huggingface dataset:
# Function to reverse words of string
import re
def rev_sentence(sentence):
 
    # find all the words in sentence
    words = re.findall('\w+', sentence)
 
    # Backward iterate over list of words and join using space
    reverse_sentence = ' '.join(words[i] for i in range(len(words)-1, -1, -1))
 
    # finally return the joined string
    return reverse_sentence
 
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print (rev_sentence(input))

Time complexity: linear
Space complexity: linear
# Python code for run length encoding
from collections import OrderedDict
def runLengthEncoding(input):
 
    # Generate ordered dictionary of all lower
    # case alphabets, its output will be
    # dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0}
    dict=OrderedDict.fromkeys(input, 0)
 
    # Now iterate through input string to calculate
    # frequency of each character, its output will be
    # dict = {'w':4,'a':3,'d':1,'e':1,'x':6}
    for ch in input:
        dict[ch] += 1
 
    # now iterate through dictionary to make
    # output string from (key,value) pairs
    output = ''
    for key,value in dict.items():
        output = output + key + str(value)
    return output
 
# Driver function
if __name__ == "__main__":
    input="wwwwaaadexxxxxx"
    print (runLengthEncoding(input))

Time complexity: linear
Space complexity: linear
def encode(message):
    encoded_message = ""
    i = 0
 
    while (i <= len(message)-1):
        count = 1
        ch = message[i]
        j = i
        while (j < len(message)-1):
            if (message[j] == message[j+1]):
                count = count+1
                j = j+1
            else:
                break
        encoded_message=encoded_message+str(count)+ch
        i = j+1
    return encoded_message
 
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)

Time complexity: quadratic
Space complexity: constant
# Python code to check if two strings are
# anagram
from collections import Counter
 
def anagram(input1, input2):
 
    # Counter() returns a dictionary data
    # structure which contains characters
    # of input as key and their frequencies
    # as it's corresponding value
    return Counter(input1) == Counter(input2)
 
# Driver function
if __name__ == "__main__":
    input1 = 'abcd'
    input2 = 'dcab'
    print anagram(input1, input2)

Time complexity: linear
Space complexity: constant
# Recursive Program to remove consecutive
# duplicates from string S.
  
  
def removeConsecutiveDuplicates(s):
    if len(s) < 2:
        return s
    if s[0] != s[1]:
        return s[0]+removeConsecutiveDuplicates(s[1:])
    return removeConsecutiveDuplicates(s[1:])
  
  
# This code is contributed by direwolf707
s1 = 'geeksforgeeks'
print(removeConsecutiveDuplicates(s1))  # geksforgeks
s2 = 'aabcca'
print(removeConsecutiveDuplicates(s2))  # ab
  
# This code is contributed by rahulsood707.

Time complexity: quadratic
Space complexity: constant
# Python3 program to remove consecutive
# duplicates from a given string.
  
# A iterative function that removes
# consecutive duplicates from string S
  
  
def removeDuplicates(S):
  
    n = len(S)
  
    # We don't need to do anything for
    # empty or single character string.
    if (n < 2):
        return
  
    # j is used to store index is result
    # string (or index of current distinct
    # character)
    j = 0
  
    # Traversing string
    for i in range(n):
  
        # If current character S[i]
        # is different from S[j]
        if (S[j] != S[i]):
            j += 1
            S[j] = S[i]
  
    # Putting string termination
    # character.
    j += 1
    S = S[:j]
    return S
  
  
# Driver Code
if __name__ == '__main__':
  
    S1 = "geeksforgeeks"
    S1 = list(S1.rstrip())
    S1 = removeDuplicates(S1)
    print(*S1, sep="")
  
    S2 = "aabcca"
    S2 = list(S2.rstrip())
    S2 = removeDuplicates(S2)
    print(*S2, sep="")
  
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Time complexity: linear
Space complexity: constant
# Python program to find smallest
# number to find smallest number
# with N as sum of digits and
# divisible by 10^N.
 
import math
def digitsNum(N):
 
    # If N = 0 the string will be 0
    if (N == 0) :
        print("0", end = "")
     
    # If n is not perfectly divisible
    # by 9 output the remainder
    if (N % 9 != 0):
        print (N % 9, end ="")
     
    # Print 9 N/9 times
    for i in range( 1, int(N / 9) + 1) :
        print("9", end = "")
     
    # Append N zero's to the number so
    # as to make it divisible by 10^N
    for i in range(1, N + 1) :
        print("0", end = "")
     
    print()
 
 
# Driver Code
N = 5
print("The number is : ",end="")
digitsNum(N)
 
# This code is contributed by Gitanjali.

Time complexity: linear
Space complexity: constant
# Python3 program to find maximum
# and minimum possible sums of
# two numbers that we can get if
# replacing digit from 5 to 6
# and vice versa are allowed.
 
 
# Find new value of x after
# replacing digit "from" to "to"
def replaceDig(x, from1, to):
    result = 0
    multiply = 1
 
    while (x > 0):
        reminder = x % 10
 
        # Required digit found,
        # replace it
        if (reminder == from1):
            result = result + to * multiply
 
        else:
            result = result + reminder * multiply
 
        multiply *= 10
        x = int(x / 10)
    return result
 
# Returns maximum and minimum
# possible sums of x1 and x2
# if digit replacements are allowed.
def calculateMinMaxSum(x1, x2):
     
    # We always get minimum sum
    # if we replace 6 with 5.
    minSum = replaceDig(x1, 6, 5) +replaceDig(x2, 6, 5)
 
    # We always get maximum sum
    # if we replace 5 with 6.
    maxSum = replaceDig(x1, 5, 6) +replaceDig(x2, 5, 6)
    print("Minimum sum =" , minSum)
    print("Maximum sum =" , maxSum,end=" ")
 
# Driver code
if __name__=='__main__':
    x1 = 5466
    x2 = 4555
    calculateMinMaxSum(x1, x2)
 
# This code is contributed
# by mits

Time complexity: logn
Space complexity: constant
# Python code for the above approach
 
# this is function for finding sum of two
# numbers as string
def string_sum(str1, str2):
 
    if (len(str1) < len(str2)):
        str1, str2 = str2,str1
 
    m = len(str1)
    n = len(str2)
    ans = ""
 
    # sum the str2 with str1
    carry = 0
    for i in range(n):
 
        # Sum of current digits
        ds = ((ord(str1[m - 1 - i]) - ord('0')) +
                (ord(str2[n - 1 - i]) - ord('0')) +
                carry) % 10
 
        carry = ((ord(str1[m - 1 - i]) - ord('0')) +
                (ord(str2[n - 1 - i]) - ord('0')) +
                carry) // 10
 
        ans = str(ds) + ans
 
    for i in range(n,m):
        ds = (ord(str1[m - 1 - i]) - ord('0') +
                carry) % 10
        carry = (ord(str1[m - 1 - i]) - ord('0') +
                carry) // 10
        ans = str(ds) + ans
 
    if (carry):
        ans = str(carry) + ans
    return ans
 
# Returns True if two substrings of given
# lengths of str[beg..] can cause a positive
# result.
def checkSumStrUtil(Str, beg,len1, len2):
 
    # Finding two substrings of given lengths
    # and their sum
    s1 = Str[beg: beg+len1]
    s2 = Str[beg + len1: beg + len1 +len2]
    s3 = string_sum(s1, s2)
 
    s3_len = len(s3)
 
    # if number of digits s3 is greater than
    # the available string size
    if (s3_len > len(Str) - len1 - len2 - beg):
        return False
 
    # we got s3 as next number in main string
    if (s3 == Str[beg + len1 + len2: beg + len1 + len2 +s3_len]):
 
        # if we reach at the end of the string
        if (beg + len1 + len2 + s3_len == len(Str)):
            return True
 
        # otherwise call recursively for n2, s3
        return checkSumStrUtil(Str, beg + len1, len2,s3_len)
 
    # we do not get s3 in main string
    return False
 
# Returns True if str is sum string, else False.
def isSumStr(Str):
 
    n = len(Str)
 
    # choosing first two numbers and checking
    # whether it is sum-string or not.
    for i in range(1,n):
        for j in range(1,n-i):
            if (checkSumStrUtil(Str, 0, i, j)):
                return True
 
    return False
 
 
# Driver code
print(isSumStr("1212243660"))
print(isSumStr("123456787"))
 
# This code is contributed by shinjanpatra

Time complexity: cubic
Space complexity: linear
# Python program to find maximum value
 
# Function to calculate the value
def calcMaxValue(str):
 
    # Store first character as integer
    # in result
    res = ord(str[0]) - 48
 
    # Start traversing the string
    for i in range(1, len(str)):
         
        # Check if any of the two numbers
        # is 0 or 1, If yes then add current
        # element
        if(str[i] == '0' or
           str[i] == '1' or res < 2):
            res += ord(str[i]) - 48
        else:
            res *= ord(str[i]) - 48
 
    return res        
 
# Driver code
if __name__== "__main__":
    str = "01891";
    print(calcMaxValue(str));
     
# This code is contributed by Sairahul Jella

Time complexity: linear
Space complexity: constant
# Python3 program to find the maximum segment
# value after putting k breaks.
 
# Function to Find Maximum Number
def findMaxSegment(s, k):
 
    # Maximum segment length
    seg_len = len(s) - k
 
    # Find value of first segment of seg_len
    res = 0
    for i in range(seg_len):
        res = res * 10 + (ord(s[i]) - ord('0'))
 
    # Find value of remaining segments
    # using sliding window
    seg_len_pow = pow(10, seg_len - 1)
    curr_val = res
    for i in range(1, len(s) - seg_len):
 
        # To find value of current segment,
        # first remove leading digit from
        # previous value    
        curr_val = curr_val - (ord(s[i - 1])-
                               ord('0')) * seg_len_pow
 
        # Then add trailing digit
        curr_val = (curr_val * 10 +
                   (ord(s[i + seg_len - 1]) - ord('0')))
 
        res = max(res, curr_val)
    return res
 
# Driver Code
if __name__ == '__main__':
    s = "8754"
    k = 2
    print("Maximum number = ",
         findMaxSegment(s, k))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: constant
# Python 3 program to find
# if a number is divisible
# by 4 or not
 
# Function to find that
# number divisible by
# 4 or not
def check(st):
    n = len(st)
 
    # Empty string
    if (n == 0):
        return False
 
    # int(string_variable) is used in Python3
    # to convert string to integer
 
    # If there is single
    # digit
    if (n == 1):
        return (int(st) % 4 == 0)
 
    # slicing of strings is used in Python to function as substring
    st = st[n-2:]
    # If number formed by
    # last two digits is
    # divisible by 4.
    return (int(st) % 4 == 0)
 
 
# Driver code
st = "76952"
 
# Function call
if(check(st)):
    print("Yes")
else:
    print("No ")
 
# This code is contributed by Abhijeet Kumar(abhijeet19403)

Time complexity: constant
Space complexity: constant
# Python3 program to calculate number
# of substring
 
# Return the number of substring divisible
# by 6 and starting at index i in s[] and
# previous sum of digits modulo 3 is m.
def f(i, m, s, memoize):
     
    # End of the string.
    if (i == len(s)):
        return 0
 
    # If already calculated, return
    # the stored value.
    if (memoize[i][m] != -1):
        return memoize[i][m]
 
    # Converting into integer.
    x = ord(s[i]) - ord('0')
 
    # Increment result by 1, if current digit
    # is divisible by 2 and sum of digits is
    # divisible by 3.
    # And recur for next index with new modulo.
    ans = (((x + m) % 3 == 0 and x % 2 == 0) +
          f(i + 1, (m + x) % 3, s, memoize))
 
    memoize[i][m] = ans
    return memoize[i][m]
 
# Returns substrings divisible by 6.
def countDivBy6(s):
    n = len(s)
 
    # For storing the value of all states.
    memoize = [[-1] * 3 for i in range(n + 1)]
 
    ans = 0
    for i in range(len(s)):
         
        # If string contain 0, increment
        # count by 1.
        if (s[i] == '0'):
            ans += 1
 
        # Else calculate using recursive function.
        # Pass previous sum modulo 3 as 0.
        else:
            ans += f(i, 0, s, memoize)
 
    return ans
 
# Driver Code
if __name__ == '__main__':
    s = "4806"
 
    print(countDivBy6(s))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 implementation to check whether
# decimal representation of given binary
# number is divisible by 5 or not
 
# function to return equivalent base 4
# number of the given binary number
def equivalentBase4(bin):
    if(bin == "00"):
        return 0
    if(bin == "01"):
        return 1
    if(bin == "10"):
        return 2
    if(bin == "11"):
        return 3
     
# function to check whether the given
# binary number is divisible by 5 or not    
def isDivisibleBy5(bin):
    l = len(bin)
    if((l % 2) == 1):
         
    # add '0' in the beginning to
    # make length an even number    
        bin = '0' + bin
         
    # to store sum of digits at odd
    # and even places respectively
    odd_sum = 0
    even_sum = 0
    isOddDigit = 1
    for i in range(0, len(bin), 2):
         
        # if digit of base 4 is at odd place,
        # then add it to odd_sum
        if(isOddDigit):
            odd_sum += equivalentBase4(bin[i:i + 2])
             
        # else digit of base 4 is at
        # even place, add it to even_sum    
        else:
            even_sum += equivalentBase4(bin[i:i + 2])
             
        isOddDigit = isOddDigit ^ 1
 
    # if this diff is divisible by 11(which is
    # 5 in decimal) then, the binary number is
    # divisible by 5
    if(abs(odd_sum - even_sum) % 5 == 0):
        return "Yes"
    else:
        return "No"
 
# Driver Code
if __name__=="__main__":
    bin = "10000101001"
    print(isDivisibleBy5(bin))
 
# This code is contributed
# by Sairahul Jella

Time complexity: linear
Space complexity: constant
# Python3 Program to count substrings
# which are divisible by 8 but not by 3
 
# Returns count of substrings
# divisible by 8 but not by 3.
def count(s, Len):
    global MAX
    cur = 0
    dig = 0
    Sum = [0] * MAX
    dp = [[0, 0, 0] for i in range(MAX)]
 
    dp[0][0] = 1
 
    # Iterating the string.
    for i in range(1, Len + 1):
        dig = int(s[i - 1]) - 48
        cur += dig
        cur %= 3
 
        Sum[i] = cur
 
        # Prefix sum of number of substrings
        # whose sum of digits modulo 3 is
        # 0, 1, 2.
        dp[i][0] = dp[i - 1][0]
        dp[i][1] = dp[i - 1][1]
        dp[i][2] = dp[i - 1][2]
 
        dp[i][Sum[i]] += 1
 
    ans = 0
    dprev = 0
    value = 0
    dprev2 = 0
 
    # Iterating the string.
    for i in range(1, Len + 1):
        dig = int(s[i - 1]) - 48
 
        # Since single digit 8 is
        # divisible by 8 and not by 3.
        if dig == 8:
            ans += 1
 
        # Taking two digit number.
        if i - 2 >= 0:
            dprev = int(s[i - 2]) - 48 # 10th position
            value = dprev * 10 + dig   # Complete 2 digit
                                       # number
 
            if (value % 8 == 0) and (value % 3 != 0):
                ans += 1
 
        # Taking 3 digit number.
        if i - 3 >= 0:
            dprev2 = int(s[i - 3]) - 48 # 100th position
            dprev = int(s[i - 2]) - 48 # 10th position
 
            # Complete 3 digit number.
            value = (dprev2 * 100 +
                     dprev * 10 + dig)
 
            if value % 8 != 0:
                continue
 
            # If number formed is divisible by 8
            # then last 3 digits are also divisible
            # by 8. Then all the substring ending
            # at this index are divisible.
            ans += (i - 2)
 
            # But those substring also contain
            # number which are not divisible
            # by 3 so remove them.
            ans -= (dp[i - 3][Sum[i]])
 
    return ans
 
# Driver Code
MAX = 1000
Str = "6564525600"
Len = len(Str)
print(count(Str, Len))
 
# This code is contributed
# by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 program for divisibility
# of number by 999
 
# function to check divisibility
def isDivisible999(num):
    n = len(num);
    if(n == 0 or num[0] == '0'):
        return true
 
    # Append required 0s at the beginning.
    if((n % 3) == 1):
        num = "00" + num
    if((n % 3) == 2):
        num = "0" + num
 
    # add digits in group of three in gSum    
    gSum = 0
    for i in range(0, n, 3):
         
        # group saves 3-digit group
        group = 0
        group += (ord(num[i]) - 48) * 100
        group += (ord(num[i + 1]) - 48) * 10
        group += (ord(num[i + 2]) - 48)
        gSum += group
 
    # calculate result till 3 digit sum    
    if(gSum > 1000):
        num = str(gSum)
        n = len(num)
        gSum = isDivisible999(num)
    return (gSum == 999)
 
# Driver code
if __name__=="__main__":
    num = "1998"
    n = len(num)
    if(isDivisible999(num)):
        print("Divisible")
    else:
        print("Not divisible")
         
# This code is contributed
# by Sairahul Jella

Time complexity: linear
Space complexity: constant
# Python3 program to implement division
# with large number
import math
 
# A function to perform division of
# large numbers
def longDivision(number, divisor):
 
    # As result can be very large
    # store it in string
    ans = "";
     
    # Find prefix of number that
    # is larger than divisor.
    idx = 0;
    temp = ord(number[idx]) - ord('0');
    while (temp < divisor):
        temp = (temp * 10 + ord(number[idx + 1]) -
                            ord('0'));
        idx += 1;
     
    idx += 1;
 
    # Repeatedly divide divisor with temp.
    # After every division, update temp to
    # include one more digit.
    while ((len(number)) > idx):
         
        # Store result in answer i.e. temp / divisor
        ans += chr(math.floor(temp // divisor) + ord('0'));
         
        # Take next digit of number
        temp = ((temp % divisor) * 10 + ord(number[idx]) -
                                        ord('0'));
        idx += 1;
 
    ans += chr(math.floor(temp // divisor) + ord('0'));
     
    # If divisor is greater than number
    if (len(ans) == 0):
        return "0";
     
    # else return ans
    return ans;
 
# Driver Code
number = "1248163264128256512";
divisor = 125;
print(longDivision(number, divisor));
     
# This code is contributed by mits

Time complexity: np
Space complexity: linear
# Python3 program to find remainder of
# a large number when divided by 7.
 
# Function which return Remainder
# after dividing the number by 7
def remainderWith7(num):
     
    # This series is used to
    # find remainder with 7
    series = [1, 3, 2, -1, -3, -2];
     
    # Index of next element
    # in series
    series_index = 0;
     
    # Initialize result
    result = 0;
     
    # Traverse num from end
    for i in range((len(num) - 1), -1, -1):
         
        # Find current digit of num
        digit = ord(num[i]) - 48;
         
        # Add next term to result
        result += digit * series[series_index];
         
        # Move to next term in series
        series_index = (series_index + 1) % 6;
         
        # Make sure that result
        # never goes beyond 7.
        result %= 7;
     
    # Make sure that remainder
    # is positive
     
    if (result < 0):
        result = (result + 7) % 7;
    return result;
 
# Driver Code
str = "12345";
print("Remainder with 7 is",
       remainderWith7(str));
 
# This code is contributed by mits

Time complexity: linear
Space complexity: constant
# A simple Python3 code
# to check for even or odd
 
# Returns true if n is even, else odd
def isEven(n):
    return (n % 2 == 0)
     
# Driver code
n = 101
print("Even" if isEven(n) else "Odd")
 
# This code is contributed by "Sharad_Bhardwaj".

Time complexity: constant
Space complexity: constant
# A Python3 code program
# to check for even or odd
 
# Returns true if n is even, else odd
def isEven(n):
     
    # n&1 is 1, then odd, else even
    return (not(n & 1))
     
# Driver code
n = 101;
print("Even" if isEven(n) else "Odd")
 
# This code is contributed by "Sharad_Bhardwaj".

Time complexity: constant
Space complexity: constant
# Python 3 implementation
# to find product of
# digits of elements
# at k-th level
 
# Function to find
# product of digits
# of elements at
# k-th level
def productAtKthLevel(tree, k):
 
    level = -1
         
        # Initialize result
    product = 1
    n = len(tree)
 
    for i in range(0, n):
 
        # increasing level number
        if (tree[i] == '('):
            level+=1
 
        # decreasing level number
        elif (tree[i] == ')'):
            level-=1
 
        else:
            # check if current level is
            # the desired level or not
            if (level == k):
                product *= (int(tree[i]) - int('0'))
         
     
 
    # required product
    return product
 
 
# Driver program
tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
k = 2
 
print(productAtKthLevel(tree, k))
 
# This code is contributed by
# Smitha Dinesh Semwal

Time complexity: linear
Space complexity: constant
# Python 3 implementation to find remainder
# when a large number is divided by 11
 
# Function to return remainder
def remainder(st) :
     
    # len is variable to store the
    # length of number string.
    ln = len(st)
     
    rem = 0
     
    # loop that find remainder
    for i in range(0, ln) :
        num = rem * 10 + (int)(st[i])
        rem = num % 11
         
    return rem
     
     
# Driver code
st = "3435346456547566345436457867978"
print(remainder(st))
 
 
# This code is contributed by Nikita Tiwari.

Time complexity: linear
Space complexity: constant
# Python 3 program to count number of
# ways to remove an element so that
# XOR of remaining string becomes 0.
 
# Return number of ways in which XOR
# become ZERO by remove 1 element
def xorZero(str):
    one_count = 0
    zero_count = 0
    n = len(str)
 
    # Counting number of 0 and 1
    for i in range(0, n, 1):
        if (str[i] == '1'):
            one_count += 1
        else:
            zero_count += 1
     
    # If count of ones is even
    # then return count of zero
    # else count of one
    if (one_count % 2 == 0):
        return zero_count
    return one_count
 
# Driver Code
if __name__ == '__main__':
    str = "11111"
    print(xorZero(str))
 
# This code is contributed by
# Surendra_Gangwar

Time complexity: linear
Space complexity: constant