giulio98/xlcost-single-prompt huggingface dataset:
# majority element | function to find majority element in an array it returns - 1 if there is no majority element ; sort the array in o ( nlogn ) ; increases the count if the same element occurs otherwise starts counting new element ; sets maximum count and stores maximum occured element so far if maximum count becomes greater than n / 2 it breaks out setting the flag ; returns maximum occured element if there is no such element , returns - 1 ; 
def majorityElement(arr, n):
    arr .sort()
    count, max_ele, temp, f = 1, -1, arr[0], 0
    for i in range(1, n):
        if (temp == arr[i]):
            count += 1
        else:
            count = 1
            temp = arr[i]
        if (max_ele < count):
            max_ele = count
            ele = arr[i]
            if (max_ele > (n // 2)):
                f = 1
                break
    if f == 1:
        return ele
    else:
        return -1


arr = [1, 1, 2, 1, 3, 5, 1]
n = len(arr)
print(majorityElement(arr, n))

# Expected output:
1
# dynamic programming | returns true if there is a subset of set [ ] with sum equal to given sum ; the value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; if sum is 0 , then answer is true ; if sum is not 0 and set is empty , then answer is false ; fill the subset table in bottom up manner ; uncomment this code to print table ; 
def isSubsetSum(set, n, sum):
    subset = ([[False for i in range(sum + 1)]for i in range(n + 1)])
    for i in range(n + 1):
        subset[i][0] = True
    for i in range(1, sum + 1):
        subset[0][i] = False
    for i in range(1, n + 1):
        for j in range(1, sum + 1):
            if j < set[i - 1]:
                subset[i][j] = subset[i - 1][j]
            if j >= set[i - 1]:
                subset[i][j] = (subset[i - 1][j]
                                or subset[i - 1][j - set[i - 1]])
    return subset[n][sum]


if __name__ == '__main__':
    set = [3, 34, 4, 12, 5, 2]
    sum = 9
    n = len(set)
    if (isSubsetSum(set, n, sum)):
        print("Found a subset with given sum")
    else:
        print("No subset with given sum")

# Expected output:
Found a subset with given sum
# dynamic programming | taking the matrix as globally ; check if possible subset with given sum is possible or not ; if the sum is zero it means we got our expected sum ; if the value is not - 1 it means it already call the function with the same value . it will save our from the repetition . ; if the value of a [ n - 1 ] is greater than the sum . we call for the next value ; here we do two calls because we don ' t ▁ know ▁ which ▁ value ▁ is ▁ ▁ full - fill ▁ our ▁ criteria ▁ ▁ that ' s why we doing two calls ; 

tab = [[-1 for i in range(2000)]for j in range(2000)]


def subsetSum(a, n, sum):
    if (sum == 0):
        return 1
    if (n <= 0):
        return 0
    if (tab[n - 1][sum] != -1):
        return tab[n - 1][sum]
    if (a[n - 1] > sum):
        tab[n - 1][sum] = subsetSum(a, n - 1, sum)
        return tab[n - 1][sum]
    else:
        tab[n - 1][sum] = subsetSum(a, n - 1, sum)
        return tab[n - 1][sum] or subsetSum(a, n - 1, sum - a[n - 1])


n = 5
a = [1, 5, 3, 7, 4]
sum = 12
if (subsetSum(a, n, sum)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# sum of bit differences for numbers from 0 to n | python3 program for the above approach ; function to implement fast exponentiation ; function to return the value for powers of 2 ; function to convert n into binary ; to store binary representation ; iterate each digit of n ; return binary representation ; function to find difference in bits ; get binary representation ; total number of bit differences from 0 to n ; iterate over each binary bit ; if current bit is '1' then add the count of current bit ; 

from math import log


def binpow(a, b):
    res = 1
    while (b > 0):
        if (b % 2 == 1):
            res = res * a
        a = a * a
        b //= 2
    return res


def find(x):
    if (x == 0):
        return 0
    p = log(x) / log(2)
    return binpow(2, p + 1) - 1


def getBinary(n):
    ans = ""
    while (n > 0):
        dig = n % 2
        ans += str(dig)
        n //= 2
    return ans


def totalCountDifference(n):
    ans = getBinary(n)
    req = 0
    for i in range(len(ans)):
        if (ans[i] == '1'):
            req += find(binpow(2, i))
    return req


N = 5
print(totalCountDifference(N))

# Expected output:
8
# find the maximum length of the prefix | function to return the maximum length of the required prefix ; array to store the frequency of each element of the array ; iterating for all the elements ; update the frequency of the current element i . e . v ; sorted positive values from counts array ; if current prefix satisfies the given conditions ; return the maximum length ; 
def Maximum_Length(a):
    counts = [0] * 11
    for index, v in enumerate(a):
        counts[v] += 1
        k = sorted([i for i in counts if i])
        if len(k) == 1 or (k[0] == k[-2] and k[-1] - k[-2]
                           == 1) or (k[0] == 1 and k[1] == k[-1]):
            ans = index
    return ans + 1


if __name__ == "__main__":
    a = [1, 1, 1, 2, 2, 2]
    n = len(a)
    print(Maximum_Length(a))

# Expected output:
5
# online queries for gcd of array after divide operations | returns the gcd after all updates in the array ; function to calculate gcd of onine queries ; stores the gcd of the initial array elements ; calculates the gcd ; performing online queries ; index is 1 based ; divide the array element ; calculates the current gcd ; print the gcd after each step ; 
def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)


def print_gcd_online(n, m, query, arr):
    max_gcd = 0
    for i in range(0, n):
        max_gcd = gcd(max_gcd, arr[i])
    for i in range(0, m):
        query[i][0] -= 1
        arr[query[i][0]] //= query[i][1]
        max_gcd = gcd(arr[query[i][0]], max_gcd)
        print(max_gcd)


if __name__ == "__main__":
    n, m = 3, 3
    query = [[1, 3], [3, 12], [2, 4]]
    arr = [36, 24, 72]
    print_gcd_online(n, m, query, arr)

# Expected output:
12
6
6
# numbers in range [ l , r ] such that the count of their divisors is both even and prime | python 3 implementation of the approach ; stores whether the number is prime or not ; stores the count of prime numbers less than or equal to the index ; create the sieve ; create a boolean array " prime [ 0 . . n ] " and initialize all the entries as true . a value in prime [ i ] will finally be false if ' i ' is not a prime , else true ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; stores the prefix sum of number of primes less than or equal to 'i ; 

MAX = 1000000
prime = [True] * (MAX + 1)
sum = [0] * (MAX + 1)


def SieveOfEratosthenes():

    prime[1] = False

    p = 2
    while p * p <= MAX:
        if (prime[p]):
            i = p * 2
            while i <= MAX:
                prime[i] = False
                i += p

        p += 1

    for i in range(1, MAX + 1):
        if (prime[i] == True):
            sum[i] = 1

        sum[i] += sum[i - 1]


if __name__ == "__main__":
    SieveOfEratosthenes()
    l = 3
    r = 9
    c = (sum[r] - sum[l - 1])
    print("Count:", c)

# Expected output:
Count: 3
# area of a circle inscribed in a rectangle which is inscribed in a semicircle | python 3 program to find the area of the circle inscribed within the rectangle which in turn is inscribed in a semicircle ; function to find the area of the circle ; radius cannot be negative ; area of the circle ; 

from math import pow, sqrt


def area(r):
    if (r < 0):
        return -1
    area = 3.14 * pow(r / (2 * sqrt(2)), 2)
    return area


if __name__ == '__main__':
    a = 5
    print("{0:.6}".format(area(a)))

# Expected output:
9.8125
# divide a number into two parts such that sum of digits is maximum | returns sum of digits of x ; returns closest number to x in terms of 9 's ; 
def sumOfDigitsSingle(x):
    ans = 0
    while x:
        ans += x % 10
        x //= 10
    return ans


def closest(x):
    ans = 0
    while (ans * 10 + 9 <= x):
        ans = ans * 10 + 9
    return ans


def sumOfDigitsTwoParts(N):
    A = closest(N)
    return sumOfDigitsSingle(A) + sumOfDigitsSingle(N - A)


if __name__ == "__main__":
    N = 35
    print(sumOfDigitsTwoParts(N))

# Expected output:
17
# Primality Test | Set 5 ( Using Lucas | Function to check whether ( 2 ^ p - 1 ) is prime or not . ; generate the number ; First number of the series ; Generate the rest ( p - 2 ) terms of the series ; now if the ( p - 1 ) the term is 0 return true else false . ; Check whetherr 2 ^ ( p - 1 ) is prime or not .
def isPrime(p):
    checkNumber = 2 ** p - 1
    nextval = 4 % checkNumber
    for i in range(1, p - 1):
        nextval = (nextval * nextval - 2) % checkNumber
    if (nextval == 0):
        return True
    else:
        return False


p = 7
checkNumber = 2 ** p - 1
if isPrime(p):
    print(checkNumber, 'is Prime.')
else:
    print(checkNumber, 'is not Prime')

# Expected output:
127 is Prime.
# sophie germain prime | function to detect prime number here we have used sieve method https : www . geeksforgeeks . org / sieve - of - eratosthenes / to detect prime number ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; we have made array till 2 * n + 1 so that we can check prime number till that and conclude about sophie german prime . ; checking every i whether it is sophie german prime or not . ; 
def sieve(n, prime):
    p = 2
    while (p * p <= n):
        if (prime[p]):
            for i in range(p * 2, n, p):
                prime[i] = False
        p += 1


def printSophieGermanNumber(n):
    prime = [True] * (2 * n + 1)
    sieve(2 * n + 1, prime)
    for i in range(2, n + 1):
        if (prime[i] and prime[2 * i + 1]):
            print(i, end=" ")


n = 25
printSophieGermanNumber(n)

# Expected output:
2 3 5 11 23
# an efficient way to check whether n | a simple python 3 program to check if n - th fibonacci number is multiple of 10. ; returns true if n - th fibonacci number is multiple of 10. ; 
def fibonacci(n):
    a = 0
    b = 1
    if (n <= 1):
        return n
    for i in range(2, n + 1):
        c = a + b
        a = b
        b = c
    return c


def isMultipleOf10(n):
    f = fibonacci(30)
    return (f % 10 == 0)


if __name__ == "__main__":
    n = 30
    if (isMultipleOf10(n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# program to find whether a given number is power of 2 | function which checks whether a number is a power of 2 ; base cases '1' is the only odd number which is a power of 2 ( 2 ^ 0 ) ; all other odd numbers are not powers of 2 ; recursive function call ; 
def powerof2(n):
    if n == 1:
        return True
    elif n % 2 != 0 or n == 0:
        return False
    return powerof2(n / 2)


if __name__ == "__main__":
    print(powerof2(64))
    print(powerof2(12))

# Expected output:
True
False
# program to find whether a given number is power of 2 | function to check if x is power of 2 ; first x in the below expression is for the case when x is 0 ; 
def isPowerOfTwo(x):
    return (x and (not (x & (x - 1))))


if (isPowerOfTwo(31)):
    print('Yes')
else:
    print('No')
if (isPowerOfTwo(64)):
    print('Yes')
else:
    print('No')

# Expected output:
No
Yes
# program to find whether a given number is power of 2 | function to check if x is power of 2 ; 
def isPowerofTwo(n):
    if (n == 0):
        return 0
    if ((n & (~(n - 1))) == n):
        return 1
    return 0


if (isPowerofTwo(30)):
    print('Yes')
else:
    print('No')
if (isPowerofTwo(128)):
    print('Yes')
else:
    print('No')

# Expected output:
No
Yes
# smallest power of 2 which is greater than or equal to sum of array elements | function to find the nearest power of 2 ; the number ; if already a power of 2 ; find the next power of 2 ; function to find the memory used ; sum of array ; traverse and find the sum of array ; function call to find the nearest power of 2 ; 
def nextPowerOf2(n):
    p = 1
    if (n and not (n & (n - 1))):
        return n
    while (p < n):
        p <<= 1
    return p


def memoryUsed(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    nearest = nextPowerOf2(sum)
    return nearest


arr = [1, 2, 3, 2]
n = len(arr)
print(memoryUsed(arr, n))

# Expected output:
8
# toggling k | python3 code to toggle k - th bit of n ; 
def toggleKthBit(n, k):
    return (n ^ (1 << (k - 1)))


n = 5
k = 1
print(toggleKthBit(n, k))

# Expected output:
4
# smallest power of 2 greater than or equal to n | python program to find smallest power of 2 greater than or equal to n ; first n in the below condition is for the case where n is 0 ; 
def nextPowerOf2(n):
    count = 0
    if (n and not (n & (n - 1))):
        return n
    while (n != 0):
        n >>= 1
        count += 1
    return 1 << count


n = 0
print(nextPowerOf2(n))

# Expected output:
1
# add elements in start to sort the array | variation of stalin sort | function to sort the array ; iterator < integer > index = arr . iterator ( ) ; ; 
def variationStalinsort(arr):
    j = 0
    while True:
        moved = 0
        for i in range(len(arr) - 1 - j):
            if arr[i] > arr[i + 1]:
                arr .insert(moved, arr .pop(i + 1))
                moved += 1
        j += 1
        if moved == 0:
            break
    return arr


if __name__ == "__main__":
    arr = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
    print(variationStalinsort(arr))

# Expected output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# maximum sum of values of n items in 0 | function to find the maximum value ; base condition ; k elements already reduced to half of their weight ; dont include item ; if weight of the item is less than or equal to the remaining weight then include the item ; return the maximum of both cases ; if the weight reduction to half is possible ; skip the item ; include item with full weight if weight of the item is less than the remaining weight ; include item with half weight if half weight of the item is less than the remaining weight ; return the maximum of all 3 cases ; 
def maximum(value, weight, weight1, flag, K, index, val_len):
    if (index >= val_len):
        return 0
    if (flag == K):
        skip = maximum(value, weight, weight1, flag, K, index + 1, val_len)
        full = 0
        if (weight[index] <= weight1):
            full = value[index] + maximum(value,
                                          weight,
                                          weight1 - weight[index],
                                          flag,
                                          K,
                                          index + 1,
                                          val_len)
        return max(full, skip)
    else:
        skip = maximum(value, weight, weight1, flag, K, index + 1, val_len)
        full = 0
        half = 0
        if (weight[index] <= weight1):
            full = value[index] + maximum(value,
                                          weight,
                                          weight1 - weight[index],
                                          flag,
                                          K,
                                          index + 1,
                                          val_len)
        if (weight[index] / 2 <= weight1):
            half = value[index] + maximum(value,
                                          weight,
                                          weight1 - weight[index] / 2,
                                          flag,
                                          K,
                                          index + 1,
                                          val_len)
        return max(full, max(skip, half))


value = [17, 20, 10, 15]
weight = [4, 2, 7, 5]
K = 1
W = 4
val_len = len(value)
print(maximum(value, weight, W, 0, K, 0, val_len))

# Expected output:
37
# number of subsets with zero sum | python3 implementation of above approach ; variable to store states of dp ; to find the number of subsets with sum equal to 0. since s can be negative , we will maxsum to it to make it positive ; base cases ; returns the value if a state is already solved ; if the state is not visited , then continue ; recurrence relation ; returning the value ; 

import numpy as np
maxSum = 100
arrSize = 51
dp = np .zeros((arrSize, maxSum))
visit = np .zeros((arrSize, maxSum))


def SubsetCnt(i, s, arr, n):
    if (i == n):
        if (s == 0):
            return 1
        else:
            return 0
    if (visit[i][s + arrSize]):
        return dp[i][s + arrSize]
    visit[i][s + arrSize] = 1
    dp[i][s + arrSize] = (SubsetCnt(i + 1, s + arr[i], arr,
                          n) + SubsetCnt(i + 1, s, arr, n))
    return dp[i][s + arrSize]


if __name__ == "__main__":
    arr = [2, 2, 2, -4, -4]
    n = len(arr)
    print(SubsetCnt(0, 0, arr, n))

# Expected output:
7.0
# tetranacci numbers | function to print the n - th tetranacci number ; initialize first four numbers to base cases ; declare a current variable ; loop to add previous four numbers for each number starting from 4 and then assign first , second , third to second , third , fourth and curr to fourth respectively ; 
def printTetra(n):
    if (n < 0):
        return
    first = 0
    second = 1
    third = 1
    fourth = 2
    curr = 0
    if (n == 0):
        print(first)
    elif (n == 1 or n == 2):
        print(second)
    elif (n == 3):
        print(fourth)
    else:
        for i in range(4, n + 1):
            curr = first + second + third + fourth
            first = second
            second = third
            third = fourth
            fourth = curr
    print(curr)


n = 10
printTetra(n)

# Expected output:
208
# count ways to reach the nth stair using step 1 , 2 or 3 | a recursive function used by countways ; 
def countWays(n):
    res = [0] * (n + 2)
    res[0] = 1
    res[1] = 1
    res[2] = 2
    for i in range(3, n + 1):
        res[i] = res[i - 1] + res[i - 2] + res[i - 3]
    return res[n]


n = 4
print(countWays(n))

# Expected output:
7
# count ways to reach the nth stair using step 1 , 2 or 3 | a recursive function used by countways ; declaring three variables and holding the ways for first three stairs ; d = 0 fourth variable ; starting from 4 as already counted for 3 stairs ; 
def countWays(n):
    a = 1
    b = 2
    c = 4
    if (n == 0 or n == 1 or n == 2):
        return n
    if (n == 3):
        return c
    for i in range(4, n + 1):
        d = c + b + a
        a = b
        b = c
        c = d
    return d


n = 4
print(countWays(n))

# Expected output:
7
# subset sum problem in o ( sum ) space |  ; initializing with 1 as sum 0 is always possible ; loop to go through every element of the elements array ; to change the value o all possible sum values to true ; if target is possible return true else false ; 
def isPossible(elements, target):
    dp = [False] * (target + 1)
    dp[0] = True
    for ele in elements:
        for j in range(target, ele - 1, -1):
            if dp[j - ele]:
                dp[j] = True
    return dp[target]


arr = [6, 2, 5]
target = 7
if isPossible(arr, target):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# dynamic programming | high | returns maximum amount of task that can be done till day n ; if n is less than equal to 0 , then no solution exists ; determines which task to choose on day n , then returns the maximum till that day ; 
def maxTasks(high, low, n):
    if (n <= 0):
        return 0
    return max(high[n - 1] + maxTasks(high, low, (n - 2)),
               low[n - 1] + maxTasks(high, low, (n - 1)))


if __name__ == "__main__":
    n = 5
    high = [3, 6, 8, 7, 6]
    low = [1, 5, 4, 5, 3]
    print(maxTasks(high, low, n))

# Expected output:
20
# kth character after replacing each character of string by its frequency exactly x times | python3 program for the above approach ; function to find the kth character after x days ; variable to store the kthchar ; traverse the string ; convert char into int ; calculate characters ; if k is less than sum than ans = str [ i ] ; return answer ; 

import math


def FindKthChar(Str, K, X):
    ans = ' '
    Sum = 0
    for i in range(len(Str)):
        digit = ord(Str[i]) - 48
        Range = int(math .pow(digit, X))
        Sum += Range
        if (K <= Sum):
            ans = Str[i]
            break
    return ans


Str = "123"
K = 9
X = 3
ans = FindKthChar(Str, K, X)
print(ans)

# Expected output:
2
# total character pairs from two strings , with equal number of set bits in their ascii value | function to get no of set bits in binary representation of positive integer n ; function to return the count of valid pairs ; store frequency of number of set bits for s1 ; store frequency of number of set bits for s2 ; calculate total pairs ; return the count of valid pairs ; 
def countSetBits(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count


def totalPairs(s1, s2):
    count = 0
    arr1 = [0] * 7
    arr2 = [0] * 7
    for i in range(len(s1)):
        set_bits = countSetBits(ord(s1[i]))
        arr1[set_bits] += 1
    for i in range(len(s2)):
        set_bits = countSetBits(ord(s2[i]))
        arr2[set_bits] += 1
    for i in range(1, 7):
        count += (arr1[i] * arr2[i])
    return count


if __name__ == "__main__":
    s1 = "geeks"
    s2 = "forgeeks"
    print(totalPairs(s1, s2))

# Expected output:
17
# enneadecagonal number | function to find nth enneadecagonal number ; formula to calculate nth enneadecagonal number ; 
def nthEnneadecagonal(n):
    return (17 * n * n - 15 * n) // 2


if __name__ == '__main__':
    n = 6
    print(n, "th Enneadecagonal number :", nthEnneadecagonal(n))

# Expected output:
6 th Enneadecagonal number : 261
# area of a circumscribed circle of a square | python3 program to find the area of a circumscribed circle ; utility function ; 

PI = 3.14159265


def areacircumscribed(a):
    return (a * a * (PI / 2))


a = 6
print(" Area of an circumscribed circle is :", round(areacircumscribed(a), 2))

# Expected output:
 Area of an circumscribed circle is : 56.55
# find nth item distributed from infinite items of infinite types based on given conditions | function to find the type of the item given out according to the given rules ; stores the count of item given out at each step ; iterate to find the nth day present is given out ; find the number of presents given on day is day * ( day + 1 ) / 2 ; iterate over the type ; return the resultant type ; 
def itemType(n):
    count = 0
    day = 1
    while (count + day * (day + 1) // 2 < n):
        count += day * (day + 1) // 2
        day += 1
    type = day
    while (type > 0):
        count += type
        if (count >= n):
            return type
        type -= 1


if __name__ == '__main__':
    N = 10
    print(itemType(N))

# Expected output:
1
# maximum length of consecutive 1 s or 0 s after flipping at most k characters | function to find the maximum length continuos segment of character c after flipping at most k characters ; stores the maximum length ; stores the count of char 'c ; start of window ; remove the extra ' c ' from left ; increment the value of the left ; update the resultant maximum length of character ch ; function to find the maximum length of consecutive 0 s or 1 s by flipping at most k characters of the string ; print the maximum of the maximum length of 0 s or 1 s ; 
def maxLength(str, n, c, k):
    ans = -1

    cnt = 0
    left = 0
    for right in range(0, n):
        if (str[right] == c):
            cnt += 1
        while (cnt > k):
            if (str[left] == c):
                cnt -= 1
            left += 1
        ans = max(ans, right - left + 1)
    return ans


def maxConsecutiveSegment(S, K):
    N = len(S)
    return max(maxLength(S, N, '0', K), maxLength(S, N, '1', K))


if __name__ == "__main__":
    S = "1001"
    K = 1
    print(maxConsecutiveSegment(S, K))

# Expected output:
3