giulio98/xlcost-single-prompt huggingface dataset:
# program to find the roots of quadratic equation | python program to find roots of a quadratic equation ; prints roots of quadratic equation ax * 2 + bx + x ; if a is 0 , then equation is not quadratic , but linear ; else : d < 0 ; 

import math


def findRoots(a, b, c):
    if a == 0:
        print("Invalid")
        return -1
    d = b * b - 4 * a * c
    sqrt_val = math .sqrt(abs(d))
    if d > 0:
        print("Roots are real and different ")
        print((-b + sqrt_val) / (2 * a))
        print((-b - sqrt_val) / (2 * a))
    elif d == 0:
        print("Roots are real and same")
        print(-b / (2 * a))
        print("Roots are complex")
        print(-b / (2 * a), " + i", sqrt_val)
        print(-b / (2 * a), " - i", sqrt_val)


a = 1
b = -7
c = 12
findRoots(a, b, c)

# Expected output:
Roots are real and different 
4.0
3.0
# check perfect square using addition / subtraction | this function returns true if n is perfect square , else false ; the_sum is sum of all odd numbers . i is used one by one hold odd numbers ; 
def isPerfectSquare(n):
    i = 1
    the_sum = 0
    while the_sum < n:
        the_sum += i
        if the_sum == n:
            return True
        i += 2
    return False


if __name__ == "__main__":
    print('Yes')if isPerfectSquare(35)else print('NO')
    print('Yes')if isPerfectSquare(49)else print('NO')

# Expected output:
NO
Yes
# count ' d ' digit positive integers with 0 as a digit | python 3 program to find the count of positive integer of a given number of digits that contain atleast one zero ; returns count of ' d ' digit integers have 0 as a digit ; 

import math


def findCount(d):
    return 9 * ((int)(math .pow(10, d - 1)) - (int)(math .pow(9, d - 1)))


d = 1
print(findCount(d))
d = 2
print(findCount(d))
d = 4
print(findCount(d))

# Expected output:
0
9
2439
# dyck path | returns count dyck paths in n x n grid ; compute value of 2 ncn ; return 2 ncn / ( n + 1 ) ; 
def countDyckPaths(n):
    res = 1
    for i in range(0, n):
        res *= (2 * n - i)
        res /= (i + 1)
    return res / (n + 1)


n = 4
print("Number of Dyck Paths is ", str(int(countDyckPaths(n))))

# Expected output:
Number of Dyck Paths is  14
# triangular numbers | returns true if ' num ' is triangular , else false ; base case ; a triangular number must be sum of first n natural numbers ; 
def isTriangular(num):
    if (num < 0):
        return False
    sum, n = 0, 1
    while (sum <= num):
        sum = sum + n
        if (sum == num):
            return True
        n += 1
    return False


n = 55
if (isTriangular(n)):
    print("The number is a triangular number")
else:
    print("The number is NOT a triangular number")

# Expected output:
The number is a triangular number
# triangular numbers | python3 program to check if a number is a triangular number using quadratic equation . ; returns true if num is triangular ; considering the equation n * ( n + 1 ) / 2 = num the equation is : a ( n ^ 2 ) + bn + c = 0 ; find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; 

import math


def isTriangular(num):
    if (num < 0):
        return False
    c = (-2 * num)
    b, a = 1, 1
    d = (b * b) - (4 * a * c)
    if (d < 0):
        return False
    root1 = (-b + math .sqrt(d)) / (2 * a)
    root2 = (-b - math .sqrt(d)) / (2 * a)
    if (root1 > 0 and math .floor(root1) == root1):
        return True
    if (root2 > 0 and math .floor(root2) == root2):
        return True
    return False


n = 55
if (isTriangular(n)):
    print("The number is a triangular number")
else:
    print("The number is NOT a triangular number")

# Expected output:
The number is a triangular number
# convert from any base to decimal and vice versa | to return value of a char . for example , 2 is returned for '2' . 10 is returned for ' a ' , 11 for 'b ; function to convert a number from given base ' b ' to decimal ; initialize power of base ; initialize result ; decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; a digit in input number must be less than number 's base ; 
def val(c):
    if c >= '0' and c <= '9':
        return ord(c) - ord('0')
    else:
        return ord(c) - ord('A') + 10


def toDeci(str, base):
    llen = len(str)
    power = 1
    num = 0
    for i in range(llen - 1, -1, -1):
        if val(str[i]) >= base:
            print('Invalid Number')
            return -1
        num += val(str[i]) * power
        power = power * base
    return num


strr = "11A"
base = 16
print(('Decimal equivalent of', strr, 'in base', base, 'is', toDeci(strr, base)))

# Expected output:
('Decimal equivalent of', '11A', 'in base', 16, 'is', 282)
# frobenius coin problem | utility function to find gcd ; function to print the desired output ; solution doesn 't exist   if gcd is not 1 ; else apply the formula ; 
def gcd(a, b):
    while (a != 0):
        c = a
        a = b % a
        b = c
    return b


def forbenius(X, Y):
    if (gcd(X, Y) != 1):
        print("NA")
        return
    A = (X * Y) - (X + Y)
    N = (X - 1) * (Y - 1) // 2
    print("Largest Amount =", A)
    print("Total Count =", N)


X = 2
Y = 5
forbenius(X, Y)
X = 5
Y = 10
print("")
forbenius(X, Y)

# Expected output:
Largest Amount = 3
Total Count = 2

NA
# solving f ( n ) = ( 1 ) + ( 2 * 3 ) + ( 4 * 5 * 6 ) . . . n using recursion | recursive function for finding sum of series calculated - number of terms till which sum of terms has been calculated current - number of terms for which sum has to be calculated n - number of terms in the function to be calculated ; checking termination condition ; product of terms till current ; recursive call for adding terms next in the series ; 
def seriesSum(calculated, current, N):
    i = calculated
    cur = 1
    if (current == N + 1):
        return 0
    while (i < calculated + current):
        cur *= i
        i += 1
    return cur + seriesSum(i, current + 1, N)


N = 5
print(seriesSum(1, 1, N))

# Expected output:
365527
# how to avoid overflow in modular multiplication ? | to compute ( a * b ) % mod ; res = 0 ; initialize result ; if b is odd , add ' a ' to result ; multiply ' a ' with 2 ; divide b by 2 ; return result ; 
def mulmod(a, b, mod):
    res = 0
    a = a % mod
    while (b > 0):
        if (b % 2 == 1):
            res = (res + a) % mod
        a = (a * 2) % mod
        b //= 2
    return res % mod


a = 9223372036854775807
b = 9223372036854775807
print(mulmod(a, b, 100000000000))

# Expected output:
84232501249
# compute n ! under modulo p | returns value of n ! % p ; 
def modFact(n, p):
    if n >= p:
        return 0
    result = 1
    for i in range(1, n + 1):
        result = (result * i) % p
    return result


n = 25
p = 29
print(modFact(n, p))

# Expected output:
5
# chinese remainder theorem | set 2 ( inverse modulo based implementation ) | returns modulo inverse of a with respect to m using extended euclid algorithm . refer below post for details : https : www . geeksforgeeks . org / multiplicative - inverse - under - modulo - m / ; apply extended euclid algorithm ; q is quotient ; m is remainder now , process same as euclid 's algo ; make x1 positive ; k is size of num [ ] and rem [ ] . returns the smallest number x such that : x % num [ 0 ] = rem [ 0 ] , x % num [ 1 ] = rem [ 1 ] , ... ... ... ... ... ... x % num [ k - 2 ] = rem [ k - 1 ] assumption : numbers in num [ ] are pairwise coprime ( gcd for every pair is 1 ) ; compute product of all numbers ; initialize result ; apply above formula ; 
def inv(a, m):
    m0 = m
    x0 = 0
    x1 = 1
    if (m == 1):
        return 0
    while (a > 1):
        q = a // m
        t = m
        m = a % m
        a = t
        t = x0
        x0 = x1 - q * x0
        x1 = t
    if (x1 < 0):
        x1 = x1 + m0
    return x1


def findMinX(num, rem, k):
    prod = 1
    for i in range(0, k):
        prod = prod * num[i]
    result = 0
    for i in range(0, k):
        pp = prod // num[i]
        result = result + rem[i] * inv(pp, num[i]) * pp
    return result % prod


num = [3, 4, 5]
rem = [2, 3, 1]
k = len(num)
print("x is ", findMinX(num, rem, k))

# Expected output:
x is  11
# chinese remainder theorem | set 1 ( introduction ) | k is size of num [ ] and rem [ ] . returns the smallest number x such that : x % num [ 0 ] = rem [ 0 ] , x % num [ 1 ] = rem [ 1 ] , ... ... ... ... ... ... x % num [ k - 2 ] = rem [ k - 1 ] assumption : numbers in num [ ] are pairwise coprime ( gcd forevery pair is 1 ) ; as per the chinise remainder theorem , this loop will always break . ; check if remainder of x % num [ j ] is rem [ j ] or not ( for all j from 0 to k - 1 ) ; if all remainders matched , we found x ; else try next number ; 
def findMinX(num, rem, k):
    x = 1
    while (True):
        j = 0
        while (j < k):
            if (x % num[j] != rem[j]):
                break
            j += 1
        if (j == k):
            return x
        x += 1


num = [3, 4, 5]
rem = [2, 3, 1]
k = len(num)
print("x is", findMinX(num, rem, k))

# Expected output:
x is 11
# fibonacci coding | to limit on the largest fibonacci number to be used ; array to store fibonacci numbers . fib [ i ] is going to store ( i + 2 ) 'th fibonacci number ; stores values in fib and returns index of the largest fibonacci number smaller than n . ; fib [ 0 ] stores 2 nd fibonacci no . ; fib [ 1 ] stores 3 rd fibonacci no . ; keep generating remaining numbers while previously generated number is smaller ; return index of the largest fibonacci number smaller than or equal to n . note that the above loop stopped when fib [ i - 1 ] became larger . ; returns pointer to the char string which corresponds to code for n ; allocate memory for codeword ; index of the largest fibonacci f <= n ; mark usage of fibonacci f ( 1 bit ) ; subtract f from n ; move to fibonacci just smaller than f ; mark all fibonacci > n as not used ( 0 bit ) , progress backwards ; additional '1' bit ; return pointer to codeword ; 

N = 30
fib = [0 for i in range(N)]


def largestFiboLessOrEqual(n):
    fib[0] = 1
    fib[1] = 2
    i = 2
    while fib[i - 1] <= n:
        fib[i] = fib[i - 1] + fib[i - 2]
        i += 1
    return (i - 2)


def fibonacciEncoding(n):
    index = largestFiboLessOrEqual(n)
    codeword = ['a'for i in range(index + 2)]
    i = index
    while (n):
        codeword[i] = '1'
        n = n - fib[i]
        i = i - 1
        while (i >= 0 and fib[i] > n):
            codeword[i] = '0'
            i = i - 1
    codeword[index + 1] = '1'
    return "".join(codeword)


n = 143
print("Fibonacci code word for", n, "is", fibonacciEncoding(n))

# Expected output:
Fibonacci code word for 143 is 01010101011
# print all good numbers in given range | function to check whether n is a good number and doesn ' t ▁ contain ▁ digit ▁ ' d ; get last digit and initialize sum from right side ; if last digit is d , return ; traverse remaining digits ; current digit ; if digit is d or digit is less than or equal to sum of digits on right side ; update sum and n ; print good numbers in range [ l , r ] ; traverse all numbers in given range ; if current numbers is good , print it ; 
def isValid(n, d):
    digit = n % 10
    sum = digit
    if (digit == d):
        return False
    n = int(n / 10)
    while (n > 0):
        digit = n % 10
        if (digit == d or digit <= sum):
            return False
        else:
            sum += digit
            n = int(n / 10)
    return True


def printGoodNumber(L, R, d):
    for i in range(L, R + 1):
        if (isValid(i, d)):
            print(i, end=" ")


L = 410
R = 520
d = 3
printGoodNumber(L, R, d)

# Expected output:
410 420 421 510 520
# count number of squares in a rectangle | returns count of all squares in a rectangle of size m x n ; if n is smaller , swap m and n ; now n is greater dimension , apply formula ; 
def countSquares(m, n):
    if (n < m):
        temp = m
        m = n
        n = temp
    return n * (n + 1) * (3 * m - n + 1) // 6


if __name__ == '__main__':
    m = 4
    n = 3
    print("Count of squares is", countSquares(m, n))

# Expected output:
Count of squares is 20
# zeckendorf 's theorem (non | returns the greatest fibonacci number smaller than or equal to n . ; corner cases ; finds the greatest fibonacci number smaller than n . ; prints fibonacci representation of n using greedy algorithm ; find the greates fibonacci number smaller than or equal to n ; print the found fibonacci number ; reduce n ; 
def nearestSmallerEqFib(n):
    if (n == 0 or n == 1):
        return n
    f1, f2, f3 = 0, 1, 1
    while (f3 <= n):
        f1 = f2
        f2 = f3
        f3 = f1 + f2
    return f2


def printFibRepresntation(n):
    while (n > 0):
        f = nearestSmallerEqFib(n)
        print(f,)
        n = n - f


n = 30
print("Non-neighbouring Fibonacci Representation of", n, "is")
printFibRepresntation(n)

# Expected output:
Non-neighbouring Fibonacci Representation of 30 is
21
8
1
# count number of ways to divide a number in 4 parts | a dynamic programming based solution to count number of ways to represent n as sum of four numbers ; " parts " is number of parts left , n is the value left " nextpart " is starting point from where we start trying for next part . ; base cases ; if this subproblem is already solved ; count number of ways for remaining number n - i remaining parts " parts - 1" , and for all part varying from ' nextpart ' to 'n ; store computed answer in table and return result ; this function mainly initializes dp table and calls countwaysutil ( ) ; 

dp = [[[-1 for i in range(5)]
       for i in range(501)]
      for i in range(501)]


def countWaysUtil(n, parts, nextPart):
    if (parts == 0 and n == 0):
        return 1
    if (n <= 0 or parts <= 0):
        return 0
    if (dp[n][nextPart][parts] != -1):
        return dp[n][nextPart][parts]

    ans = 0
    for i in range(nextPart, n + 1):
        ans += countWaysUtil(n - i, parts - 1, i)
    dp[n][nextPart][parts] = ans
    return (ans)


def countWays(n):
    return countWaysUtil(n, 4, 1)


n = 8
print(countWays(n))

# Expected output:
5
# segmented sieve | python3 program to print all primes smaller than n , using segmented sieve ; this method finds all primes smaller than ' limit ' using simple sieve of eratosthenes . it also stores found primes in list prime ; create a boolean list " mark [ 0 . . n - 1 ] " and initialize all entries of it as true . a value in mark [ p ] will finally be false if ' p ' is not a prime , else true . ; if p is not changed , then it is a prime ; update all multiples of p ; print all prime numbers and store them in prime ; prints all prime numbers smaller than 'n ; compute all primes smaller than or equal to square root of n using simple sieve ; divide the range [ 0. . n - 1 ] in different segments we have chosen segment size as sqrt ( n ) . ; while all segments of range [ 0. . n - 1 ] are not processed , process one segment at a time ; to mark primes in current range . a value in mark [ i ] will finally be false if ' i - low ' is not a prime , else true . ; use the found primes by simplesieve ( ) to find primes in current range ; find the minimum number in [ low . . high ] that is a multiple of prime [ i ] ( divisible by prime [ i ] ) for example , if low is 31 and prime [ i ] is 3 , we start with 33. ; mark multiples of prime [ i ] in [ low . . high ] : we are marking j - low for j , i . e . each number in range [ low , high ] is mapped to [ 0 , high - low ] so if range is [ 50 , 100 ] marking 50 corresponds to marking 0 , marking 51 corresponds to 1 and so on . in this way we need to allocate space only for range ; numbers which are not marked as false are prime ; update low and high for next segment ; 

import math
prime = []


def simpleSieve(limit):
    mark = [True for i in range(limit + 1)]
    p = 2
    while (p * p <= limit):
        if (mark[p]):
            for i in range(p * p, limit + 1, p):
                mark[i] = False
        p += 1
    for p in range(2, limit):
        if mark[p]:
            prime .append(p)
            print(p, end=" ")


def segmentedSieve(n):
    limit = int(math .floor(math .sqrt(n)) + 1)
    simpleSieve(limit)
    low = limit
    high = limit * 2
    while low < n:
        if high >= n:
            high = n
        mark = [True for i in range(limit + 1)]
        for i in range(len(prime)):
            loLim = int(math .floor(low / prime[i]) * prime[i])
            if loLim < low:
                loLim += prime[i]
            for j in range(loLim, high, prime[i]):
                mark[j - low] = False
        for i in range(low, high):
            if mark[i - low]:
                print(i, end=" ")
        low = low + limit
        high = high + limit


n = 100
print("Primes smaller than", n, ":")
segmentedSieve(100)

# Expected output:
Primes smaller than 100 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
# find the smallest twins in given range | python3 program to find the smallest twin in given range ; create a boolean array " prime [ 0 . . high ] " and initialize all entries it as true . a value in prime [ i ] will finally be false if i is not a prime , else true . ; look for the smallest twin ; if p is not marked , then it is a prime ; update all multiples of p ; now print the smallest twin in range ; 

import math


def printTwins(low, high):
    prime = [True] * (high + 1)
    twin = False
    prime[0] = prime[1] = False
    for p in range(2, int(math .floor(math .sqrt(high)) + 2)):
        if (prime[p]):
            for i in range(p * 2, high + 1, p):
                prime[i] = False
    for i in range(low, high + 1):
        if (prime[i] and prime[i + 2]):
            print("Smallest twins in given range: (", i, ",", (i + 2), ")")
            twin = True
            break
    if (twin == False):
        print("No such pair exists")


printTwins(10, 100)

# Expected output:
Smallest twins in given range: ( 11 , 13 )
# check if a given number is fancy | python 3 program to find if a given number is fancy or not . ; to store mappings of fancy pair characters . for example 6 is paired with 9 and 9 is paired with 6. ; find number of digits in given number ; traverse from both ends , and compare characters one by one ; if current characters at both ends are not fancy pairs ; 
def isFancy(num):
    fp = {}
    fp['0'] = '0'
    fp['1'] = '1'
    fp['6'] = '9'
    fp['8'] = '8'
    fp['9'] = '6'
    n = len(num)
    l = 0
    r = n - 1
    while (l <= r):
        if (num[l]not in fp or fp[num[l]] != num[r]):
            return False
        l += 1
        r -= 1
    return True


if __name__ == "__main__":
    st = "9088806"
    if isFancy(st):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find next sparse number | python3 program to find next sparse number ; find binary representation of x and store it in bin [ ] . bin [ 0 ] contains least significant bit ( lsb ) , next bit is in bin [ 1 ] , and so on . ; there my be extra bit in result , so add one extra bit ; the position till which all bits are finalized ; start from second bit ( next to lsb ) ; if current bit and its previous bit are 1 , but next bit is not 1. ; make the next bit 1 ; make all bits before current bit as 0 to make sure that we get the smallest next number ; store position of the bit set so that this bit and bits before it are not changed next time . ; find decimal equivalent of modified bin [ ] ; 
def nextSparse(x):
    bin = []
    while (x != 0):
        bin .append(x & 1)
        x >>= 1
    bin .append(0)
    n = len(bin)
    last_final = 0
    for i in range(1, n - 1):
        if ((bin[i] == 1 and bin[i - 1] == 1 and bin[i + 1] != 1)):
            bin[i + 1] = 1
            for j in range(i, last_final - 1, -1):
                bin[j] = 0
            last_final = i + 1
    ans = 0
    for i in range(n):
        ans += bin[i] * (1 << i)
    return ans


if __name__ == '__main__':
    x = 38
    print("Next Sparse Number is", nextSparse(x))

# Expected output:
Next Sparse Number is 40
# count number of subsets of a set with gcd equal to a given number | n is size of arr [ ] and m is sizeof gcd [ ] ; map to store frequency of array elements ; map to store number of subsets with given gcd ; initialize maximum element . assumption : all array elements are positive . ; find maximum element in array and fill frequency map . ; run a loop from max element to 1 to find subsets with all gcds ; run a loop for all multiples of i ; sum the frequencies of every element which is a multiple of i ; excluding those subsets which have gcd > i but not i i . e . which have gcd as multiple of i in the subset . for ex : { 2 , 3 , 4 } considering i = 2 and subset we need to exclude are those having gcd as 4 ; number of subsets with gcd equal to ' i ' is pow ( 2 , add ) - 1 - sub ; 
def countSubsets(arr, n, gcd, m):
    freq = dict()
    subsets = dict()
    arrMax = 0
    for i in range(n):
        arrMax = max(arrMax, arr[i])
        if arr[i]not in freq:
            freq[arr[i]] = 1
        else:
            freq[arr[i]] += 1
    for i in range(arrMax, 0, -1):
        sub = 0
        add = 0
        if i in freq:
            add = freq[i]
        j = 2
        while j * i <= arrMax:
            if j * i in freq:
                add += freq[j * i]
            sub += subsets[j * i]
            j += 1
        subsets[i] = (1 << add) - 1 - sub
    for i in range(m):
        print("Number of subsets with gcd %d is %d" %
              (gcd[i], subsets[gcd[i]]))


if __name__ == "__main__":
    gcd = [2, 3]
    arr = [9, 6, 2]
    n = len(arr)
    m = len(gcd)
    countSubsets(arr, n, gcd, m)

# Expected output:
Number of subsets with gcd 2 is 2
Number of subsets with gcd 3 is 1
# sum of bit differences among all pairs | python program to compute sum of pairwise bit differences ; traverse over all bits ; count number of elements with i 'th bit set ; add " count ▁ * ▁ ( n ▁ - ▁ count ) ▁ * ▁ 2" to the answer ; 
def sumBitDifferences(arr, n):
    ans = 0
    for i in range(0, 32):
        count = 0
        for j in range(0, n):
            if ((arr[j] & (1 << i))):
                count += 1
        ans += (count * (n - count) * 2)
    return ans


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

# Expected output:
8
# print all non | utility function to print array arr [ 0. . n - 1 ] ; recursive function to generate all non - increasing sequences with sum x arr [ ] -- > elements of current sequence curr_sum -- > current sum curr_idx -- > current index in arr [ ] ; if current sum is equal to x , then we found a sequence ; try placing all numbers from 1 to x - curr_sum at current index ; the placed number must also be smaller than previously placed numbers and it may be equal to the previous stored value , i . e . , arr [ curr_idx - 1 ] if there exists a previous number ; place number at curr_idx ; recur ; try next number ; a wrapper over generateutil ( ) ; array to store sequences on by one ; 
def printArr(arr, n):
    for i in range(0, n):
        print(arr[i], end=" ")
    print("")


def generateUtil(x, arr, curr_sum, curr_idx):
    if (curr_sum == x):
        printArr(arr, curr_idx)
        return
    num = 1
    while (num <= x - curr_sum and (curr_idx ==
           0 or num <= arr[curr_idx - 1])):
        arr[curr_idx] = num
        generateUtil(x, arr, curr_sum + num, curr_idx + 1)
        num += 1


def generate(x):
    arr = [0] * x
    generateUtil(x, arr, 0, 0)


x = 5
generate(x)

# Expected output:
1 1 1 1 1 
2 1 1 1 
2 2 1 
3 1 1 
3 2 
4 1 
5
# perfect number | returns true if n is perfect ; to store sum of divisors ; find all divisors and add them ; if sum of divisors is equal to n , then n is a perfect number ; 
def isPerfect(n):
    sum = 1
    i = 2
    while i * i <= n:
        if n % i == 0:
            sum = sum + i + n / i
        i += 1
    return (True if sum == n and n != 1 else False)


print("Below are all perfect numbers till 10000")
n = 2
for n in range(10000):
    if isPerfect(n):
        print(n, " is a perfect number")

# Expected output:
Below are all perfect numbers till 10000
6  is a perfect number
28  is a perfect number
496  is a perfect number
8128  is a perfect number