giulio98/xlcost-single-prompt huggingface dataset:
# count of even and odd set bit with array element after xor with k | function to store even and odd variable ; store the count of even and odd set bit ; count the set bit using in built function ; count of set - bit of k ; if y is odd then , count of even and odd set bit will be interchanged ; else it will remain same as the original array ; 
def countEvenOdd(arr, n, K):
    even = 0
    odd = 0
    for i in range(n):
        x = bin(arr[i]).count('1')
        if (x % 2 == 0):
            even += 1
        else:
            odd += 1
    y = bin(K).count('1')
    if (y & 1):
        print("Even =", odd, ", Odd =", even)
    else:
        print("Even =", even, ", Odd =", odd)


if __name__ == "__main__":
    arr = [4, 2, 15, 9, 8, 8]
    K = 3
    n = len(arr)
    countEvenOdd(arr, n, K)

# Expected output:
Even = 2 , Odd = 4
# longest subsequence from an array of pairs having first element increasing and second element decreasing . | python 3 program for the above approach ; recursive function to find the length of the longest subsequence of pairs whose first element is increasing and second is decreasing ; base case ; not include the current pair in the longest subsequence ; including the current pair in the longest subsequence ;  ; 

import sys


def longestSubSequence(
        A,
        N,
        ind=0,
        lastf=-
        sys .maxsize -
        1,
        lasts=sys .maxsize):
    if (ind == N):
        return 0
    ans = longestSubSequence(A, N, ind + 1, lastf, lasts)
    if (A[ind][0] > lastf and A[ind][1] < lasts):
        ans = max(
            ans,
            longestSubSequence(
                A,
                N,
                ind + 1,
                A[ind][0],
                A[ind][1]) + 1)
    return ans


if __name__ == "__main__":
    A = [[1, 2], [2, 2], [3, 1]]
    N = len(A)
    print(longestSubSequence(A, N))

# Expected output:
2
# count triples with bitwise and equal to zero | function to find the number of triplets whose bitwise and is 0. ; stores the count of triplets having bitwise and equal to 0 ; stores frequencies of all possible a [ i ] & a [ j ] ; traverse the array ; update frequency of bitwise and of all array elements with a ; traverse the array ; iterate the map ; if bitwise and of triplet is zero , increment cnt ; return the number of triplets whose bitwise and is 0. ; 
def countTriplets(A):
    cnt = 0
    tuples = {}
    for a in A:
        for b in A:
            if (a & b) in tuples:
                tuples[a & b] += 1
            else:
                tuples[a & b] = 1
    for a in A:
        for t in tuples:
            if ((t & a) == 0):
                cnt += tuples[t]
    return cnt


if __name__ == "__main__":
    A = [2, 1, 3]
    print(countTriplets(A))

# Expected output:
12
# count ways to reach a score using 1 and 2 with no consecutive 2 s | bottom up approach for counting ways to reach a score using 1 and 2 with consecutive 2 allowed ; noofways [ i ] will store count for value i . 3 extra values are to take care of corner case n = 0 ; loop till " n + 1" to compute value for " n " ; number of ways if first run is 1 + number of ways if first run is 2 and second run is 1 ; 
def CountWays(n):
    noOfWays = [0] * (n + 3)
    noOfWays[0] = 1
    noOfWays[1] = 1
    noOfWays[2] = 1 + 1
    for i in range(3, n + 1):
        noOfWays[i] = noOfWays[i - 1] + noOfWays[i - 3]
    return noOfWays[n]


if __name__ == '__main__':
    n = 5
    print(CountWays(n))

# Expected output:
6
# find the last player to be able to flip a character in a binary string | python3 program for the above approach ; function to check if player a wins the game or not ; stores size of the groups of 0 s ; stores size of the group of 0 s ; traverse the array ; increment c by 1 if a [ i ] is 0 ; otherwise , push the size in array and reset c to 0 ; if there is no substring of odd length consisting only of 0 s ; if there is only 1 substring of odd length consisting only of 0 s ; otherwise ; stores the size of the largest and second largest substrings of 0 s ; traverse the array v [ ] ; if current element is greater than first , then update both first and second ; if arr [ i ] is in between first and second , then update second ; if the condition is satisfied ; 

import sys


def findWinner(a, n):
    v = []
    c = 0
    for i in range(0, n):
        if (a[i] == '0'):
            c += 1
        else:
            if (c != 0):
                v .append(c)
            c = 0
    if (c != 0):
        v .append(c)
    if (len(v) == 0):
        print("Player B", end="")
        return
    if (len(v) == 1):
        if ((v[0] & 1) != 0):
            print("Player A", end="")
        else:
            print("Player B", end="")
        return
    first = sys .minsize
    second = sys .minsize
    for i in range(len(v)):
        if (a[i] > first):
            second = first
            first = a[i]
        elif (a[i] > second and a[i] != first):
            second = a[i]
    if (((first & 1) != 0) and (first + 1) // 2 > second):
        print("Player A", end="")
    else:
        print("Player B", end="")


S = "1100011"
N = len(S)
findWinner(S, N)

# Expected output:
Player A
# check if k palindromic strings can be formed from a given string | function to check whether the is k palindrome or not ; map to frequency of character ; check when k is given as same as length of string ; storing the frequency of every character in map ; if k is greater than size of then return false ; check that number of character having the odd frequency ; if k is less than number of odd frequency character then it is again false otherwise true ; 
def can_Construct(S, K):
    m = dict()
    p = 0
    if (len(S) == K):
        return True
    for i in S:
        m[i] = m .get(i, 0) + 1
    if (K > len(S)):
        return False
    else:
        for h in m:
            if (m[h] % 2 != 0):
                p = p + 1
    if (K < p):
        return False
    return True


if __name__ == '__main__':
    S = "annabelle"
    K = 4
    if (can_Construct(S, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if two strings are same ignoring their cases | function to compare two strings ignoring their cases ; convert to lower case ; comparing both ; if strings are equal , return true otherwise false ; function to print the same or not same if strings are equal or not equal ; 
def equalIgnoreCase(str1, str2):
    str1 = str1 .lower()
    str2 = str2 .lower()
    x = str1 == str2
    return x


def equalIgnoreCaseUtil(str1, str2):
    res = equalIgnoreCase(str1, str2)
    if (res):
        print("Same")
    else:
        print("Not Same")


if __name__ == "__main__":
    str1 = "Geeks"
    str2 = "geeks"
    equalIgnoreCaseUtil(str1, str2)
    str1 = "Geek"
    str2 = "geeksforgeeks"
    equalIgnoreCaseUtil(str1, str2)

# Expected output:
Same
Not Same
# Program to print Step Pattern | Python3 program to print Step Pattern ; function to print the steps ; declare a flag ; traverse through all the characters in the string ; if the x value is 0. . then we must increment till n ... set flag to true ; if the x value is n - 1 then we must decrement till 0 ... set flag as false ; print x * s ; checking whether to increment or decrement x ; Get the String and the number n ; calling the function

import math as mt


def steps(string, n):
    flag = False
    x = 0
    for i in range(len(string)):
        if (x == 0):
            flag = True
        if (x == n - 1):
            flag = False
        for j in range(x):
            print("*", end="")
        print(string[i])
        if (flag):
            x += 1
        else:
            x -= 1


n = 4
string = "GeeksForGeeks"
print("String: ", string)
print("Max Length of Steps: ", n)
steps(string, n)

# Expected output:
String:  GeeksForGeeks
Max Length of Steps:  4
G
*e
**e
***k
**s
*F
o
*r
**G
***e
**e
*k
s
# frequency measuring techniques for competitive programming | python program to count frequencies of array items ; mark all array elements as not visited ; traverse through array elements and count frequencies ; skip this element if already processed ; count frequency ; 
def countFreq(arr, n):
    visited = [False for i in range(n)]
    for i in range(n):
        if visited[i]:
            continue
        count = 1
        for j in range(i + 1, n):
            if arr[i] == arr[j]:
                visited[j] = True
                count += 1
        print(arr[i], count)


a = [10, 20, 20, 10, 10, 20, 5, 20]
n = len(a)
countFreq(a, n)

# Expected output:
10 3
20 4
5 1
# check divisibility of binary string by 2 ^ k | function to check whether 
def isDivisible(str, k):
    n = len(str)
    c = 0
    for i in range(0, k):
        if (str[n - i - 1] == '0'):
            c += 1
    return (c == k)


str1 = "10101100"
k = 2
if (isDivisible(str1, k)):
    print("Yes")
else:
    print("No")
str2 = "111010100"
k = 2
if (isDivisible(str2, k)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
Yes
# check if any anagram of a string is palindrome or not | python program to check if any anagram of a string is palindrome or not ; function to check whether characters of a string can form a palindrome ; create a count array and initialize all values as 0 ; for each character in input strings , increment count in the corresponding count array ; count odd occurring characters ; return true if odd count is 0 or 1 , ; 

NO_OF_CHARS = 256


def canFormPalindrome(string):
    count = [0 for i in range(NO_OF_CHARS)]
    for i in string:
        count[ord(i)] += 1
    odd = 0
    for i in range(NO_OF_CHARS):
        if (count[i] & 1):
            odd += 1
        if (odd > 1):
            return False
    return True


if (canFormPalindrome("geeksforgeeks")):
    print("Yes")
else:
    print("No")
if (canFormPalindrome("geeksogeeks")):
    print("Yes")
else:
    print("NO")

# Expected output:
No
Yes
# program to check if input is an integer or a string | this function returns true if s is a number else false ; 
def isNumber(s):
    for i in range(len(s)):
        if s[i].isdigit() != True:
            return False
    return True


if __name__ == "__main__":
    str = "6790"
    if isNumber(str):
        print("Integer")
    else:
        print("String")

# Expected output:
Integer
# print reverse of a string using recursion | function to print reverse of the passed string ; 
def reverse(string):
    if len(string) == 0:
        return
    temp = string[0]
    reverse(string[1:])
    print(temp, end='')


string = "Geeks for Geeks"
reverse(string)

# Expected output:
skeeG rof skeeG
# probability of distributing given balls into two halves having equal count of distinct colors | stores the count of distinct colors in box1 ; stores the count of distinct colors in box2 ; function to calculate the required probability ; calculate factorial from [ 1 , 10 ] ; assign all distinct balls to second box ; total number of balls ; calculate total number of balls ; if k is an odd number ; total ways of distributing the balls in two equal halves ; required number of ways ; return the required probability ; function to calculate total number of possible distributions which satisfies the given conditions ; if used balls is equal to k / 2 ; if box1 is equal to box2 ; base condition ; stores the number of ways of distributing remaining balls without including the current balls in box1 ; increment box1 by one ; iterate over the range [ 1 , balls [ i ] ] ; if all the balls goes to box1 , then decrease box2 by one ; total number of ways of selecting j balls ; increment res by total number of valid ways of distributing the remaining balls ; decrement box1 by one ; increment box2 by 1 ; function to calculate factorial of n ; base case ; iterate over the range [ 1 , n ] ; function to calculate ncr ; 

box1 = 0
box2 = 0
fact = [0 for i in range(11)]


def validPermutations(n, balls, usedBalls, i):
    global box1, box2, fact
    if (usedBalls == n):
        if (box1 == box2):
            return 1
        else:
            return 0
    if (i >= len(balls)):
        return 0
    res = validPermutations(n, balls, usedBalls, i + 1)
    box1 += 1
    for j in range(1, balls[i] + 1):
        if (j == balls[i]):
            box2 -= 1
        combinations = comb(balls[i], j)
        res += combinations * validPermutations(n, balls, usedBalls + j, i + 1)
    box1 -= 1
    box2 += 1
    return res


def factorial(N):
    global box1, box2, fact
    fact[0] = 1
    for i in range(1, N + 1):
        fact[i] = fact[i - 1] * i


def comb(n, r):
    global box1, box2, fact
    res = fact[n] // fact[r]
    res //= fact[n - r]
    return res

def getProbability(balls):
    global box1, box2, fact
    factorial(10)
    box2 = len(balls)
    K = 0
    for i in range(len(balls)):
        K += balls[i]
    if (K % 2 == 1):
        return 0
    all = comb(K, K // 2)
    validPermutation = validPermutations(K // 2, balls, 0, 0)
    return validPermutation / all


arr = [2, 1, 1]
N = 4
print(getProbability(arr))

# Expected output:
0.6666666666666666
# area of a n | python3 program to find the area of a regular polygon with given radius ; function to find the area of a regular polygon ; side and radius cannot be negative ; area degree converted to radians ; 

from math import sin


def polyarea(n, r):
    if (r < 0 and n < 0):
        return -1
    A = (((r * r * n) * sin((360 / n) * 3.14159 / 180)) / 2)
    return round(A, 3)


if __name__ == "__main__":
    r, n = 9, 6
    print(polyarea(n, r))

# Expected output:
210.444
# check if a line at 45 degree can divide the plane into two equal weight parts |  ; checking if a plane can be divide by a line at 45 degrees such that weight sum is equal ; rotating each point by 45 degrees and calculating prefix sum . also , finding maximum and minimum x coordinates ; storing weight sum upto x - y point ; finding prefix sum ; line passes through i , so it neither falls left nor right . ; 

from collections import defaultdict


def is_partition_possible(n, x, y, w):
    weight_at_x = defaultdict(int)
    max_x = -2e3
    min_x = 2e3
    for i in range(n):
        new_x = x[i] - y[i]
        max_x = max(max_x, new_x)
        min_x = min(min_x, new_x)
        weight_at_x[new_x] += w[i]
    sum_till = []
    sum_till .append(0)
    for x in range(min_x, max_x + 1):
        sum_till .append(sum_till[-1] + weight_at_x[x])
    total_sum = sum_till[-1]
    partition_possible = False
    for i in range(1, len(sum_till)):
        if (sum_till[i] == total_sum - sum_till[i]):
            partition_possible = True
        if (sum_till[i - 1] == total_sum - sum_till[i]):
            partition_possible = True
    if partition_possible:
        print("YES")
    else:
        print("NO")


if __name__ == "__main__":
    n = 3
    x = [-1, -2, 1]
    y = [1, 1, -1]
    w = [3, 1, 4]
    is_partition_possible(n, x, y, w)

# Expected output:
YES
# slope of perpendicular to line | function to find the slope of other line ; 
def findPCSlope(m):
    return -1.0 / m


m = 2.0
print(findPCSlope(m))

# Expected output:
-0.5
# program to find area of a circular segment | python3 program to find area of segment of a circle ; function to find area of segment ; calculating area of sector ; calculating area of triangle ; 

import math
pi = 3.14159


def area_of_segment(radius, angle):
    area_of_sector = pi * (radius * radius)*(angle / 360)
    area_of_triangle = 1 / 2 * (radius * radius)*math .sin((angle * pi) / 180)
    return area_of_sector - area_of_triangle


radius = 10.0
angle = 90.0
print("Area of minor segment =", area_of_segment(radius, angle))
print("Area of major segment =", area_of_segment(radius, (360 - angle)))

# Expected output:
Area of minor segment = 28.53975000004401
Area of major segment = 285.6192499996039
# area of a circular sector | python program to find area of a sector ; calculating area of the sector ; 
def SectorArea(radius, angle):
    pi = 22 / 7
    if angle >= 360:
        print("Angle not possible")
        return
    else:
        sector = (pi * radius ** 2) * (angle / 360)
        print(sector)
        return


radius = 9
angle = 60
SectorArea(radius, angle)

# Expected output:
42.42857142857142
# make two numbers equal by multiplying with their prime factors minimum number of times | python program for the above approach ; function to calculate total number of prime factor with their prime factor ; iterate while the number is even ; reduce to half ; iterate up to sqrt ( n ) ; iterate while n has factors of i ; removing one factor of i ; function to count the number of factors ; find the gcd ; find multiples left in x and y ; find prime factor of multiple left in x and y ; initialize ans ; check if it possible to obtain x or not ; check if it possible to obtain y or not ; return main ans ; 

import math


def PrimeFactor(N):
    ANS = dict()
    while N % 2 == 0:
        if 2 in ANS:
            ANS[2] += 1
        else:
            ANS[2] = 1
        N = N // 2
    for i in range(3, int(math .sqrt(N)) + 1, 2):
        while N % i == 0:
            if i in ANS:
                ANS[i] += 1
            else:
                ANS[i] = 1
            N = N // i
    if 2 < N:
        ANS[N] = 1
    return ANS


def CountToMakeEqual(X, Y):
    GCD = math .gcd(X, Y)
    newY = X // GCD
    newX = Y // GCD
    primeX = PrimeFactor(newX)
    primeY = PrimeFactor(newY)
    ans = 0
    for factor in primeX:
        if X % factor != 0:
            return -1
        ans += primeX[factor]
    for factor in primeY:
        if Y % factor != 0:
            return -1
        ans += primeY[factor]
    return ans


if __name__ == "__main__":
    X = 36
    Y = 48
    ans = CountToMakeEqual(X, Y)
    print(ans)

# Expected output:
3
# make given segments non | python3 program for the above approach ; function to check whether the graph is bipartite or not ; mark source node as visited ; push the source vertex in queue ; get the front of the queue ; assign the color to the popped node ; traverse the adjacency list of the node u ; if any node is visited & a different colors has been assigned , then return false ; set visited [ x ] ; push the node x into the queue ; update color of node ; if the graph is bipartite ; function to add an edge between the nodes u and v ; function to check if the assignment of direction can be possible to all the segments , such that they do not intersect after a long period of time ; stores the adjacency list of the created graph ; generate all possible pairs ; if segments do not overlap ; otherwise , the segments overlap ; if both segments have same speed , then add an edge ; keep the track of visited nodes ; iterate for all possible nodes ; check whether graph is bipartite or not ; if the graph is bipartite ; 

from collections import deque


def check(Adj, Src, N, visited):
    color = [0] * N
    visited = [True] * Src
    q = deque()
    q .append(Src)
    while (len(q) > 0):
        u = q .popleft()
        Col = color[u]
        for x in Adj[u]:
            if (visited[x] and color[x] == Col):
                return False
            elif (visited[x] == False):
                visited[x] = True
                q .append(x)
                color[x] = 1 - Col
    return True


def addEdge(Adj, u, v):
    Adj[u].append(v)
    Adj[v].append(u)
    return Adj


def isPossible(Arr, N):
    Adj = [[]for i in range(N)]
    for i in range(N - 1):
        for j in range(i + 1, N):
            if (Arr[i][0] < Arr[j][1] or Arr[i][1] > Arr[j][0]):
                continue
            else:
                if (Arr[i][2] == Arr[j][2]):
                    Adj = addEdge(Adj, i, j)
    visited = [False] * N
    for i in range(N):
        if (visited[i] == False and len(Adj[i]) > 0):
            if (check(Adj, i, N, visited) == False):
                print("No")
                return
    print("Yes")


if __name__ == '__main__':
    arr = [[5, 7, 2], [4, 6, 1], [1, 5, 2], [6, 5, 1]]
    N = len(arr)
    isPossible(arr, N)

# Expected output:
Yes
# minimum number of swaps required to sort an array of first n number | function to find minimum swaps ; initialise count variable ; if current element is not at the right position ; swap current element with correct position of that element ; increment for next index when current element is at correct position ; 
def minimumSwaps(arr):
    count = 0
    i = 0
    while (i < len(arr)):
        if (arr[i] != i + 1):
            while (arr[i] != i + 1):
                temp = 0
                temp = arr[arr[i] - 1]
                arr[arr[i] - 1] = arr[i]
                arr[i] = temp
                count += 1
        i += 1
    return count


if __name__ == '__main__':
    arr = [2, 3, 4, 1, 5]
    print(minimumSwaps(arr))

# Expected output:
3
# recursive selection sort | return minimum index ; find minimum of remaining elements ; return minimum of current and remaining . ; recursive selection sort . n is size of a [ ] and index is index of starting element . ; return when starting and size are same ; calling minimum index function for minimum index ; swapping when index and minimum index are not same ; swap ; recursively calling selection sort function ; 
def minIndex(a, i, j):
    if i == j:
        return i
    k = minIndex(a, i + 1, j)
    return (i if a[i] < a[k]else k)


def recurSelectionSort(a, n, index=0):
    if index == n:
        return -1
    k = minIndex(a, index, n - 1)
    if k != index:
        a[k], a[index] = a[index], a[k]
        a[k], a[index] = a[index], a[k]
    recurSelectionSort(a, n, index + 1)


arr = [3, 1, 5, 2, 7, 0]
n = len(arr)
recurSelectionSort(arr, n)
for i in arr:
    print(i, end=' ')

# Expected output:
3 1 5 2 7 0
# maximum possible difference of sum of two subsets of an array | set 2 | python 3 program for the above approach ; stores the positive elements ; stores the negative elements ; stores the count of 0 s ; sum of all positive numbers ; sum of all negative numbers ; iterate over the array ; stores the difference ; sort the positive numbers in ascending order ; sort the negative numbers in decreasing order ; case 1 : include both positive and negative numbers ; put all numbers in subset a and one 0 in subset b ; put all numbers in subset a except the smallest positive number which is put in b ; put all numbers in subset b and one 0 in subset a ; place the largest negative number in subset a and remaining in b ; 
def maxSumAfterPartition(arr, n):
    pos = []
    neg = []
    zero = 0
    pos_sum = 0
    neg_sum = 0
    for i in range(n):
        if (arr[i] > 0):
            pos .append(arr[i])
            pos_sum += arr[i]
        elif (arr[i] < 0):
            neg .append(arr[i])
            neg_sum += arr[i]
        else:
            zero += 1
    ans = 0
    pos .sort()
    neg .sort(reverse=True)
    if (len(pos) > 0 and len(neg) > 0):
        ans = (pos_sum - neg_sum)
    elif (len(pos) > 0):
        if (zero > 0):
            ans = (pos_sum)
        else:
            ans = (pos_sum - 2 * pos[0])
    else:
        if (zero > 0):
            ans = (-1 * neg_sum)
        else:
            ans = (neg[0] - (neg_sum - neg[0]))
    return ans


if __name__ == '__main__':
    arr = [1, 2, 3, -5, -7]
    n = len(arr)
    print(maxSumAfterPartition(arr, n))

# Expected output:
18
# split an array into subarrays with maximum bitwise xor of their respective bitwise or values | function to find the bitwise or of array elements ; stores the resultant maximum value of bitwise xor ; traverse the array arr [ ] ; return the maximum value res ; 
def MaxXOR(arr, N):
    res = 0
    for i in range(N):
        res |= arr[i]
    return res


if __name__ == '__main__':
    arr = [1, 5, 7]
    N = len(arr)
    print(MaxXOR(arr, N))

# Expected output:
7