giulio98/xlcost-single-prompt huggingface dataset:
# number of triangles in an undirected graph | number of vertices in the graph ; utility function for matrix multiplication ; utility function to calculate trace of a matrix ( sum ofdiagnonal elements ) ; utility function for calculating number of triangles in graph ; to store graph ^ 2 ; to store graph ^ 3 ; initialising aux matrices with 0 ; aux2 is graph ^ 2 now printmatrix ( aux2 ) ; after this multiplication aux3 is graph ^ 3 printmatrix ( aux3 ) ; 

V = 4


def multiply(A, B, C):
    global V
    for i in range(V):
        for j in range(V):
            C[i][j] = 0
            for k in range(V):
                C[i][j] += A[i][k] * B[k][j]


def getTrace(graph):
    global V
    trace = 0
    for i in range(V):
        trace += graph[i][i]
    return trace


def triangleInGraph(graph):
    global V
    aux2 = [[None] * V for i in range(V)]
    aux3 = [[None] * V for i in range(V)]
    for i in range(V):
        for j in range(V):
            aux2[i][j] = aux3[i][j] = 0
    multiply(graph, graph, aux2)
    multiply(graph, aux2, aux3)
    trace = getTrace(aux3)
    return trace // 6


graph = [[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]]
print("Total number of Triangle in Graph :", triangleInGraph(graph))

# Expected output:
Total number of Triangle in Graph : 2
# count subsequence of length three in a given string | function to find number of occurrences of a subsequence of length three in a string ; variable to store no of occurrences ; loop to find first character ; loop to find 2 nd character ; loop to find 3 rd character ; increment count if subsequence is found ; 
def findOccurrences(str, substr):
    counter = 0
    for i in range(0, len(str)):
        if (str[i] == substr[0]):
            for j in range(i + 1, len(str)):
                if (str[j] == substr[1]):
                    for k in range(j + 1, len(str)):
                        if (str[k] == substr[2]):
                            counter = counter + 1
    return counter


str = "GFGFGYSYIOIWIN"
substr = "GFG"
print(findOccurrences(str, substr))

# Expected output:
4
# count subsequence of length three in a given string | function to find number of occurrences of a subsequence of length three in a string ; calculate length of string ; auxiliary array to store occurrences of first character ; auxiliary array to store occurrences of third character ; calculate occurrences of first character upto ith index from left ; calculate occurrences of third character upto ith index from right ; variable to store total number of occurrences ; loop to find the occurrences of middle element ; if middle character of subsequence is found in the string ; multiply the total occurrences of first character before middle character with the total occurrences of third character after middle character ; 
def findOccurrences(str1, substr):
    n = len(str1)
    preLeft = [0 for i in range(n)]
    preRight = [0 for i in range(n)]
    if (str1[0] == substr[0]):
        preLeft[0] += 1
    for i in range(1, n):
        if (str1[i] == substr[0]):
            preLeft[i] = preLeft[i - 1] + 1
        else:
            preLeft[i] = preLeft[i - 1]
    if (str1[n - 1] == substr[2]):
        preRight[n - 1] += 1
    i = n - 2
    while (i >= 0):
        if (str1[i] == substr[2]):
            preRight[i] = preRight[i + 1] + 1
        else:
            preRight[i] = preRight[i + 1]
        i -= 1
    counter = 0
    for i in range(1, n - 1):
        if (str1[i] == str1[1]):
            total = preLeft[i - 1] * preRight[i + 1]
            counter += total
    return counter


if __name__ == '__main__':
    str1 = "GFGFGYSYIOIWIN"
    substr = "GFG"
    print(findOccurrences(str1, substr))

# Expected output:
4
# mirror characters of a string | function which take the given string and the position from which the reversing shall be done and returns the modified string ; creating a string having reversed alphabetical order ; the string up to the point specified in the question , the string remains unchanged and from the point up to the length of the string , we reverse the alphabetical order ; 
def compute(st, n):
    reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"
    l = len(st)
    answer = ""
    for i in range(0, n):
        answer = answer + st[i]
    for i in range(n, l):
        answer = (answer + reverseAlphabet[ord(st[i]) - ord('a')])
    return answer


st = "pneumonia"
n = 4
answer = compute(st, n - 1)
print(answer)

# Expected output:
pnefnlmrz
# lexicographically first alternate vowel and consonant string | python3 implementation of lexicographically first 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 lexicographically first alternate vowel and consonant string ; hash table to store frequencies of each character in ' str ' char_freq = [ 0 ] * size initialize all elements of char_freq [ ] to 0 ; count vowels ; count consonants ; update frequency of ' ch ' in char_freq [ ] ; no such string can be formed ; form the vowel string ' vstr ' and consonant string ' cstr ' which contains characters in lexicographical order ; 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 ; 

SIZE = 26


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
    j = start
    while j < l:
        finalStr += str1[i] + str2[j]
        i += 1
        j += 1
    return finalStr


def findAltStr(string):
    char_freq = [0] * SIZE
    nv = 0
    nc = 0
    vstr = ""
    cstr = ""
    l = len(string)

    for i in range(l):
        ch = string[i]
        if isVowel(ch):
            nv += 1
        else:
            nc += 1
        char_freq[ord(ch) - 97] += 1
    if abs(nv - nc) >= 2:
        return "no such string"
    for i in range(SIZE):
        ch = chr(i + 97)
        for j in range(1, char_freq[i] + 1):
            if isVowel(ch):
                vstr += ch
            else:
                cstr += ch
    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__":
    string = "aeroplane"
    print(findAltStr(string))

# Expected output:
alanepero
# print all possible strings that can be made by placing spaces | python 3 program to print all strings that can be made by placing spaces ; function to print all subsequences ; 

from math import pow


def printSubsequences(str):
    n = len(str)
    opsize = int(pow(2, n - 1))
    for counter in range(opsize):
        for j in range(n):
            print(str[j], end="")
            if (counter & (1 << j)):
                print(" ", end="")
        print("",  end="")


if __name__ == '__main__':
    str = "ABC"
    printSubsequences(str)

# Expected output:
ABCA BCAB CA B C
# find n | python3 program to print n - th permutation ; utility for calculating factorials ; function for nth permutation ; length of given string ; count frequencies of all characters ; out string for output string ; iterate till sum equals n ; we update both n and sum in this loop . ; check for characters present in freq [ ] ; remove character ; calculate sum after fixing a particular char ; if sum > n fix that char as present char and update sum and required nth after fixing char at that position ; if sum < n , add character back ; if sum == n means this char will provide its greatest permutation as nth permutation ; print result ; 

MAX_CHAR = 26
MAX_FACT = 20
fact = [None] * (MAX_FACT)


def precomputeFactorials():
    fact[0] = 1
    for i in range(1, MAX_FACT):
        fact[i] = fact[i - 1] * i


def nPermute(string, n):
    precomputeFactorials()
    length = len(string)
    freq = [0] * (MAX_CHAR)
    for i in range(0, length):
        freq[ord(string[i]) - ord('a')] += 1
    out = [None] * (MAX_CHAR)
    Sum, k = 0, 0
    while Sum != n:
        Sum = 0
        for i in range(0, MAX_CHAR):
            if freq[i] == 0:
                continue
            freq[i] -= 1
            xsum = fact[length - 1 - k]
            for j in range(0, MAX_CHAR):
                xsum = xsum // fact[freq[j]]
            Sum += xsum
            if Sum >= n:
                out[k] = chr(i + ord('a'))
                n -= Sum - xsum
                k += 1
                break
            if Sum < n:
                freq[i] += 1
    i = MAX_CHAR - 1
    while k < length and i >= 0:
        if freq[i]:
            out[k] = chr(i + ord('a'))
            freq[i] -= 1
            i += 1
            k += 1
        i -= 1
    print(''.join(out[:k]))


if __name__ == "__main__":
    n = 2
    string = "geeksquiz"
    nPermute(string, n)

# Expected output:
eegikqszu
# minimum number of deletions so that no two consecutive are same | function for counting deletions ; if two consecutive characters are the same , delete one of them . ; 
def countDeletions(string):
    ans = 0
    for i in range(len(string) - 1):
        if (string[i] == string[i + 1]):
            ans += 1
    return ans


string = "AAABBB"
print(countDeletions(string))

# Expected output:
4
# count words that appear exactly two times in an array of words | returns count of words with frequency exactly 2. ; 
def countWords(stri, n):
    m = dict()
    for i in range(n):
        m[stri[i]] = m .get(stri[i], 0) + 1
    res = 0
    for i in m .values():
        if i == 2:
            res += 1
    return res


s = [
    "hate",
    "love",
    "peace",
    "love",
    "peace",
    "hate",
    "love",
    "peace",
    "love",
    "peace"]
n = len(s)
print(countWords(s, n))

# Expected output:
1
# check whether a given graph is bipartite or not | python3 program to find out whether a given graph is bipartite or not using recursion . ; color this pos as c and all its neighbours and 1 - c ; start is vertex 0 ; two colors 1 and 0 ; 

V = 4


def colorGraph(G, color, pos, c):
    if color[pos] != -1 and color[pos] != c:
        return False
    color[pos] = c
    ans = True
    for i in range(0, V):
        if G[pos][i]:
            if color[i] == -1:
                ans &= colorGraph(G, color, i, 1 - c)
            if color[i] != -1 and color[i] != 1 - c:
                return False
        if not ans:
            return False
    return True


def isBipartite(G):
    color = [-1] * V
    pos = 0
    return colorGraph(G, color, pos, 1)


if __name__ == "__main__":
    G = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]
    if isBipartite(G):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# nth even length palindrome | python3 program to find n = th even length string . ; function to find nth even length palindrome ; string r to store resultant palindrome . initialize same as s ; in this loop string r stores reverse of string s after the string s in consecutive manner . ; 

import math as mt


def evenlength(n):
    res = n
    for j in range(len(n) - 1, -1, -1):
        res += n[j]
    return res


n = "10"
print(evenlength(n))

# Expected output:
1001
# determine if a string has all unique characters | python program to illustrate string with unique characters using brute force technique ; if at any time we encounter 2 same characters , return false ; if no duplicate characters encountered , return true ; 
def uniqueCharacters(str):
    for i in range(len(str)):
        for j in range(i + 1, len(str)):
            if (str[i] == str[j]):
                return False
    return True


str = "GeeksforGeeks"
if (uniqueCharacters(str)):
    print("The String ", str, " has all unique characters")
else:
    print("The String ", str, " has duplicate characters")

# Expected output:
The String  GeeksforGeeks  has duplicate characters
# check if given string can be split into four distinct strings | return if the given string can be split or not . ; we can always break a of size 10 or more into four distinct strings . ; brute force ; making 4 from the given ; checking if they are distinct or not . ; 
def check(s):
    if (len(s) >= 10):
        return True
    for i in range(1, len(s)):
        for j in range(i + 1, len(s)):
            for k in range(j + 1, len(s)):
                s1 = s[0:i]
                s2 = s[i:j - i]
                s3 = s[j:k - j]
                s4 = s[k:len(s) - k]
                if (s1 != s2 and s1 != s3 and s1 !=
                        s4 and s2 != s3 and s2 != s4 and s3 != s4):
                    return True
    return False


if __name__ == '__main__':
    str = "aaabb"
    print("Yes")if (check(str))else print("NO")

# Expected output:
NO
# multiply large numbers represented as strings | multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; below two indexes are used to find positions in result . ; go from right to left in num1 ; to shift position to left after every multiplication of a digit in num2 ; go from right to left in num2 ; take current digit of second number ; multiply with current digit of first number and add result to previously stored result at current position . ; carry for next iteration ; store result ; store carry in next cell ; to shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; if all were '0' s - means either both or one of num1 or num2 were '0 ; generate the result string ; 
def multiply(num1, num2):
    len1 = len(num1)
    len2 = len(num2)
    if len1 == 0 or len2 == 0:
        return "0"
    result = [0] * (len1 + len2)
    i_n1 = 0
    i_n2 = 0
    for i in range(len1 - 1, -1, -1):
        carry = 0
        n1 = ord(num1[i]) - 48
        i_n2 = 0
        for j in range(len2 - 1, -1, -1):
            n2 = ord(num2[j]) - 48
            summ = n1 * n2 + result[i_n1 + i_n2] + carry
            carry = summ // 10
            result[i_n1 + i_n2] = summ % 10
            i_n2 += 1
        if (carry > 0):
            result[i_n1 + i_n2] += carry
        i_n1 += 1
    i = len(result) - 1
    while (i >= 0 and result[i] == 0):
        i -= 1

    if (i == -1):
        return "0"
    s = ""
    while (i >= 0):
        s += chr(result[i] + 48)
        i -= 1
    return s


str1 = "1235421415454545454545454544"
str2 = "1714546546546545454544548544544545"
if ((str1[0] == '-' or str2[0] == '-') and (str1[0] != '-' or str2[0] != '-')):
    print("-", end='')
if (str1[0] == '-' and str2[0] != '-'):
    str1 = str1[1:]
elif (str1[0] != '-' and str2[0] == '-'):
    str2 = str2[1:]
elif (str1[0] == '-' and str2[0] == '-'):
    str1 = str1[1:]
    str2 = str2[1:]
print(multiply(str1, str2))

# Expected output:
2118187521397235888154583183918321221520083884298838480662480
# find an equal point in a string of brackets | method to find an equal index ; store the number of opening brackets at each index ; store the number of closing brackets at each index ; check if there is no opening or closing brackets ; check if there is any index at which both brackets are equal ; 
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
    for i in range(1, l):
        if (str[i] == '('):
            open[i + 1] = open[i] + 1
        else:
            open[i + 1] = open[i]
    for i in range(l - 2, -1, -1):
        if (str[i] == ')'):
            close[i] = close[i + 1] + 1
        else:
            close[i] = close[i + 1]
    if (open[l] == 0):
        return len
    if (close[0] == 0):
        return 0
    for i in range(l + 1):
        if (open[i] == close[i]):
            index = i
    return index


str = "(()))(()()())))"
print(findIndex(str))

# Expected output:
9
# convert decimal fraction to binary number | function to convert decimal to binary upto k - precision after decimal point ; fetch the integral part of decimal number ; fetch the fractional part decimal number ; conversion of integral part to binary equivalent ; append 0 in binary ; reverse string to get original binary equivalent ; append point before conversion of fractional part ; conversion of fractional part to binary equivalent ; find next bit in fraction ; 
def decimalToBinary(num, k_prec):
    binary = ""
    Integral = int(num)
    fractional = num - Integral
    while (Integral):
        rem = Integral % 2
        binary += str(rem)
        Integral //= 2
    binary = binary[::-1]
    binary += '.'
    while (k_prec):
        fractional *= 2
        fract_bit = int(fractional)
        if (fract_bit == 1):
            fractional -= fract_bit
            binary += '1'
        else:
            binary += '0'
        k_prec -= 1
    return binary


if __name__ == "__main__":
    n = 4.47
    k = 3
    print(decimalToBinary(n, k))
    n = 6.986
    k = 5
    print(decimalToBinary(n, k))

# Expected output:
100.011
110.11111
# difference of two large numbers | returns true if str1 is smaller than str2 , else false . ; calculate lengths of both string ; function for finding difference of larger numbers ; before proceeding further , make sure str1 is not smaller ; take an empty string for storing result ; calculate lengths of both string ; initially take carry zero ; traverse from end of both strings ; do school mathematics , compute difference of current digits and carry ; subtract remaining digits of str1 [ ] ; remove preceding 0 's ; reverse resultant string ; 
def isSmaller(str1, str2):
    n1 = len(str1)
    n2 = len(str2)
    if (n1 < n2):
        return True
    if (n2 < n1):
        return False
    for i in range(n1):
        if (str1[i] < str2[i]):
            return True
        elif (str1[i] > str2[i]):
            return False
    return False


def findDiff(str1, str2):
    if (isSmaller(str1, str2)):
        str1, str2 = str2, str1
    Str = ""
    n1 = len(str1)
    n2 = len(str2)
    diff = n1 - n2
    carry = 0
    for i in range(n2 - 1, -1, -1):
        sub = ((ord(str1[i + diff]) - ord('0')) -
               (ord(str2[i]) - ord('0')) - carry)
        if (sub < 0):
            sub += 10
            carry = 1
        else:
            carry = 0
        Str += chr(sub + ord('0'))
    for i in range(n1 - n2 - 1, -1, -1):
        if (str1[i] == '0' and carry):
            Str += '9'
            continue
        sub = (ord(str1[i]) - ord('0')) - carry
        if (i > 0 or sub > 0):
            Str += chr(sub + ord('0'))
        carry = 0
    Str = Str[::-1]
    return Str


str1 = "88"
str2 = "1079"
print(findDiff(str1, str2))

# Expected output:
991
# efficiently check if a string has all unique characters without using any additional data structure | 
def unique(s):
    s = sorted(s)
    for i in range(len(s) - 1):
        if (s[i] == s[i + 1]):
            return False
            break
    return True


if (unique("abcdd")):
    print("String is Unique")
else:
    print("String is not Unique")

# Expected output:
String is not Unique
# check if two strings are k | optimized python3 program to check if two strings are k anagram or not . ; function to check if str1 and str2 are k - anagram or not ; if both strings are not of equal length then return false ; store the occurrence of all characters in a hash_array ; store the occurrence of all characters in a hash_array ; return true if count is less than or equal to k ; 

MAX_CHAR = 26


def areKAnagrams(str1, str2, k):
    n = len(str1)
    if (len(str2) != n):
        return False
    hash_str1 = [0] * (MAX_CHAR)
    for i in range(n):
        hash_str1[ord(str1[i]) - ord('a')] += 1
    count = 0
    for i in range(n):
        if (hash_str1[ord(str2[i]) - ord('a')] > 0):
            hash_str1[ord(str2[i]) - ord('a')] -= 1
        else:
            count += 1
        if (count > k):
            return False
    return True


str1 = "fodr"
str2 = "gork"
k = 2
if (areKAnagrams(str1, str2, k)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# nth character in concatenated decimal string | method to get dth digit of number n ; method to return nth character in concatenated decimal string ; sum will store character escaped till now ; dist will store numbers escaped till now ; loop for number lengths ; nine * len will be incremented characters and nine will be incremented numbers ; restore variables to previous correct state ; get distance from last one digit less maximum number ; d will store dth digit of current number ; method will return dth numbered digit of ( dist + diff ) number ; 
def getDigit(N, d):
    string = str(N)
    return string[d - 1]


def getNthChar(N):
    sum = 0
    nine = 9
    dist = 0
    for len in range(1, N):
        sum += nine * len
        dist += nine
        if (sum >= N):
            sum -= nine * len
            dist -= nine
            N -= sum
            break
        nine *= 10
    diff = (N / len) + 1
    d = N % len
    if (d == 0):
        d = len
    return getDigit(dist + diff, d)


N = 251
print(getNthChar(N))

# Expected output:
2
# minimum characters to be added at front to make string palindrome | function for checking string is palindrome or not ; 
def ispalindrome(s):
    l = len(s)
    i = 0
    j = l - 1
    while i <= j:
        if (s[i] != s[j]):
            return False
        i += 1
        j -= 1
    return True


if __name__ == "__main__":
    s = "BABABAA"
    cnt = 0
    flag = 0
    while (len(s) > 0):
        if (ispalindrome(s)):
            flag = 1
            break
        else:
            cnt += 1
            s = s[:-1]
    if (flag):
        print(cnt)

# Expected output:
2
# count characters at same position as in english alphabet | function to count the number of characters at same position as in english alphabets ; traverse the input string ; check that index of characters of string is same as of english alphabets by using ascii values and the fact that all lower case alphabetic characters come together in same order in ascii table . and same is true for upper case . ; 
def findCount(str):
    result = 0
    for i in range(len(str)):
        if ((i == ord(str[i]) - ord('a')) or (i == ord(str[i]) - ord('A'))):
            result += 1
    return result


str = 'AbgdeF'
print(findCount(str))

# Expected output:
5