giulio98/xlcost-single-prompt huggingface dataset:
# number of distinct permutation a string can have | python program to find number of distinct permutations of a string . ; utility function to find factorial of n . ; returns count of distinct permutations of str . ; finding frequency of all the lower case alphabet and storing them in array of integer ; finding factorial of number of appearances and multiplying them since they are repeating alphabets ; finding factorial of size of string and dividing it by factorial found after multiplying ; 

MAX_CHAR = 26


def factorial(n):
    fact = 1
    for i in range(2, n + 1):
        fact = fact * i
    return fact


def countDistinctPermutations(st):
    length = len(st)
    freq = [0] * MAX_CHAR
    for i in range(0, length):
        if (st[i] >= 'a'):
            freq[(ord)(st[i]) - 97] = freq[(ord)(st[i]) - 97] + 1
    fact = 1
    for i in range(0, MAX_CHAR):
        fact = fact * factorial(freq[i])
    return factorial(length) / fact


st = "fvvfhvgv"
print(countDistinctPermutations(st))

# Expected output:
840.0
# determine if a string has all unique characters | python3 program to illustrate string with unique characters without using any data structure ; assuming string can have characters a - z this has 32 bits set to 0 ; if that bit is already set in checker , return false ; otherwise update and continue by setting that bit in the checker ; no duplicates encountered , return true ; 

import math


def uniqueCharacters(str):
    checker = 0
    for i in range(len(str)):
        bitAtIndex = ord(str[i]) - ord('a')
        if ((bitAtIndex) > 0):
            if ((checker & ((1 << bitAtIndex))) > 0):
                return False
            checker = checker | (1 << bitAtIndex)
    return True


if __name__ == '__main__':
    input = "geekforgeeks"
    if (uniqueCharacters(input)):
        print("The String " + input + " has all unique characters")
    else:
        print("The String " + input + " has duplicate characters")

# Expected output:
The String geekforgeeks has duplicate characters
# alternate vowel and consonant string | ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required alternate vowel and consonant string ; count vowels and update vowel string ; count consonants and update consonant string ; no such string can be formed ; remove first character of vowel string then create alternate string with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant string then create alternate string with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating string with consonant ; start creating string with vowel ; 
def isVowel(ch):
    if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
        return True
    return False


def createAltStr(str1, str2, start, l):
    finalStr = ""
    i = 0
    for j in range(start, l):
        finalStr = (finalStr + str1[i]) + str2[j]
        i + 1
    return finalStr


def findAltStr(str1):
    nv = 0
    nc = 0
    vstr = ""
    cstr = ""
    l = len(str1)
    for i in range(0, l):
        if (isVowel(str1[i])):
            nv += 1
            vstr = vstr + str1[i]
        else:
            nc += 1
            cstr = cstr + str1[i]
    if (abs(nv - nc) >= 2):
        return "no such string"
    if (nv > nc):
        return (vstr[0] + createAltStr(cstr, vstr, 1, nv))
    if (nc > nv):
        return (cstr[0] + createAltStr(vstr, cstr, 1, nc))
    if (cstr[0] < vstr[0]):
        return createAltStr(cstr, vstr, 0, nv)
    return createAltStr(vstr, cstr, 0, nc)


if __name__ == "__main__":
    str1 = "geeks"
    print(findAltStr(str1))

# Expected output:
gekes
# check whether k | python3 code to check if k - th bit of a given number is set or not ; 
def isKthBitSet(n, k):
    if n & (1 << (k - 1)):
        print("SET")
    else:
        print("NOT SET")


n = 5
k = 1
isKthBitSet(n, k)

# Expected output:
SET
# recursive function to check if a string is palindrome | a recursive function that check a str [ s . . e ] is palindrome or not . ; if there is only one character ; if first and last characters do not match ; if there are more than two characters , check if middle substring is also palindrome or not . ; an empty string is considered as palindrome ; 
def isPalRec(st, s, e):
    if (s == e):
        return True
    if (st[s] != st[e]):
        return False
    if (s < e + 1):
        return isPalRec(st, s + 1, e - 1)
    return True


def isPalindrome(st):
    n = len(st)
    if (n == 0):
        return True
    return isPalRec(st, 0, n - 1)


st = "geeg"
if (isPalindrome(st)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count substrings with same first and last characters | assuming lower case only ; calculating frequency of each character in the string . ; computing result using counts ; 

MAX_CHAR = 26


def countSubstringWithEqualEnds(s):
    result = 0
    n = len(s)
    count = [0] * MAX_CHAR
    for i in range(n):
        count[ord(s[i]) - ord('a')] += 1
    for i in range(MAX_CHAR):
        result += (count[i] * (count[i] + 1) / 2)
    return result


s = "abcab"
print(countSubstringWithEqualEnds(s))

# Expected output:
7.0
# maximum consecutive repeating character in string | returns the maximum repeating character in a given string ; traverse string except last character ; if current character matches with next ; if doesn 't match, update result  (if required) and reset count ; 
def maxRepeating(str):
    n = len(str)
    count = 0
    res = str[0]
    cur_count = 1
    for i in range(n):
        if (i < n - 1 and str[i] == str[i + 1]):
            cur_count += 1
        else:
            if cur_count > count:
                count = cur_count
                res = str[i]
            cur_count = 1
    return res


if __name__ == "__main__":
    str = "aaaabbaaccde"
    print(maxRepeating(str))

# Expected output:
a
# queries for characters in a repeated string | print whether index i and j have same element or not . ; finding relative position of index i , j . ; checking is element are same at index i , j . ; 
def query(s, i, j):
    n = len(s)
    i %= n
    j %= n
    print("Yes")if s[i] == s[j]else print("No")


if __name__ == "__main__":
    X = "geeksforgeeks"
    query(X, 0, 8)
    query(X, 8, 13)
    query(X, 6, 15)

# Expected output:
Yes
Yes
No
# count of character pairs at same distance as in english alphabets | function to count pairs ; increment count if characters are at same distance ; 
def countPairs(str1):
    result = 0
    n = len(str1)
    for i in range(0, n):
        for j in range(i + 1, n):
            if (abs(ord(str1[i]) - ord(str1[j])) == abs(i - j)):
                result += 1
    return result


if __name__ == "__main__":
    str1 = "geeksforgeeks"
    print(countPairs(str1))

# Expected output:
4
# longest common subsequence with permutations allowed | function to calculate longest string str1 -- > first string str2 -- > second string count1 [ ] -- > hash array to calculate frequency of characters in str1 count [ 2 ] -- > hash array to calculate frequency of characters in str2 result -- > resultant longest string whose permutations are sub - sequence of given two strings ; calculate frequency of characters ; now traverse hash array ; append character ( ' a ' + i ) in resultant string ' result ' by min ( count1 [ i ] , count2i ] ) times ; 
def longestString(str1, str2):
    count1 = [0] * 26
    count2 = [0] * 26
    for i in range(len(str1)):
        count1[ord(str1[i]) - ord('a')] += 1
    for i in range(len(str2)):
        count2[ord(str2[i]) - ord('a')] += 1
    result = ""
    for i in range(26):
        for j in range(1, min(count1[i], count2[i]) + 1):
            result = result + chr(ord('a') + i)
    print(result)


if __name__ == "__main__":
    str1 = "geeks"
    str2 = "cake"
    longestString(str1, str2)

# Expected output:
ek
# check if string follows order of characters defined by a pattern or not | set 1 | function to check if characters in the input string follows the same order as determined by characters present in the given pattern ; len stores length of the given pattern ; if length of pattern is more than length of input string , return false ; ; x , y are two adjacent characters in pattern ; find index of last occurrence of character x in the input string ; find index of first occurrence of character y in the input string ; return false if x or y are not present in the input string or last occurrence of x is after the first occurrence of y in the input string ; return true if string matches the pattern ; 
def checkPattern(string, pattern):
    l = len(pattern)
    if len(string) < l:
        return False
    for i in range(l - 1):
        x = pattern[i]
        y = pattern[i + 1]
        last = string .rindex(x)
        first = string .index(y)
        if last == -1 or first == -1 or last > first:
            return False
    return True


if __name__ == "__main__":
    string = "engineers rock"
    pattern = "gsr"
    print(checkPattern(string, pattern))

# Expected output:
False
# calculate sum of all numbers present in a string | function to calculate sum of all numbers present in a str1ing containing alphanumeric characters ; a temporary str1ing ; holds sum of all numbers present in the str1ing ; read each character in input string ; if current character is a digit ; if current character is an alphabet ; increment sum by number found earlier ( if any ) ; reset temporary str1ing to empty ; atoi ( temp . c_str1 ( ) ) takes care of trailing numbers ; 
def findSum(str1):
    temp = "0"
    Sum = 0
    for ch in str1:
        if (ch .isdigit()):
            temp += ch
        else:
            Sum += int(temp)
            temp = "0"
    return Sum + int(temp)


str1 = "12abc20yz68"
print(findSum(str1))

# Expected output:
100
# count number of substrings with exactly k distinct characters | function to count number of substrings with exactly k unique characters ; initialize result ; to store count of characters from ' a ' to ' z ' ; consider all substrings beginning with str [ i ] ; initializing array with 0 ; consider all substrings between str [ i . . j ] ; if this is a new character for this substring , increment dist_count . ; increment count of current character ; if distinct character count becomes k , then increment result . ; 
def countkDist(str1, k):
    n = len(str1)
    res = 0
    cnt = [0] * 27
    for i in range(0, n):
        dist_count = 0
        cnt = [0] * 27
        for j in range(i, n):
            if (cnt[ord(str1[j]) - 97] == 0):
                dist_count += 1
            cnt[ord(str1[j]) - 97] += 1
            if (dist_count == k):
                res += 1
            if (dist_count > k):
                break
    return res


if __name__ == "__main__":
    str1 = "abcbaa"
    k = 3
    print("Total substrings with exactly", k, "distinct characters : ", end="")
    print(countkDist(str1, k))

# Expected output:
Total substrings with exactly 3 distinct characters : 8
# lower case to upper case | converts a string to uppercase ; 
def to_upper(string):
    for i in range(len(string)):
        if ('a' <= string[i] <= 'z'):
            string = (string[0:i] + chr(ord(string[i]) -
                      ord('a') + ord('A')) + string[i + 1:])
    return string


if __name__ == '__main__':
    str = "geeksforgeeks"
    print(to_upper(str))

# Expected output:
GEEKSFORGEEKS
# longest common prefix using character by character matching | a function to find the string having the minimum length and returns that length ; a function that returns the longest common prefix from the array of strings ; our resultant string char current ; the current character ; current character ( must be same in all strings to be a part of result ) ; append to result ; 
def findMinLength(arr, n):
    min = len(arr[0])
    for i in range(1, n):
        if (len(arr[i]) < min):
            min = len(arr[i])
    return (min)


def commonPrefix(arr, n):
    minlen = findMinLength(arr, n)
    result = ""
    for i in range(minlen):
        current = arr[0][i]
        for j in range(1, n):
            if (arr[j][i] != current):
                return result
        result = result + current
    return (result)


if __name__ == "__main__":
    arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
    n = len(arr)
    ans = commonPrefix(arr, n)
    if (len(ans)):
        print("The longest common prefix is ", ans)
    else:
        print("There is no common prefix")

# Expected output:
The longest common prefix is  gee
# check if two given strings are isomorphic to each other | python program to check if two strings are isomorphic ; this function returns true if str1 and str2 are isomorphic ; length of both strings must be same for one to one corresponance ; to mark visited characters in str2 ; to store mapping of every character from str1 to that of str2 . initialize all entries of map as - 1 ; process all characters one by one ; if current character of str1 is seen first time in it . ; if current character of st2 is already seen , one to one mapping not possible ; mark current character of str2 as visited ; store mapping of current characters ; if this is not first appearance of current character in str1 , then check if previous appearance mapped to same character of str2 ; 

MAX_CHARS = 256


def areIsomorphic(string1, string2):
    m = len(string1)
    n = len(string2)
    if m != n:
        return False
    marked = [False] * MAX_CHARS
    map = [-1] * MAX_CHARS
    for i in range(n):
        if map[ord(string1[i])] == -1:
            if marked[ord(string2[i])]:
                return False
            marked[ord(string2[i])] = True
            map[ord(string1[i])] = string2[i]
        elif map[ord(string1[i])] != string2[i]:
            return False
    return True


print(areIsomorphic("aab", "xxy"))
print(areIsomorphic("aab", "xyz"))

# Expected output:
True
False
# minimum insertions to form shortest palindrome | returns true if a string str [ st . . end ] is palindrome ; returns count of insertions on left side to make str [ ] a palindrome ; find the largest prefix of given string that is palindrome . ; characters after the palindromic prefix must be added at the beginning also to make the complete string palindrome ; 
def isPalin(str, st, end):
    while (st < end):
        if (str[st] != str[end]):
            return False
        st += 1
        end - -1
    return True


def findMinInsert(str, n):
    for i in range(n - 1, -1, -1):
        if (isPalin(str, 0, i)):
            return (n - i - 1)


Input = "JAVA"
print(findMinInsert(Input, len(Input)))

# Expected output:
3
# remove repeated digits in a given number | python 3 program to remove repeated digits ; store first digits as previous digit ; initialize power ; iterate through all digits of n , note that the digits are processed from least significant digit to most significant digit . ; store current digit ; add the current digit to the beginning of result ; update previous result and power ; remove last digit from n ; 
def removeRecur(n):
    prev_digit = n % 10
    pow = 10
    res = prev_digit
    while (n):
        curr_digit = n % 10
        if (curr_digit != prev_digit):
            res += curr_digit * pow
            prev_digit = curr_digit
            pow *= 10
        n = int(n / 10)
    return res


if __name__ == '__main__':
    n = 12224
    print(removeRecur(n))

# Expected output:
124
# write your own atoi ( ) | a simple python3 program for implementation of atoi ; if whitespaces then ignore . ; sign of number ; checking for valid input ; handling overflow test case ; 

import sys


def myAtoi(Str):
    sign, base, i = 1, 0, 0
    while (Str[i] == ' '):
        i += 1
    if (Str[i] == '-' or Str[i] == '+'):
        sign = 1 - 2 * (Str[i] == '-')
        i += 1
    while (i < len(Str) and Str[i] >= '0' and Str[i] <= '9'):
        if (base > (sys .maxsize // 10) or (base ==
                                            (sys .maxsize // 10) and (Str[i] - '0') > 7)):
            if (sign == 1):
                return sys .maxsize
            else:
                return -(sys .maxsize)
        base = 10 * base + (ord(Str[i]) - ord('0'))
        i += 1
    return base * sign


Str = list(" -123")
val = myAtoi(Str)
print(val)

# Expected output:
-123
# check whether two strings are anagram of each other | python program to check if two strings are anagrams of each other ; function to check if two strings are anagrams of each other ; create a count array and initialize all values as 0 ; for each character in input strings , increment count in the corresponding count array ; if both strings are of different length . removing this condition will make the program fail for strings like " aaca " and " aca " ; see if there is any non - zero value in count array ; 

NO_OF_CHARS = 256


def areAnagram(str1, str2):
    count = [0 for i in range(NO_OF_CHARS)]
    i = 0
    for i in range(len(str1)):
        count[ord(str1[i]) - ord('a')] += 1
        count[ord(str2[i]) - ord('a')] -= 1
    if (len(str1) != len(str2)):
        return False
    for i in range(NO_OF_CHARS):
        if (count[i] != 0):
            return False
    return True


str1 = "geeksforgeeks"
str2 = "forgeeksgeeks"
if (areAnagram(str1, str2)):
    print("The two strings are anagram of each other")
else:
    print("The two strings are not anagram of each other")

# Expected output:
The two strings are anagram of each other
# length of the longest substring without repeating characters | this functionr eturns true if all characters in strr [ i . . j ] are distinct , otherwise returns false ; note : default values in visited are false ; returns length of the longest substring with all distinct characters . ; result ; 
def areDistinct(strr, i, j):
    visited = [0] * (26)
    for k in range(i, j + 1):
        if (visited[ord(strr[k]) - ord('a')]):
            return False
        visited[ord(strr[k]) - ord('a')] = True
    return True


def longestUniqueSubsttr(strr):
    n = len(strr)
    res = 0
    for i in range(n):
        for j in range(i, n):
            if (areDistinct(strr, i, j)):
                res = max(res, j - i + 1)
    return res


if __name__ == '__main__':
    strr = "geeksforgeeks"
    print("The input is ", strr)
    len = longestUniqueSubsttr(strr)
    print("The length of the longest "
          "non-repeating character substring is ", len)

# Expected output:
The input is  geeksforgeeks
The length of the longest non-repeating character substring is  7
# remove duplicates from a given string | function to make the string unique ; loop to traverse the string and check for repeating chars using indexof ( ) method in java ; character at i 'th index of s ; if c is present in str , it returns the index of c , else it returns - 1 print ( st . index ( c ) ) ; adding c to str if - 1 is returned ; 
def unique(s):
    st = ""
    length = len(s)
    for i in range(length):
        c = s[i]
        if c not in st:
            st += c
    return st


if __name__ == "__main__":
    s = "geeksforgeeks"
    print(unique(s))

# Expected output:
geksfor
# sum of all subsets whose sum is a perfect number from a given array | python3 program for the above approach ; function to check is a given number is a perfect number or not ; stores the sum of its divisors ; add all divisors of x to sum_div ; if the sum of divisors is equal to the given number , return true ; otherwise , return false ; function to find sum of all subsets from an array whose sum is a perfect number ; prthe current subset sum if it is a perfect number ; check if sum is a perfect number or not ; calculate sum of the subset including arr [ l ] ; calculate sum of the subset excluding arr [ l ] ; 

import math


def isPerfect(x):
    sum_div = 1
    for i in range(2, (x // 2) + 1):
        if (x % i == 0):
            sum_div += i
    if (sum_div == x):
        return 1
    else:
        return 0


def subsetSum(arr, l, r, sum):
    if (l > r):
        if (isPerfect(sum) != 0):
            print(sum, end=" ")
        return
    subsetSum(arr, l + 1, r, sum + arr[l])
    subsetSum(arr, l + 1, r, sum)


arr = [5, 4, 6]
N = len(arr)
subsetSum(arr, 0, N - 1, 0)

# Expected output:
6
# print all possible ways to split an array into k subsets | utility function to find all possible ways to split array into k subsets ; if count of elements in k subsets are greater than or equal to n ; if count of subsets formed is equal to k ; print k subsets by splitting array into k subsets ; print current subset ; if current element is the last element of the subset ; otherwise ; if any subset is occupied , then push the element in that first ; recursively do the same for remaining elements ; backtrack ; otherwise , push it in an empty subset and increase the subset count by 1 ; break to avoid the case of going in other empty subsets , if available , and forming the same combination ; function to to find all possible ways to split array into k subsets ; stores k subset by splitting array into k subsets ; size of each subset must be less than the number of elements ; 
def PartitionSub(arr, i, N, K, nos, v):
    if (i >= N):
        if (nos == K):
            for x in range(len(v)):
                print("{ ", end="")
                for y in range(len(v[x])):
                    print(v[x][y], end="")
                    if (y == len(v[x]) - 1):
                        print(" ", end="")
                    else:
                        print(", ", end="")
                if (x == len(v) - 1):
                    print("}", end="")
                else:
                    print("}, ", end="")
            print("",  end="")
        return
    for j in range(K):
        if (len(v[j]) > 0):
            v[j].append(arr[i])
            PartitionSub(arr, i + 1, N, K, nos, v)
            v[j].remove(v[j][len(v[j]) - 1])
        else:
            v[j].append(arr[i])
            PartitionSub(arr, i + 1, N, K, nos + 1, v)
            v[j].remove(v[j][len(v[j]) - 1])
            break


def partKSubsets(arr, N, K):
    v = [[]for i in range(K)]
    if (K == 0 or K > N):
        print("Not Possible", end="")
    else:
        print("The Subset Combinations are: ")
        PartitionSub(arr, 0, N, K, 0, v)


if __name__ == '__main__':
    arr = [1, 2, 3, 4]
    K = 2
    N = len(arr)
    partKSubsets(arr, N, K)

# Expected output:
The Subset Combinations are: 
{ 1, 2, 3 }, { 4 }{ 1, 2, 4 }, { 3 }{ 1, 2 }, { 3, 4 }{ 1, 3, 4 }, { 2 }{ 1, 3 }, { 2, 4 }{ 1, 4 }, { 2, 3 }{ 1 }, { 2, 3, 4 }