giulio98/xlcost-single-prompt huggingface dataset:
# lexicographically n | function to print nth permutation using next_permute ( ) ; sort the string in lexicographically ascending order ; keep iterating until we reach nth position ; check for nth iteration ; print string after nth iteration ; next_permutation method implementation ; 
def next_permutation(L):
    n = len(L)
    i = n - 2
    while i >= 0 and L[i] >= L[i + 1]:
        i -= 1
    if i == -1:
        return False
    j = i + 1
    while j < n and L[j] > L[i]:
        j += 1
    j -= 1
    L[i], L[j] = L[j], L[i]
    left = i + 1
    right = n - 1
    while left < right:
        L[left], L[right] = L[right], L[left]
        left += 1
        right -= 1
    return True


def nPermute(string, n):
    string = list(string)
    new_string = []
    string .sort()
    j = 2
    while next_permutation(string):
        new_string = string
        if j == n:
            break
        j += 1
    print(''.join(new_string))


if __name__ == "__main__":
    string = "GEEKSFORGEEKS"
    n = 100
    nPermute(string, n)

# Expected output:
EEEEFGGRKSOSK
# split numeric , alphabetic and special symbols from a string | python 3 program to split an alphanumeric string using stl ; 
def splitString(str):
    alpha = ""
    num = ""
    special = ""
    for i in range(len(str)):
        if (str[i].isdigit()):
            num = num + str[i]
        elif ((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z')):
            alpha += str[i]
        else:
            special += str[i]
    print(alpha)
    print(num)
    print(special)


if __name__ == "__main__":
    str = "geeks01$$for02geeks03!@!!"
    splitString(str)

# Expected output:
geeksforgeeks
010203
$$!@!!
# program to print all substrings of a given string | function to print all sub strings ; pick starting point in outer loop and lengths of different strings for a given starting point ; 
def subString(s, n):
    for i in range(n):
        for len in range(i + 1, n + 1):
            print(s[i:len])


s = "abcd"
subString(s, len(s))

# Expected output:
a
ab
abc
abcd
b
bc
bcd
c
cd
d
# program to print all substrings of a given string | python program for the above approach ; outermost for loop this is for the selection of starting point ; 2 nd for loop is for selection of ending point ; 3 rd loop is for printing from starting point to ending point ; changing the line after printing from starting point to ending point ; 
def printSubstrings(string, n):
    for i in range(n):
        for j in range(i, n):
            for k in range(i, (j + 1)):
                print(string[k], end="")
            print()


string = "abcd"
printSubstrings(string, len(string))

# Expected output:
a
ab
abc
abcd
b
bc
bcd
c
cd
d
# maximum tip calculator | recursive function to calculate sum of maximum tip order taken by x and y ; when all orders have been taken ; when x cannot take more orders ; when y cannot take more orders ; when both can take order calculate maximum out of two ; 
def solve(i, X, Y, a, b, n):
    if (i == n):
        return 0
    if (X <= 0):
        return (b[i] + solve(i + 1, X, Y - 1, a, b, n))
    if (Y <= 0):
        return (a[i] + solve(i + 1, X - 1, Y, a, b, n))
    else:
        return max(a[i] + solve(i + 1, X - 1, Y, a, b, n),
                   b[i] + solve(i + 1, X, Y - 1, a, b, n))


a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
n = len(a)
x = 3
y = 3
print(solve(0, x, y, a, b, n))

# Expected output:
21
# number of even substrings in a string of digits | return the even number substrings . ; if current digit is even , add count of substrings ending with it . the count is ( i + 1 ) ; 
def evenNumSubstring(str):
    length = len(str)
    count = 0
    for i in range(0, length, 1):
        temp = ord(str[i]) - ord('0')
        if (temp % 2 == 0):
            count += (i + 1)
    return count


if __name__ == '__main__':
    str = ['1', '2', '3', '4']
    print(evenNumSubstring(str))

# Expected output:
6
# maximum consecutive increasing path length in binary tree | a binary tree node ; returns the maximum consecutive path length ; get the vlue of current node the value of the current node will be prev node for its left and right children ; if current node has to be a part of the consecutive path then it should be 1 greater thn the value of the previous node ; a ) find the length of the left path b ) find the length of the right path return the maximum of left path and right path ; find the length of the maximum path under subtree rooted with this node ; take the maximum previous path and path under subtree rooted with this node ; a wrapper over maxpathlenutil ( ) ; return 0 if root is none ; else compute maximum consecutive increasing path length using maxpathlenutil ; 

class Node:
    def __init__(self, val):
        self .val = val
        self .left = None
        self .right = None


def maxPathLenUtil(root, prev_val, prev_len):
    if root is None:
        return prev_len
    curr_val = root .val
    if curr_val == prev_val + 1:
        return max(
            maxPathLenUtil(
                root .left,
                curr_val,
                prev_len + 1),
            maxPathLenUtil(
                root .right,
                curr_val,
                prev_len + 1))
    newPathLen = max(
        maxPathLenUtil(
            root .left, curr_val, 1), maxPathLenUtil(
            root .right, curr_val, 1))
    return max(prev_len, newPathLen)


def maxConsecutivePathLength(root):
    if root is None:
        return 0
    return maxPathLenUtil(root, root .val - 1, 0)


root = Node(10)
root .left = Node(11)
root .right = Node(9)
root .left .left = Node(13)
root .left .right = Node(12)
root .right .left = Node(13)
root .right .right = Node(8)
print("Maximum Consecutive Increasing Path Length is")
print(maxConsecutivePathLength(root))

# Expected output:
Maximum Consecutive Increasing Path Length is
3
# find largest word in dictionary by deleting some characters of given string | returns true if str1 [ ] is a subsequence of str2 [ ] . m is length of str1 and n is length of str2 ; traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 , if matched then move ahead in str1 ; if all characters of str1 were found in str2 ; returns the longest string in dictionary which is a subsequence of str . ; traverse through all words of dictionary ; if current word is subsequence of str and is largest such word so far . ; return longest string ; 
def isSubSequence(str1, str2):
    m = len(str1)
    n = len(str2)
    j = 0
    i = 0
    while (i < n and j < m):
        if (str1[j] == str2[i]):
            j += 1
        i += 1
    return (j == m)


def findLongestString(dict1, str1):
    result = ""
    length = 0
    for word in dict1:
        if (length < len(word) and isSubSequence(word, str1)):
            result = word
            length = len(word)
    return result


dict1 = ["ale", "apple", "monkey", "plea"]
str1 = "abpcplea"
print(findLongestString(dict1, str1))

# Expected output:
apple
# xor cipher | the same function is used to encrypt and decrypt ; define xor key any character value will work ; calculate length of input string ; perform xor operation of key with every character in string ; 
def encryptDecrypt(inpString):
    xorKey = 'P'
    length = len(inpString)
    for i in range(length):
        inpString = (inpString[:i] + chr(ord(inpString[i])
                     ^ ord(xorKey)) + inpString[i + 1:])
        print(inpString[i], end="")
    return inpString


if __name__ == '__main__':
    sampleString = "GeeksforGeeks"
    print("Encrypted String: ", end="")
    sampleString = encryptDecrypt(sampleString)
    print("")
    print("Decrypted String: ", end="")
    encryptDecrypt(sampleString)

# Expected output:
Encrypted String: 55;#6?"55;#
Decrypted String: GeeksforGeeks
# repeated subsequence of length 2 or more | python3 program to check if any repeated subsequence exists in the string ; a function to check if a string str is palindrome ; l and h are leftmost and rightmost corners of str keep comparing characters while they are same ; the main function that checks if repeated subsequence exists in the string ; find length of input string ; create an array to store all characters and their frequencies in str [ ] ; traverse the input string and store frequencies of all characters in freq [ ] array . ; if the character count is more than 2 we found a repetition ; in - place remove non - repeating characters from the string ; check if the resultant string is palindrome ; special case - if length is odd return true if the middle character is same as previous one ; return false if string is a palindrome ; return true if string is not a palindrome ; 

MAX_CHAR = 256


def isPalindrome(Str, l, h):
    while (h > l):
        if (Str[l] != Str[h]):
            l += 1
            h -= 1
            return False
    return True


def check(Str):
    n = len(Str)
    freq = [0 for i in range(MAX_CHAR)]
    for i in range(n):
        freq[ord(Str[i])] += 1
        if (freq[ord(Str[i])] > 2):
            return True
    k = 0
    for i in range(n):
        if (freq[ord(Str[i])] > 1):
            Str[k] = Str[i]
            k += 1
    Str[k] = '\0'
    if (isPalindrome(Str, 0, k - 1)):
        if (k & 1):
            return Str[k // 2] == Str[k // 2 - 1]
        return False
    return True


S = "ABCABD"
Str = [i for i in S]
if (check(Str)):
    print("Repeated Subsequence Exists")
else:
    print("Repeated Subsequence Doesn't Exists")

# Expected output:
Repeated Subsequence Exists
# how to find lexicographically previous permutation ? | function to compute the previous permutation ; find index of the last element of the string ; find largest index i such that str [ i - 1 ] > str [ i ] ; if string is sorted in ascending order we 're at the last permutation ; note - str [ i . . n ] is sorted in ascending order . find rightmost element 's index  that is less than str[i - 1] ; swap character at i - 1 with j ; reverse the substring [ i . . n ] ; 
def prevPermutation(str):
    n = len(str) - 1
    i = n
    while (i > 0 and str[i - 1] <= str[i]):
        i -= 1
    if (i <= 0):
        return False
    j = i - 1
    while (j + 1 <= n and str[j + 1] <= str[i - 1]):
        j += 1
    str = list(str)
    temp = str[i - 1]
    str[i - 1] = str[j]
    str[j] = temp
    str = ''.join(str)
    str[::-1]
    return True, str


if __name__ == '__main__':
    str = "4321"
    b, str = prevPermutation(str)
    if (b):
        print("Previous permutation is", str)
    else:
        print("Previous permutation doesn't exist")

# Expected output:
Previous permutation is 4312
# check if edit distance between two strings is one | returns true if edit distance between s1 and s2 is one , else false ; find lengths of given strings ; if difference between lengths is more than 1 , then strings can 't be at one distance ; count = 0 count of iseditdistanceone ; if current characters dont match ; if length of one string is more , then only possible edit is to remove a character ; else : if lengths of both strings is same ; increment count of edits ; else : if current characters match ; if last character is extra in any string ; 
def isEditDistanceOne(s1, s2):

    m = len(s1)
    n = len(s2)
    if abs(m - n) > 1:
        return false

    count = 0

    i = 0
    j = 0
    while i < m and j < n:
        if s1[i] != s2[j]:
            if count == 1:
                return false

            if m > n:
                i += 1
            elif m < n:
                j += 1
            else:
                i += 1
                j += 1

            count += 1

        else:
            i += 1
            j += 1

    if i < m or j < n:
        count += 1

    return count == 1


s1 = "gfg"
s2 = "gf"
if isEditDistanceOne(s1, s2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count of numbers from range [ l , r ] whose sum of digits is y | set 2 | python program for the above approach ; function to find the sum of digits of numbers in the range [ 0 , x ] ; check if count of digits in a number greater than count of digits in x ; check if sum of digits of a number is equal to y ; check if current subproblem has already been comrputed ; stores count of numbers whose sum of digits is y ; check if the number exceeds y or not ; iterate over all possible values of i - th digits ; update res ; return res ; utility function to count the numbers in the range [ l , r ] whose sum of digits is y ; base case ; stores numbers in the form of its equivalent ; stores overlapping subproblems ; stores count of numbers in the range [ 0 , r ] ; update str ; stores count of numbers in the range [ 0 , l - 1 ] ; 

M = 1000


def cntNum(X, i, sum, tight, dp):
    if (i >= len(X) or sum < 0):
        if (sum == 0):
            return 1
        return 0
    if (dp[sum][i][tight] != -1):
        return dp[sum][i][tight]
    res, end = 0, 9
    if tight:
        end = ord(X[i]) - ord('0')
    for j in range(end + 1):
        res += cntNum(X, i + 1, sum - j, (tight & (j == end)), dp)
    dp[sum][i][tight] = res
    return res


def UtilCntNumRange(L, R, Y):
    if (R == 0 and Y == 0):
        return 1
    strr = str(R)
    dp = [[[-1 for i in range(2)]for i in range(M)]for i in range(M)]
    cntR = cntNum(strr, 0, Y, True, dp)
    strr = str(L - 1)
    cntL = cntNum(strr, 0, Y, True, dp)
    return (cntR - cntL)


if __name__ == '__main__':
    L, R, Y = 20, 10000, 14
    print(UtilCntNumRange(L, R, Y))

# Expected output:
0
# remove spaces from a given string | function to remove all spaces from a given string ; 
def removeSpaces(string):
    string = string .replace(' ', '')
    return string


string = "g eeks for ge eeks "
print(removeSpaces(string))

# Expected output:
geeksforgeeeks
# given a binary string , count number of substrings that start and end with 1. | a simple python 3 program to count number of substrings starting and ending with 1 ; initialize result ; pick a starting point ; search for all possible ending point ; 
def countSubStr(st, n):
    res = 0
    for i in range(0, n):
        if (st[i] == '1'):
            for j in range(i + 1, n):
                if (st[j] == '1'):
                    res = res + 1
    return res


st = "00100101"
list(st)
n = len(st)
print(countSubStr(st, n), end="")

# Expected output:
3
# an in | a utility function to reverse string str [ low . . high ] ; cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; keep the back - up of element at new position ; the main function to transform a string . this function mainly uses cycleleader ( ) to transform ; step 1 : find the largest prefix subarray of the form 3 ^ k + 1 ; step 2 : apply cycle leader algorithm for the largest subarrau ; step 4.1 : reverse the second half of first subarray ; step 4.2 : reverse the first half of second sub - string ; step 4.3 reverse the second half of first sub - string and first half of second sub - string together ; increase the length of first subarray ; 
def Reverse(string: list, low: int, high: int):
    while low < high:
        string[low], string[high] = string[high], string[low]
        low += 1
        high -= 1


def cycleLeader(string: list, shift: int, len: int):
    i = 1
    while i < len:
        j = i
        item = string[j + shift]
        while True:
            if j & 1:
                j = len // 2 + j // 2
            else:
                j //= 2
            string[j + shift], item = item, string[j + shift]
            if j == i:
                break
        i *= 3


def moveNumberToSecondHalf(string: list):
    k, lenFirst = 0, 0
    lenRemaining = len(string)
    shift = 0
    while lenRemaining:
        k = 0
        while pow(3, k) + 1 <= lenRemaining:
            k += 1
        lenFirst = pow(3, k - 1) + 1
        lenRemaining -= lenFirst
        cycleLeader(string, shift, lenFirst)
        Reverse(string, shift // 2, shift - 1)
        Reverse(string, shift, shift + lenFirst // 2 - 1)
        Reverse(string, shift // 2, shift + lenFirst // 2 - 1)
        shift += lenFirst


if __name__ == "__main__":
    string = "a1b2c3d4e5f6g7"
    string = list(string)
    moveNumberToSecondHalf(string)
    print(''.join(string))

# Expected output:
abcdefg1234567
# find remainder when a number a raised to n factorial is divided by p | function to calculate ( a ^ n ! ) % p in o ( log y ) ; initialize result ; update x if it is more than or equal to p ; in case x is divisible by p ; if y is odd , multiply x with result ; y must be even now ; returning modular power ; function to calculate resultant remainder ; initializing ans to store final remainder ; calculating remainder ; returning resultant remainder ; 
def power(x, y, p):
    res = 1
    x = x % p
    if (x == 0):
        return 0
    while (y > 0):
        if (y & 1):
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res


def remainder(n, a, p):
    ans = a % p
    for i in range(1, n + 1):
        ans = power(ans, i, p)
    return ans


A = 2
N = 1
P = 2
print(remainder(N, A, P))

# Expected output:
0
# modular exponentiation ( recursive ) | recursive python program to compute modular power ; base cases ; if b is even ; if b is odd ; 
def exponentMod(A, B, C):
    if (A == 0):
        return 0
    if (B == 0):
        return 1
    y = 0
    if (B % 2 == 0):
        y = exponentMod(A, B / 2, C)
        y = (y * y) % C
    else:
        y = A % C
        y = (y * exponentMod(A, B - 1, C) % C) % C
    return ((y + C) % C)


A = 2
B = 5
C = 13
print("Power is", exponentMod(A, B, C))

# Expected output:
Power is 6
# Find frequency of each element in a limited range array in less than O ( n ) time | python program to count number of occurrences of each element in the array in O ( n ) time and O ( 1 ) space ; check if the current element is equal to previous element . ; reset the frequency ; print the last element and its frequency ;
def findFrequencies(ele, n):
    freq = 1
    idx = 1
    element = ele[0]
    while (idx < n):
        if (ele[idx - 1] == ele[idx]):
            freq += 1
            idx += 1
        else:
            print(element, " ", freq)
            element = ele[idx]
            idx += 1
            freq = 1
    print(element, " ", freq)


print("---frequencies in a sorted array----")
arr = [10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70]
n = len(arr)
findFrequencies(arr, n)

# Expected output:
---frequencies in a sorted array----
10   1
20   1
30   3
40   1
50   4
70   1
# modular exponentiation ( power in modular arithmetic ) | iterative function to calculate ( x ^ y ) in o ( log y ) ; 
def power(x, y, p):

    res = 1

    while (y > 0):

        if ((y & 1) != 0):
            res = res * x
        y = y >> 1
        x = x * x

    return res % p


x = 2
y = 5
p = 13
print("Power is ", power(x, y, p))

# Expected output:
Power is  6
# program to calculate angle between two n | python3 program for the above approach ; function to find the magnitude of the given vector ; stores the final magnitude ; traverse the array ; return square root of magnitude ; function to find the dot product of two vectors ; stores dot product ; traverse the array ; return the product ; stores dot product of two vectors ; stores magnitude of vector a ; stores magnitude of vector b ; stores angle between given vectors ; print the angle ; 

import math


def magnitude(arr, N):
    magnitude = 0
    for i in range(N):
        magnitude += arr[i] * arr[i]
    return math .sqrt(magnitude)


def dotProduct(arr, brr, N):
    product = 0
    for i in range(N):
        product = product + arr[i] * brr[i]
    return product


def angleBetweenVectors(arr, brr, N):
    dotProductOfVectors = dotProduct(arr, brr, N)
    magnitudeOfA = magnitude(arr, N)
    magnitudeOfB = magnitude(brr, N)
    angle = (dotProductOfVectors / (magnitudeOfA * magnitudeOfB))
    print('%.5f' % angle)


if __name__ == "__main__":
    arr = [-0.5, -2, 1]
    brr = [-1, -1, 0.3]
    N = len(arr)
    angleBetweenVectors(arr, brr, N)

# Expected output:
0.84529
# sum of sides of largest and smallest child polygons possible from a given polygon | function to find the sum of largest and smallest secondary polygons if possible ; count edges of primary polygon ; calculate edges present in the largest secondary polygon ; 
def secondary_polygon(Angle):
    edges_primary = 360 // Angle
    if edges_primary >= 6:
        edges_max_secondary = edges_primary // 2
        return edges_max_secondary + 3
    else:
        return "Not Possible"


if __name__ == '__main__':
    Angle = 45
    print(secondary_polygon(Angle))

# Expected output:
7
# area of circumcircle of an equilateral triangle using median | python3 implementation to find the equation of circle which inscribes equilateral triangle of median m ; function to find the equation of circle whose center is ( x1 , y1 ) and the radius of circle is r ; function to find the equation of circle which inscribes equilateral triangle of median m ; function to find the circle equation ; 

pi = 3.14159265358979323846


def circleArea(r):
    print(round(pi * r * r, 4))


def findCircleAreaByMedian(m):
    r = 2 * m / 3
    circleArea(r)


if __name__ == '__main__':
    m = 3
    findCircleAreaByMedian(m)

# Expected output:
12.5664
# find the type of triangle from the given sides | function to find the type of triangle with the help of sides ; 
def checkTypeOfTriangle(a, b, c):
    sqa = pow(a, 2)
    sqb = pow(b, 2)
    sqc = pow(c, 2)
    if (sqa == sqa + sqb or sqb == sqa + sqc or sqc == sqa + sqb):
        print("Right-angled Triangle")
    elif (sqa > sqc + sqb or sqb > sqa + sqc or sqc > sqa + sqb):
        print("Obtuse-angled Triangle")
    else:
        print("Acute-angled Triangle")


if __name__ == '__main__':
    a = 2
    b = 2
    c = 2
    checkTypeOfTriangle(a, b, c)

# Expected output:
Acute-angled Triangle
# check whether the triangle is valid or not if angles are given | function to check if sum of the three angles is 180 or not ; check condition ; 
def Valid(a, b, c):
    if ((a + b + c == 180) and a != 0 and b != 0 and c != 0):
        return True
    else:
        return False


if __name__ == "__main__":
    a = 60
    b = 40
    c = 80
    if (Valid(a, b, c)):
        print("Valid")
    else:
        print("Invalid")

# Expected output:
Valid
# area of the largest triangle inscribed in a hexagon | python3 program to find the biggest triangle which can be inscribed within the hexagon ; function to find the area of the triangle ; side cannot be negative ; area of the triangle ; 

import math


def trianglearea(a):
    if (a < 0):
        return -1
    area = (3 * math .sqrt(3) * math .pow(a, 2)) / 4
    return area


a = 6
print(trianglearea(a))

# Expected output:
46.76537180435969
# equation of ellipse from its focus , directrix , and eccentricity | function to find equation of ellipse . ; 
def equation_ellipse(x1, y1, a, b, c, e):
    t = a * a + b * b
    a1 = t - e * (a * a)
    b1 = t - e * (b * b)
    c1 = (-2 * t * x1) - (2 * e * c * a)
    d1 = (-2 * t * y1) - (2 * e * c * b)
    e1 = -2 * e * a * b
    f1 = (-e * c * c) + (t * x1 * x1) + (t * y1 * y1)
    print(
        "Equation of ellipse is",
        a1,
        "x^2 +",
        b1,
        "y^2 +",
        c1,
        "x +",
        d1,
        "y +",
        e1,
        "xy +",
        f1,
        "= 0")


if __name__ == "__main__":
    x1, y1, a, b, c, e = 1, 1, 1, -1, 3, 0.5 * 0.5
    equation_ellipse(x1, y1, a, b, c, e)

# Expected output:
Equation of ellipse is 1.75 x^2 + 1.75 y^2 + -5.5 x + -2.5 y + 0.5 xy + 1.75 = 0
# area of circle which is inscribed in equilateral triangle | python3 program to find the area of circle which is inscribed in equilateral triangle ; function return the area of circle inscribed in equilateral triangle ; 

from math import pi


def circle_inscribed(a):
    return pi * (a * a) / 12


a = 4
print(circle_inscribed(a))

# Expected output:
4.1887902047863905