giulio98/xlcost-single-prompt huggingface dataset:
# how to check if two given line segments intersect ? | a python3 program to find if 2 given line segments intersect or not ; given three colinear points p , q , r , the function checks if point q lies on line segment ' pr ' ; to find the orientation of an ordered triplet ( p , q , r ) function returns the following values : 0 : colinear points 1 : clockwise points 2 : counterclockwise see https : www . geeksforgeeks . org / orientation - 3 - ordered - points / amp / for details of below formula . ; counterclockwise orientation ; the main function that returns true if the line segment ' p1q1' and ' p2q2' intersect . ; find the 4 orientations required for the general and special cases ; general case ; special cases p1 , q1 and p2 are colinear and p2 lies on segment p1q1 ; p1 , q1 and q2 are colinear and q2 lies on segment p1q1 ; p2 , q2 and p1 are colinear and p1 lies on segment p2q2 ; p2 , q2 and q1 are colinear and q1 lies on segment p2q2 ; if none of the cases ; 

class Point:
    def __init__(self, x, y):
        self .x = x
        self .y = y


def onSegment(p, q, r):
    if ((q .x <= max(p .x, r .x)) and (q .x >= min(p .x, r .x)) and (
            q .y <= max(p .y, r .y)) and (q .y >= min(p .y, r .y))):
        return True
    return False


def orientation(p, q, r):
    val = (float(q .y - p .y) * (r .x - q .x)) - \
        (float(q .x - p .x) * (r .y - q .y))
    if (val > 0):
        return 1
    elif (val < 0):
        return 2
    else:
        return 0


def doIntersect(p1, q1, p2, q2):
    o1 = orientation(p1, q1, p2)
    o2 = orientation(p1, q1, q2)
    o3 = orientation(p2, q2, p1)
    o4 = orientation(p2, q2, q1)
    if ((o1 != o2) and (o3 != o4)):
        return True
    if ((o1 == 0) and onSegment(p1, p2, q1)):
        return True
    if ((o2 == 0) and onSegment(p1, q2, q1)):
        return True
    if ((o3 == 0) and onSegment(p2, p1, q2)):
        return True
    if ((o4 == 0) and onSegment(p2, q1, q2)):
        return True
    return False


p1 = Point(1, 1)
q1 = Point(10, 1)
p2 = Point(1, 2)
q2 = Point(10, 2)
if doIntersect(p1, q1, p2, q2):
    print("Yes")
else:
    print("No")
p1 = Point(10, 0)
q1 = Point(0, 10)
p2 = Point(0, 0)
q2 = Point(10, 10)
if doIntersect(p1, q1, p2, q2):
    print("Yes")
else:
    print("No")
p1 = Point(-5, -5)
q1 = Point(0, 0)
p2 = Point(1, 1)
q2 = Point(10, 10)
if doIntersect(p1, q1, p2, q2):
    print("Yes")
else:
    print("No")

# Expected output:
No
Yes
No
# check whether a 
def area(x1, y1, x2, y2, x3, y3):
    return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)


def isInside(x1, y1, x2, y2, x3, y3, x, y):
    A = area(x1, y1, x2, y2, x3, y3)
    A1 = area(x, y, x2, y2, x3, y3)
    A2 = area(x1, y1, x, y, x3, y3)
    A3 = area(x1, y1, x2, y2, x, y)
    if (A == A1 + A2 + A3):
        return True
    else:
        return False


if (isInside(0, 0, 20, 0, 10, 30, 10, 15)):
    print('Inside')
else:
    print('Not Inside')

# Expected output:
Inside
# lucky numbers | returns 1 if n is a lucky number otherwise returns 0 ; function attribute will act as static variable just for readability , can be removed and used n instead ; calculate next position of input number ; 
def isLucky(n):
    next_position = n
    if isLucky .counter > n:
        return 1
    if n % isLucky .counter == 0:
        return 0
    next_position = next_position - next_position / isLucky .counter
    isLucky .counter = isLucky .counter + 1
    return isLucky(next_position)


isLucky .counter = 2
x = 5
if isLucky(x):
    print(x, "is a Lucky number")
else:
    print(x, "is not a Lucky number")

# Expected output:
5 is a Lucky number
# write you own power without using multiplication ( * ) and division ( / ) operators | works only if a >= 0 and b >= 0 ; 
def pow(a, b):
    if (b == 0):
        return 1
    answer = a
    increment = a
    for i in range(1, b):
        for j in range(1, a):
            answer += increment
        increment = answer
    return answer


print(pow(5, 3))

# Expected output:
125
# write you own power without using multiplication ( * ) and division ( / ) operators | a recursive function to get x * y * ;  ; 
def multiply(x, y):
    if (y):
        return (x + multiply(x, y - 1))
    else:
        return 0


def pow(a, b):
    if (b):
        return multiply(a, pow(a, b - 1))
    else:
        return 1


print(pow(5, 3))

# Expected output:
125
# count numbers that don 't contain 3 | returns count of numbers which are in range from 1 to n and don 't contain 3 as a digit ; base cases ( n is not negative ) ; calculate 10 ^ ( d - 1 ) ( 10 raise to the power d - 1 ) where d is number of digits in n . po will be 100 for n = 578 ; find the msd ( msd is 5 for 578 ) ; for 578 , total will be 4 * count ( 10 ^ 2 - 1 ) + 4 + ccount ( 78 ) ; for 35 total will be equal to count ( 29 ) ; 
def count(n):
    if n < 3:
        return n
    elif n >= 3 and n < 10:
        return n-1

    po = 1
    while n//po > 9:
        po = po * 10
    msd = n//po

    if msd != 3:
        return count(msd) * count(po-1) + count(msd) + count(n % po)
    else:
        return count(msd * po - 1)


n = 578
print(count(n))

# Expected output:
385
# number which has the maximum number of distinct prime factors in the range m to n | function to return the maximum number ; array to store the number of distinct primes ; true if index ' i ' is a prime ; initializing the number of factors to 0 and ; used in sieve ; condition works only when ' i ' is prime , hence for factors of all prime number , the prime status is changed to false ; number is prime ; number of factor of a prime number is 1 ; incrementing factorcount all the factors of i ; and changing prime status to false ; initialize the max and num ; gets the maximum number ; gets the maximum number ; 
def maximumNumberDistinctPrimeRange(m, n):
    factorCount = [0] * (n + 1)
    prime = [False] * (n + 1)
    for i in range(n + 1):
        factorCount[i] = 0
        prime[i] = True
    for i in range(2, n + 1):
        if (prime[i]):
            factorCount[i] = 1
            for j in range(i * 2, n + 1, i):
                factorCount[j] += 1
                prime[j] = False
    max = factorCount[m]
    num = m
    for i in range(m, n + 1):
        if (factorCount[i] > max):
            max = factorCount[i]
            num = i
    return num


if __name__ == "__main__":
    m = 4
    n = 6
    print(maximumNumberDistinctPrimeRange(m, n))

# Expected output:
6
# lexicographic rank of a string | a utility function to find factorial of n ; a utility function to count smaller characters on right of arr [ low ] ; a function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; 
def fact(n):
    f = 1
    while n >= 1:
        f = f * n
        n = n - 1
    return f


def findSmallerInRight(st, low, high):
    countRight = 0
    i = low + 1
    while i <= high:
        if st[i] < st[low]:
            countRight = countRight + 1
        i = i + 1
    return countRight


def findRank(st):
    ln = len(st)
    mul = fact(ln)
    rank = 1
    i = 0
    while i < ln:
        mul = mul / (ln - i)
        countRight = findSmallerInRight(st, i, ln - 1)
        rank = rank + countRight * mul
        i = i + 1
    return rank


st = "string"
print(findRank(st))

# Expected output:
598.0
# lexicographic rank of a string | a o ( n ) solution for finding rank of string ; all elements of count [ ] are initialized with 0 ; a utility function to find factorial of n ; construct a count array where value at every index contains count of smaller characters in whole string ; removes a character ch from count [ ] array constructed by populateandincreasecount ( ) ; a function to find rank of a string in all permutations of characters ; populate the count array such that count [ i ] contains count of characters which are present in str and are smaller than i ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; reduce count of characters greater than str [ i ] ; 

MAX_CHAR = 256
count = [0] * (MAX_CHAR + 1)


def fact(n):
    return 1 if (n <= 1)else (n * fact(n - 1))


def populateAndIncreaseCount(str):
    for i in range(len(str)):
        count[ord(str[i])] += 1
    for i in range(1, MAX_CHAR):
        count[i] += count[i - 1]


def updatecount(ch):
    for i in range(ord(ch), MAX_CHAR):
        count[i] -= 1


def findRank(str):
    len1 = len(str)
    mul = fact(len1)
    rank = 1
    populateAndIncreaseCount(str)
    for i in range(len1):
        mul = mul // (len1 - i)
        rank += count[ord(str[i]) - 1] * mul
        updatecount(str[i])
    return rank


str = "string"
print(findRank(str))

# Expected output:
598
# efficient program to calculate e ^ x | function to calculate value using sum of first n terms of taylor series ; initialize sum of series ; 
def exponential(n, x):
    sum = 1.0
    for i in range(n, 0, -1):
        sum = 1 + x * sum / i
    print("e^x =", sum)


n = 10
x = 1.0
exponential(n, x)

# Expected output:
e^x = 2.7182818011463845
# how to check if a 

import math


def isPerfectSquare(x):
    s = int(math .sqrt(x))
    return s * s == x


def isFibonacci(n):
    return isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4)


for i in range(1, 11):
    if (isFibonacci(i)):
        print(i, "is a Fibonacci Number")
    else:
        print(i, "is a not Fibonacci Number ")

# Expected output:
1 is a Fibonacci Number
2 is a Fibonacci Number
3 is a Fibonacci Number
4 is a not Fibonacci Number 
5 is a Fibonacci Number
6 is a not Fibonacci Number 
7 is a not Fibonacci Number 
8 is a Fibonacci Number
9 is a not Fibonacci Number 
10 is a not Fibonacci Number
# count trailing zeroes in factorial of a number | function to return trailing 0 s in factorial of n ; initialize result ; keep dividing n by 5 & update count ; 
def findTrailingZeros(n):
    count = 0
    while (n >= 5):
        n //= 5
        count += n
    return count


n = 100
print("Count of trailing 0s " + "in 100! is", findTrailingZeros(n))

# Expected output:
Count of trailing 0s in 100! is 24
# program for nth catalan number | a recursive function to find nth catalan number ; base case ; catalan ( n ) is the sum of catalan ( i ) * catalan ( n - i - 1 ) ; 
def catalan(n):
    if n <= 1:
        return 1
    res = 0
    for i in range(n):
        res += catalan(i) * catalan(n - i - 1)
    return res


for i in range(10):
    print(catalan(i),)

# Expected output:
1
1
2
5
14
42
132
429
1430
4862
# program for nth catalan number | a dynamic programming based function to find nth catalan number ; table to store results of subproblems ; initialize first two values in table ; fill entries in catalan [ ] using recursive formula ; return last entry ; 
def catalan(n):
    if (n == 0 or n == 1):
        return 1
    catalan = [0] * (n + 1)
    catalan[0] = 1
    catalan[1] = 1
    for i in range(2, n + 1):
        for j in range(i):
            catalan[i] += catalan[j] * catalan[i - j - 1]
    return catalan[n]


for i in range(10):
    print(catalan(i), end=" ")

# Expected output:
1 1 2 5 14 42 132 429 1430 4862
# program for nth catalan number | returns value of binomial coefficient c ( n , k ) ; since c ( n , k ) = c ( n , n - k ) ; calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- -- * 1 ] ; a binomial coefficient based function to find nth catalan number in o ( n ) time ; calculate value of 2 ncn ; return 2 ncn / ( n + 1 ) ; 
def binomialCoefficient(n, k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(k):
        res = res * (n - i)
        res = res / (i + 1)
    return res


def catalan(n):
    c = binomialCoefficient(2 * n, n)
    return c / (n + 1)


for i in range(10):
    print(catalan(i), end=" ")

# Expected output:
1.0 1.0 2.0 5.0 14.0 42.0 132.0 429.0 1430.0 4862.0
# program for nth catalan number | function to print the number ; for the first number c ( 0 ) ; iterate till n ; calculate the number and print it ; 
def catalan(n):
    cat_ = 1
    print(cat_, " ", end='')
    for i in range(1, n):
        cat_ *= (4 * i - 2)
        cat_ //= (i + 1)
        print(cat_, " ", end='')


n = 5
catalan(n)

# Expected output:
1  1  2  5  14
# find excel column name from a given column number |  ; step 1 : converting to number assuming 0 in number system ; step 2 : getting rid of 0 , as 0 is not part of number system ; 
def printString(n):
    arr = [0] * 10000
    i = 0
    while (n > 0):
        arr[i] = n % 26
        n = int(n // 26)
        i += 1
    for j in range(0, i - 1):
        if (arr[j] <= 0):
            arr[j] += 26
            arr[j + 1] = arr[j + 1] - 1
    for j in range(i, -1, -1):
        if (arr[j] > 0):
            print(chr(ord('A') + (arr[j] - 1)), end="")
    print()


if __name__ == '__main__':
    printString(26)
    printString(51)
    printString(52)
    printString(80)
    printString(676)
    printString(702)
    printString(705)

# Expected output:
Z
AY
AZ
CB
YZ
ZZ
AAC
# calculate the angle between hour hand and minute hand | function to calculate angle b / w hour hand and minute hand ; validate the input ; calculate the angles moved by hour and minute hands with reference to 12 : 00 ; find the difference between two angles ; return the smaller angle of two possible angles ; 
def calcAngle(h, m):
    if (h < 0 or m < 0 or h > 12 or m > 60):
        print('Wrong input')
    if (h == 12):
        h = 0
    if (m == 60):
        m = 0
        h += 1
        if (h > 12):
            h = h - 12
    hour_angle = 0.5 * (h * 60 + m)
    minute_angle = 6 * m
    angle = abs(hour_angle - minute_angle)
    angle = min(360 - angle, angle)
    return angle


h = 9
m = 60
print('Angle ', calcAngle(h, m))

# Expected output:
Angle  60.0
# how to check if an instance of 8 puzzle is solvable ? | a utility function to count inversions in given array ' arr [ ] ' ; value 0 is used for empty space ; this function returns true if given 8 puzzle is solvable . ; count inversions in given 8 puzzle ; return true if inversion count is even . ; 
def getInvCount(arr):
    inv_count = 0
    for i in range(0, 2):
        for j in range(i + 1, 3):
            if (arr[j][i] > 0 and arr[j][i] > arr[i][j]):
                inv_count += 1
    return inv_count


def isSolvable(puzzle):
    invCount = getInvCount(puzzle)
    return (invCount % 2 == 0)


puzzle = [[1, 8, 2], [0, 4, 3], [7, 6, 5]]
if (isSolvable(puzzle)):
    print("Solvable")
else:
    print("Not Solvable")

# Expected output:
Solvable
# birthday paradox | python3 code to approximate number of people in birthday paradox problem ; returns approximate number of people for a given probability ; 

import math


def find(p):
    return math .ceil(math .sqrt(2 * 365 * math .log(1 / (1 - p))))


print(find(0.70))

# Expected output:
30
# count distinct non | this function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; 
def countSolutions(n):
    res = 0
    x = 0
    while (x * x < n):
        y = 0
        while (x * x + y * y < n):
            res = res + 1
            y = y + 1
        x = x + 1
    return res


if __name__ == '__main__':
    print("Total Number of distinct Non-Negative pairs is ", countSolutions(6))

# Expected output:
Total Number of distinct Non-Negative pairs is  8
# count distinct non | this function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; find the count of different y values for x = 0. ; one by one increase value of x , and find ycount for current x . if ycount becomes 0 , then we have reached maximum possible value of x . ; add ycount ( count of different possible values of y for current x ) to result ; increment x ; update ycount for current x . keep reducing ycount while the inequality is not satisfied . ; 
def countSolutions(n):
    x = 0
    res = 0
    yCount = 0
    while (yCount * yCount < n):
        yCount = yCount + 1
    while (yCount != 0):
        res = res + yCount
        x = x + 1
        while (yCount != 0 and (x * x + (yCount - 1) * (yCount - 1) >= n)):
            yCount = yCount - 1
    return res


print("Total Number of distinct ", countSolutions(6))

# Expected output:
Total Number of distinct  8
# program for method of false position | python3 implementation of bisection method for solving equations ; an example function whose solution is determined using bisection method . the function is x ^ 3 - x ^ 2 + 2 ; prints root of func ( x ) in interval [ a , b ] ; 

MAX_ITER = 1000000


def func(x):
    return (x * x * x - x * x + 2)


def regulaFalsi(a, b):
    if func(a) * func(b) >= 0:
        print("You have not assumed right a and b")
        return -1
    c = a
    for i in range(MAX_ITER):
        c = (a * func(b) - b * func(a)) / (func(b) - func(a))
        if func(c) == 0:
            break
        elif func(c) * func(a) < 0:
            b = c
        else:
            a = c
    print("The value of root is : ", '%.4f' % c)


a = -200
b = 300
regulaFalsi(a, b)

# Expected output:
The value of root is :  -1.0000
# Program for Newton Raphson Method | An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Derivative of the above function which is 3 * x ^ x - 2 * x ; Function to find the root ; x ( i + 1 ) = x ( i ) - f ( x ) / f '(x) ; Initial values assumed
def func(x):
    return x * x * x - x * x + 2


def derivFunc(x):
    return 3 * x * x - 2 * x


def newtonRaphson(x):
    h = func(x) / derivFunc(x)
    while abs(h) >= 0.0001:
        h = func(x) / derivFunc(x)
        x = x - h
    print("The value of the root is : ", "%.4f" % x)


x0 = -20
newtonRaphson(x0)

# Expected output:
The value of the root is :  -1.0000
# find the element that appears once | method to find the element that occur only once ; one & arr [ i ] " gives the bits that  are there in both 'ones' and new  element from arr[]. we add these  bits to 'twos' using bitwise or ; one & arr [ i ] " gives the bits that  are there in both 'ones' and new  element from arr[]. we add these  bits to 'twos' using bitwise or ; the common bits are those bits which appear third time . so these bits should not be there in both ' ones ' and ' twos ' . common_bit_mask contains all these bits as 0 , so that the bits can be removed from ' ones ' and 'twos   ; remove common bits ( the bits that appear third time ) from 'ones   ; remove common bits ( the bits that appear third time ) from 'twos   ; 
def getSingle(arr, n):
    ones = 0
    twos = 0
    for i in range(n):
        twos = twos | (ones & arr[i])
        ones = ones ^ arr[i]
        common_bit_mask = ~(ones & twos)
        ones &= common_bit_mask
        twos &= common_bit_mask
    return ones


arr = [3, 3, 2, 3]
n = len(arr)
print("The element with single occurrence is ", getSingle(arr, n))

# Expected output:
The element with single occurrence is  2
# find the element that appears once | python3 code to find the element that occur only once ; initialize result ; iterate through every bit ; find sum of set bits at ith position in all array elements ; the bits with sum not multiple of 3 , are the bits of element with single occurrence . ; 

INT_SIZE = 32


def getSingle(arr, n):
    result = 0
    for i in range(0, INT_SIZE):
        sm = 0
        x = (1 << i)
        for j in range(0, n):
            if (arr[j] & x):
                sm = sm + 1
        if ((sm % 3) != 0):
            result = result | x
    return result


arr = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7]
n = len(arr)
print("The element with single occurrence is ", getSingle(arr, n))

# Expected output:
The element with single occurrence is  7
# detect if two integers have opposite signs | function to detect signs ; 
def oppositeSigns(x, y):
    return ((x ^ y) < 0)


x = 100
y = 1
if (oppositeSigns(x, y)):
    print("Signs are opposite")
else:
    print("Signs are not opposite")

# Expected output:
Signs are not opposite
# count total set bits in all numbers from 1 to n | returns count of set bits present in all numbers from 1 to n ; initialize the result ; a utility function to count set bits in a number x ; 
def countSetBitsUtil(x):
    if (x <= 0):
        return 0
    return (0 if int(x % 2) == 0 else 1) + countSetBitsUtil(int(x / 2))
    

def countSetBits(n):
    bitCount = 0
    for i in range(1, n + 1):
        bitCount += countSetBitsUtil(i)
    return bitCount


if __name__ == '__main__':
    n = 4
    print("Total set bit count is", countSetBits(n))

# Expected output:
Total set bit count is 5
# count total set bits in all numbers from 1 to n | function which counts set bits from 0 to n ; ans store sum of set bits from 0 to n ; while n greater than equal to 2 ^ i ; this k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; this will loop from 0 to n for every bit position ; when change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; 
def countSetBits(n):
    i = 0
    ans = 0
    while ((1 << i) <= n):
        k = 0
        change = 1 << i
        for j in range(0, n + 1):
            ans += k
            if change == 1:
                k = not k
                change = 1 << i
            else:
                change -= 1
        i += 1
    return ans


if __name__ == "__main__":
    n = 17
    print(countSetBits(n))

# Expected output:
35
# count total set bits in all numbers from 1 to n | returns position of leftmost set bit . the rightmost position is considered as 0 ; given the position of previous leftmost set bit in n ( or an upper bound onleftmost position ) returns the new position of leftmost set bit in n ; the main recursive function used by countsetbits ( ) def _countsetbits ( n , m ) returns count of set bits present in all numbers from 1 to n ; get the position of leftmost set bit in n . this will be used as an upper bound for next set bit function ; use the position ; base case : if n is 0 , then set bit count is 0 ; get position of next leftmost set bit ; if n is of the form 2 ^ x - 1 , i . e . , if n is like 1 , 3 , 7 , 15 , 31 , . . etc , then we are done . since positions are considered starting from 0 , 1 is added to m ; update n for next recursive call ; 
def getLeftmostBit(n):
    m = 0
    while (n > 1):
        n = n >> 1
        m += 1
    return m


def getNextLeftmostBit(n, m):
    temp = 1 << m
    while (n < temp):
        temp = temp >> 1
        m -= 1
    return m


def _countSetBits(n, m):
    if (n == 0):
        return 0
    m = getNextLeftmostBit(n, m)
    if (n == (1 << (m + 1)) - 1):
        return ((m + 1) * (1 << m))
    n = n - (1 << m)
    return (n + 1) + countSetBits(n) + m * (1 << (m - 1))


def countSetBits(n):
    m = getLeftmostBit(n)
    return _countSetBits(n, m)


n = 17
print("Total set bit count is", countSetBits(n))

# Expected output:
Total set bit count is 35
# swap bits in a given number | python program to swap bits in a given number ; move all bits of first set to rightmost side ; moce all bits of second set to rightmost side ; xor the two sets ; put the xor bits back to their original positions ; xor the ' xor ' with the original number so that the two sets are swapped ; 
def swapBits(x, p1, p2, n):
    set1 = (x >> p1) & ((1 << n) - 1)
    set2 = (x >> p2) & ((1 << n) - 1)
    xor = (set1 ^ set2)
    xor = (xor << p1) | (xor << p2)
    result = x ^ xor
    return result


res = swapBits(28, 0, 3, 2)
print("Result =", res)

# Expected output:
Result = 7