giulio98/xlcost-single-prompt huggingface dataset:
# find all factors of large perfect square natural number in o ( sqrt ( sqrt ( n ) ) | python 3 program to find the factors of large perfect square number in o ( sqrt ( sqrt ( n ) ) ) time ; function that find all the prime factors of n ; store the sqrt ( n ) in temp ; initialise factor array with 1 as a factor in it ; check divisibility by 2 ; store the factors twice ; check for other prime factors other than 2 ; if j is a prime factor ; store the prime factor twice ; if j is prime number left other than 2 ; store j twice ; initialise matrix m to to store all the factors ; tpc for rows tpr for column ; initialise m [ 0 ] [ 0 ] = 1 as it also factor of n ; traversing factor array ; if current and previous factors are not same then move to next row and insert the current factor ; if current and previous factors are same then , insert the factor with previous factor inserted in matrix m ; the arr1 [ ] and arr2 [ ] used to store all the factors of n ; initialise arrays as 1 ; traversing the matrix m print ( " tpr ▁ " , tpr ) ; traversing till column element doesn 't become 0 ; store the product of every element of current row with every element in arr1 [ ] ; copying every element of arr2 [ ] in arr1 [ ] ; length of arr2 [ ] and arr1 [ ] are equal after copying ; print all the factors ; 

import math
MAX = 100000


def findFactors(N):
    temp = int(math .sqrt(N))
    factor = [1] * MAX
    len1 = 1
    while (temp % 2 == 0):
        factor[len1] = 2
        len1 += 1
        factor[len1] = 2
        len1 += 1
        temp //= 2
    sqt = math .sqrt(temp)
    for j in range(3, math .ceil(sqt), 2):
        while (temp % j == 0):
            factor[len1] = j
            len1 += 1
            factor[len1] = j
            len1 += 1
            temp //= j
    if (temp > 2):
        factor[len1] = temp
        len1 += 1
        factor[len1] = temp
        len1 += 1
    M = [[0 for x in range(MAX)]for y in range(len1)]
    tpc, tpr = 0, 0
    M[0][0] = 1
    j = 1
    while (j < len1):
        if (factor[j] != factor[j - 1]):
            tpr += 1
            M[tpr][0] = factor[j]
            j += 1
            tpc = 1
        else:
            M[tpr][tpc] = M[tpr][tpc - 1] * factor[j]
            j += 1
            tpc += 1
    arr1 = [0] * MAX
    arr2 = [0] * MAX
    l1 = l2 = 1
    arr1[0] = 1
    arr2[0] = 1
    for i in range(1, tpr + 1):
        j = 0
        while M[i][j] != 0:
            for k in range(l1):
                arr2[l2] = arr1[k] * M[i][j]
                l2 += 1
            j += 1
        for j in range(l1, l2):
            arr1[j] = arr2[j]
        l1 = l2
    for i in range(l2):
        print(arr2[i], end=" ")


if __name__ == "__main__":
    N = 900
    findFactors(N)

# Expected output:
1 2 4 3 6 12 9 18 36 5 10 20 15 30 60 45 90 180 25 50 100 75 150 300 225 450 900
# construct a matrix such that union of ith row and ith column contains every element from 1 to 2 n | python3 implementation of the above approach ; function to find the square matrix ; for matrix of order 1 , it will contain only 1 ; for matrix of odd order , it is not possible ; for matrix of even order ; all diagonal elements of the matrix can be n itself . ; assign values at desired place in the matrix ; loop to add n in the lower half of the matrix such that it contains elements from 1 to 2 * n - 1 ; loop to print the matrix ; 

import numpy as np
matrix = np .zeros((100, 100))


def printRequiredMatrix(n):
    if (n == 1):
        print("1")
    elif (n % 2 != 0):
        print("-1")
    else:
        for i in range(n):
            matrix[i][i] = n
        u = n - 1
        for i in range(n - 1):
            matrix[i][u] = i + 1
            for j in range(1, n // 2):
                a = (i + j) % (n - 1)
                b = (i - j + n - 1) % (n - 1)
                if (a < b):
                    a, b = b, a
                matrix[b][a] = i + 1
        for i in range(n):
            for j in range(i):
                matrix[i][j] = matrix[j][i] + n
        for i in range(n):
            for j in range(n):
                print(matrix[i][j], end=" ")
            print()
    print()


if __name__ == "__main__":
    n = 1
    printRequiredMatrix(n)
    n = 3
    printRequiredMatrix(n)
    n = 6
    printRequiredMatrix(n)

# Expected output:
1

-1

6.0 4.0 2.0 5.0 3.0 1.0 
10.0 6.0 5.0 3.0 1.0 2.0 
8.0 11.0 6.0 1.0 4.0 3.0 
11.0 9.0 7.0 6.0 2.0 4.0 
9.0 7.0 10.0 8.0 6.0 5.0 
7.0 8.0 9.0 10.0 11.0 6.0
# count of sub | function to find the count of substrings with equal no . of consecutive 0 ' s ▁ and ▁ 1' s ; to store the total count of substrings ; traversing the string ; count of consecutive 0 ' s ▁ & ▁ 1' s ; counting subarrays of type "01" ; count the consecutive 0 's ; if consecutive 0 ' s ▁ ▁ ends ▁ then ▁ check ▁ for ▁ ▁ consecutive ▁ 1' s ; counting consecutive 1 's ; counting subarrays of type "10" ; count consecutive 1 's ; if consecutive 1 ' s ▁ ▁ ends ▁ then ▁ check ▁ for ▁ ▁ consecutive ▁ 0' s ; count consecutive 0 's ; update the total count of substrings with minimum of ( cnt0 , cnt1 ) ; return answer ; 
def countSubstring(S, n):
    ans = 0
    i = 0
    while (i < n):
        cnt0 = 0
        cnt1 = 0
        if (S[i] == '0'):
            while (i < n and S[i] == '0'):
                cnt0 += 1
                i += 1
            j = i
            while (j < n and S[j] == '1'):
                cnt1 += 1
                j += 1
        else:
            while (i < n and S[i] == '1'):
                cnt1 += 1
                i += 1
            j = i
            while (j < n and S[j] == '0'):
                cnt0 += 1
                j += 1
        ans += min(cnt0, cnt1)
    return ans


if __name__ == "__main__":
    S = "0001110010"
    n = len(S)
    print(countSubstring(S, n))

# Expected output:
7
# print n numbers such that their sum is a perfect cube | function to find the n numbers such that their sum is a perfect cube ; loop to find the ith term of the centered hexagonal number ; 
def findNumbers(n):
    i = 1
    while (i <= n):
        print((3 * i * (i - 1) + 1), end=" ")
        i += 1


n = 4
findNumbers(n)

# Expected output:
1 7 19 37
# largest n digit octal number which is a perfect square | python3 implementation to find the maximum n - digit octal number which is perfect square ; function to convert decimal number to a octal number ; array to store octal number ; counter for octal number array ; store remainder in octal array ; print octal number array in reverse order ; largest n - digit perfect square ; 

from math import sqrt, ceil


def decToOctal(n):
    octalNum = [0] * 100
    i = 0
    while (n != 0):
        octalNum[i] = n % 8
        n = n // 8
        i += 1
    for j in range(i - 1, -1, -1):
        print(octalNum[j], end="")
    print()


def nDigitPerfectSquares(n):
    decimal = pow(ceil(sqrt(pow(8, n))) - 1, 2)
    decToOctal(decimal)


if __name__ == "__main__":
    n = 2
    nDigitPerfectSquares(n)

# Expected output:
61
# reverse the substrings of the given string according to the given array of indices | function to reverse a string ; swap character starting from two corners ; function to reverse the string with the given array of indices ; reverse the from 0 to a [ 0 ] ; reverse the for a [ i ] to a [ i + 1 ] ; reverse string for a [ n - 1 ] to length ; 
def reverseStr(str, l, h):
    n = h - l
    for i in range(n // 2):
        str[i + l], str[n - i - 1 + l] = str[n - i - 1 + l], str[i + l]


def reverseString(s, A, n):
    reverseStr(s, 0, A[0])
    for i in range(1, n):
        reverseStr(s, A[i - 1], A[i])
    reverseStr(s, A[n - 1], len(s))


s = "abcdefgh"
s = [i for i in s]
A = [2, 4, 6]
n = len(A)
reverseString(s, A, n)
print("".join(s))

# Expected output:
badcfehg
# maximize the sum of differences of consecutive elements after removing exactly k elements | function to return the maximized sum ; remove any k internal elements ; 
def findSum(arr, n, k):
    if (k <= n - 2):
        return (arr[n - 1] - arr[0])
    return 0


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    n = len(arr)
    k = 1
    print(findSum(arr, n, k))

# Expected output:
3
# split the binary string into substrings with equal number of 0 s and 1 s | function to return the count of maximum substrings str can be divided into ; to store the count of 0 s and 1 s ; to store the count of maximum substrings str can be divided into ; it is not possible to split the string ; 
def maxSubStr(str, n):
    count0 = 0
    count1 = 0
    cnt = 0
    for i in range(n):
        if str[i] == '0':
            count0 += 1
        else:
            count1 += 1
        if count0 == count1:
            cnt += 1
    if cnt == 0:
        return -1
    return cnt


str = "0100110101"
n = len(str)
print(maxSubStr(str, n))

# Expected output:
4
# sum of the digits of square of the given number which has only 1 's as its digits | function to return the sum of the digits of num ^ 2 ; to store the number of 1 's ; find the sum of the digits of num ^ 2 ; 
def squareDigitSum(num):
    lengthN = len(num)
    result = (lengthN // 9) * 81 + (lengthN % 9)**2
    return result


if __name__ == "__main__":
    N = "1111"
    print(squareDigitSum(N))

# Expected output:
16
# check whether two strings contain same characters in same order | python3 implementation of the approach ; string class has a constructor that allows us to specify the size of string as first parameter and character to be filled in given size as the second parameter . ; function that returns true if the given strings contain same characters in same order ; get the first character of both strings ; now if there are adjacent similar character remove that character from s1 ; now if there are adjacent similar character remove that character from s2 ; if both the strings are equal then return true ; 
def getString(x):
    return x


def solve(s1, s2):
    a = getString(s1[0])
    b = getString(s2[0])
    for i in range(1, len(s1)):
        if s1[i] != s1[i - 1]:
            a += getString(s1[i])
    for i in range(1, len(s2)):
        if s2[i] != s2[i - 1]:
            b += getString(s2[i])
    if a == b:
        return True
    return False


s1 = "Geeks"
s2 = "Geks"
if solve(s1, s2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count number of distinct substrings of a given length | python3 implementation of above approach ; function to find the required count ; variable to the hash ; finding hash of substring ( 0 , l - 1 ) using random number x ; computing x ^ ( l - 1 ) ; unordered set to add hash values ; generating all possible hash values ; print the result ; 

x = 26
mod = 3001


def CntSubstr(s, l):
    hash = 0
    for i in range(l):
        hash = (hash * x + (ord(s[i]) - 97)) % mod
    pow_l = 1
    for i in range(l - 1):
        pow_l = (pow_l * x) % mod
    result = set()
    result .add(hash)
    for i in range(l, len(s)):
        hash = (
            (hash - pow_l * (ord(s[i - l]) - 97) + 2 * mod) * x + (ord(s[i]) - 97)) % mod
        result .add(hash)
    print(len(result))


if __name__ == "__main__":
    s = "abcba"
    l = 2
    CntSubstr(s, l)

# Expected output:
4
# count strings that end with the given pattern | function that return true if str1 ends with pat ; pattern is larger in length than the str1ing ; we match starting from the end while patlen is greater than or equal to 0. ; if at any index str1 doesn 't match  with pattern ; if str1 ends with the given pattern ; function to return the count of required str1ings ; if current str1ing ends with the given pattern ; 
def endsWith(str1, pat):
    patLen = len(pat)
    str1Len = len(str1)
    if (patLen > str1Len):
        return False
    patLen -= 1
    str1Len -= 1
    while (patLen >= 0):
        if (pat[patLen] != str1[str1Len]):
            return False
        patLen -= 1
        str1Len -= 1
    return True


def countOfstr1ings(pat, n, sArr):
    count = 0
    for i in range(n):
        if (endsWith(sArr[i], pat)):
            count += 1
    return count


pat = "ks"
n = 4
sArr = ["geeks", "geeksforgeeks", "games", "unit"]
print(countOfstr1ings(pat, n, sArr))

# Expected output:
2
# length of the longest substring with consecutive characters | function to return the ending index for the largest valid sub - str1ing starting from index i ; if the current character appears after the previous character according to the given circular alphabetical order ; function to return the length of the longest sub - str1ing of consecutive characters from str1 ; valid sub - str1ing exists from index i to end ; update the length ; 
def getEndingIndex(str1, n, i):
    i += 1
    while (i < n):
        curr = str1[i]
        prev = str1[i - 1]
        if ((curr == 'a' and prev == 'z') or (ord(curr) - ord(prev) == 1)):
            i += 1
        else:
            break
    return i - 1


def largestSubstr1(str1, n):
    Len = 0
    i = 0
    while (i < n):
        end = getEndingIndex(str1, n, i)
        Len = max(end - i + 1, Len)
        i = end + 1
    return Len


str1 = "abcabcdefabc"
n = len(str1)
print(largestSubstr1(str1, n))

# Expected output:
6
# sum of integers upto n with given unit digit ( set 2 ) | function to return the required sum ; decrement n ; 
def getSum(n, d):
    if (n < d):
        return 0
    while (n % 10 != d):
        n -= 1
    k = n // 10
    return ((k + 1) * d + (k * 10 + 10 * k * k) // 2)


if __name__ == "__main__":
    n = 30
    d = 3
    print(getSum(n, d))

# Expected output:
39
# maximum possible time that can be formed from four digits | python3 implementation of the approach ; function to return the updated frequency map for the array passed as argument ; function that returns true if the passed digit is present in the map after decrementing it 's frequency by 1 ; if map contains the digit ; decrement the frequency of the digit by 1 ; true here indicates that the digit was found in the map ; digit not found ; function to return the maximum possible time_value in 24 - hours format ; first digit of hours can be from the range [ 0 , 2 ] ; if no valid digit found ; if first digit of hours was chosen as 2 then the second digit of hours can be from the range [ 0 , 3 ] ; else it can be from the range [ 0 , 9 ] ; hours and minutes separator ; first digit of minutes can be from the range [ 0 , 5 ] ; second digit of minutes can be from the range [ 0 , 9 ] ; return the maximum possible time_value ; 

from collections import defaultdict


def getFrequencyMap(arr, n):
    hashMap = defaultdict(lambda: 0)
    for i in range(n):
        hashMap[arr[i]] += 1
    return hashMap


def hasDigit(hashMap, digit):
    if hashMap[digit] > 0:
        hashMap[digit] -= 1
        return True
    return False


def getMaxtime_value(arr, n):
    hashMap = getFrequencyMap(arr, n)
    flag = False
    time_value = ""
    for i in range(2, -1, -1):
        if hasDigit(hashMap, i):
            flag = True
            time_value += str(i)
            break
    if not flag:
        return "-1"
    flag = False
    if (time_value[0] == '2'):
        for i in range(3, -1, -1):
            if hasDigit(hashMap, i):
                flag = True
                time_value += str(i)
                break
    else:
        for i in range(9, -1, -1):
            if hasDigit(hashMap, i):
                flag = True
                time_value += str(i)
                break
    if not flag:
        return "-1"
    time_value += ":"
    flag = False
    for i in range(5, -1, -1):
        if hasDigit(hashMap, i):
            flag = True
            time_value += str(i)
            break
    if not flag:
        return "-1"
    flag = False
    for i in range(9, -1, -1):
        if hasDigit(hashMap, i):
            flag = True
            time_value += str(i)
            break
    if not flag:
        return "-1"
    return time_value


if __name__ == "__main__":
    arr = [0, 0, 0, 9]
    n = len(arr)
    print(getMaxtime_value(arr, n))

# Expected output:
09:00
# most frequent word in first string which is not present in second string | python3 implementation of above approach ; function to return frequent word from s1 that isn 't present in s2 ; create map of banned words ; find smallest and most frequent word ; check if word is not banned ; return answer ; 

from collections import defaultdict


def smallestFreq(S1, S2):
    banned = defaultdict(lambda: 0)
    i = 0
    while i < len(S2):
        s = ""
        while i < len(S2) and S2[i] != ' ':
            s += S2[i]
            i += 1
        i += 1
        banned[s] += 1
    result = defaultdict(lambda: 0)
    ans = ""
    freq = 0
    i = 0
    while i < len(S1):
        s = ""
        while i < len(S1) and S1[i] != ' ':
            s += S1[i]
            i += 1
        i += 1
        if banned[s] == 0:
            result[s] += 1
            if (result[s] > freq or (result[s] == freq and s < ans)):
                ans = s
                freq = result[s]
    return ans


if __name__ == "__main__":
    S1 = "geeks for geeks is best place to learn"
    S2 = "bad place"
    print(smallestFreq(S1, S2))

# Expected output:
geeks
# minimum characters to be replaced to remove the given substring | function to calculate minimum characters to replace ; mismatch occurs ; if all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; 
def replace(A, B):
    n, m = len(A), len(B)
    count, i = 0, 0
    while i < n:
        j = 0
        while j < m:
            if i + j >= n or A[i + j] != B[j]:
                break
            j += 1
        if j == m:
            count += 1
            i += m - 1
        i += 1
    return count


if __name__ == "__main__":
    str1 = "aaaaaaaa"
    str2 = "aaa"
    print(replace(str1, str2))

# Expected output:
2
# check if a string is substring of another | returns true if s1 is substring of s2 ; a loop to slide pat [ ] one by one ; for current index i , check for pattern match ; 
def isSubstring(s1, s2):
    M = len(s1)
    N = len(s2)
    for i in range(N - M + 1):
        for j in range(M):
            if (s2[i + j] != s1[j]):
                break
        if j + 1 == M:
            return i
    return -1


if __name__ == "__main__":
    s1 = "for"
    s2 = "geeksforgeeks"
    res = isSubstring(s1, s2)
    if res == -1:
        print("Not present")
    else:
        print("Present at index " + str(res))

# Expected output:
Present at index 5
# splitting a numeric string | function accepts a string and checks if string can be split . ; if there is only 1 number in the string then it is not possible to split it ; storing the substring from 0 to i + 1 to form initial number of the increasing sequence ; convert string to integer and add 1 and again convert back to string s2 ; if s2 is not a substring of number than not possible ; if s2 is the next substring of the numeric string ; incearse num2 by 1 i . e the next number to be looked for ; check if string is fully traversed then break ; if next string doesnot occurs in a given numeric string then it is not possible ; if the string was fully traversed and conditions were satisfied ; if conditions failed to hold ; 
def split(Str):
    Len = len(Str)
    if (Len == 1):
        print("Not Possible")
        return
    s1, s2 = "", ""
    for i in range((Len // 2) + 1):
        flag = 0
        s1 = Str[0:i + 1]
        num1 = int(s1)
        num2 = num1 + 1
        s2 = str(num2)
        k = i + 1
        while (flag == 0):
            l = len(s2)
            if (k + l > Len):
                flag = 1
                break
            if ((Str[k:k + l] == s2)):
                flag = 0
                num2 += 1
                k = k + l
                if (k == Len):
                    break
                s2 = str(num2)
                l = len(s2)
                if (k + 1 > len):
                    flag = 1
                    break
            else:
                flag = 1
        if (flag == 0):
            print("Possible", s1)
            break
        elif (flag == 1 and i > (Len // 2) - 1):
            print("Not Possible")
            break


Str = "99100"
split(Str)

# Expected output:
Possible 99
# count of number of given string in 2d character array | utility function to search complete string from any given index of 2d array ; through backtrack searching in every directions ; function to search the string in 2d array ; 
def internalSearch(ii, needle, row, col, hay, row_max, col_max):
    found = 0
    if (row >= 0 and row <= row_max and col >= 0 and col <=
            col_max and needle[ii] == hay[row][col]):
        match = needle[ii]
        ii += 1
        hay[row][col] = 0
        if (ii == len(needle)):
            found = 1
        else:
            found += internalSearch(ii, needle, row,
                                    col + 1, hay, row_max, col_max)
            found += internalSearch(ii, needle, row,
                                    col - 1, hay, row_max, col_max)
            found += internalSearch(ii, needle, row + 1,
                                    col, hay, row_max, col_max)
            found += internalSearch(ii, needle, row - 1,
                                    col, hay, row_max, col_max)
        hay[row][col] = match
    return found


def searchString(needle, row, col, strr, row_count, col_count):
    found = 0
    for r in range(row_count):
        for c in range(col_count):
            found += internalSearch(0, needle, r, c,
                                    strr, row_count - 1, col_count - 1)
    return found


needle = "MAGIC"
inputt = ["BBABBM", "CBMBBA", "IBABBG", "GOZBBI", "ABBBBC", "MCIGAM"]
strr = [0] * len(inputt)
for i in range(len(inputt)):
    strr[i] = list(inputt[i])
print("count: ", searchString(needle, 0, 0, strr, len(strr), len(strr[0])))

# Expected output:
count:  3
# find minimum shift for longest common prefix | function for kmp search ; preprocessing of longest proper prefix ; find out the longest prefix and position ; for new position with longer prefix in str2 update pos and len ; prresult ; 
def KMP(m, n, str2, str1):
    pos = 0
    Len = 0
    p = [0 for i in range(m + 1)]
    k = 0
    for i in range(2, n + 1):
        while (k > 0 and str1[k] != str1[i - 1]):
            k = p[k]
        if (str1[k] == str1[i - 1]):
            k += 1
        p[i] = k
    j = 0
    for i in range(m):
        while (j > 0 and j < n and str1[j] != str2[i]):
            j = p[j]
        if (j < n and str1[j] == str2[i]):
            j += 1
        if (j > Len):
            Len = j
            pos = i - j + 1
    print("Shift = ", pos)
    print("Prefix = ", str1[:Len])


str1 = "geeksforgeeks"
str2 = "forgeeksgeeks"
n = len(str1)
str2 = str2 + str2
KMP(2 * n, n, str2, str1)

# Expected output:
Shift =  8
Prefix =  geeksforgeeks
# find all the patterns of "1(0 + ) 1" in a given string | set 1 ( general approach ) | function to count patterns ; variable to store the last character ; we found 0 and last character was '1' , state change ; after the stream of 0 ' s , ▁ we ▁ got ▁ a ▁ ' 1 ',  counter incremented ; last character stored ; 
def patternCount(str):
    last = str[0]
    i = 1
    counter = 0
    while (i < len(str)):
        if (str[i] == '0' and last == '1'):
            while (str[i] == '0'):
                i += 1
                if (str[i] == '1'):
                    counter += 1
        last = str[i]
        i += 1
    return counter


str = "1001ab010abc01001"
ans = patternCount(str)
print(ans)

# Expected output:
2