giulio98/xlcost-single-prompt huggingface dataset:
# twin prime numbers between 1 and n | python program to illustrate ... to print total number of twin prime using sieve of eratosthenes ; create a boolean array " prime [ 0 . . n ] " and initialize all entries it 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 ; check twin prime numbers display the twin prime numbers ; 
def printTwinPrime(n):
    prime = [True for i in range(n + 2)]
    p = 2
    while (p * p <= n + 1):
        if (prime[p]):
            for i in range(p * 2, n + 2, p):
                prime[i] = False
        p += 1
    for p in range(2, n - 1):
        if prime[p] and prime[p + 2]:
            print("(", p, ",", (p + 2), ")", end='')


if __name__ == '__main__':
    n = 25
    printTwinPrime(n)

# Expected output:
( 3 , 5 )( 5 , 7 )( 11 , 13 )( 17 , 19 )
# cube free numbers smaller than n | python3 program to print all cube free numbers smaller than or equal to n . ; returns true if n is a cube free number , else returns false . ; check for all possible divisible cubes ; print all cube free numbers smaller than n . ; 

import math


def isCubeFree(n):
    if n == 1:
        return False
    for i in range(2, int(n ** (1 / 3) + 1)):
        if (n % (i * i * i) == 0):
            return False
    return True


def printCubeFree(n):
    for i in range(2, n + 1):
        if (isCubeFree(i)):
            print(i, end=" ")


n = 20
printCubeFree(n)

# Expected output:
2 3 4 5 6 7 9 10 11 12 13 14 15 17 18 19 20
# decimal equivalent of gray code and its inverse | function to convert given decimal number of gray code into its inverse in decimal form ; taking xor until n becomes zero ; 
def inversegrayCode(n):
    inv = 0
    while (n):
        inv = inv ^ n
        n = n >> 1
    return inv


n = 15
print(inversegrayCode(n))

# Expected output:
10
# product of unique prime factors of a number | python program to find product of unique prime factors of a number ; a function to print all prime factors of a given number n ; handle prime factor 2 explicitly so that can optimally handle other prime factors . ; n must be odd at this point . so we can skip one element ( note i = i + 2 ) ; while i divides n , print i and divide n ; this condition is to handle the case when n is a prime number greater than 2 ; 

import math


def productPrimeFactors(n):
    product = 1
    if (n % 2 == 0):
        product *= 2
        while (n % 2 == 0):
            n = n / 2
    for i in range(3, int(math .sqrt(n)) + 1, 2):
        if (n % i == 0):
            product = product * i
            while (n % i == 0):
                n = n / i
    if (n > 2):
        product = product * n
    return product


n = 44
print(int(productPrimeFactors(n)))

# Expected output:
22
# Maximizing Probability of one type from N containers | Returns the Maximum probability for Drawing 1 copy of number A from N containers with N copies each of numbers A and B ; Pmax = N / ( N + 1 ) ; 1. N = 1 ; 2. N = 2 ; 3. N = 10
def calculateProbability(N):
    probability = N / (N + 1)
    return probability


N = 1
probabilityMax = calculateProbability(N)
print("Maximum Probability for N = ", N, "is, %.4f" % probabilityMax)
N = 2
probabilityMax = calculateProbability(N)
print("Maximum Probability for N =", N, "is, %.4f" % probabilityMax)
N = 10
probabilityMax = calculateProbability(N)
print("Maximum Probability for N =", N, "is, %.4f" % probabilityMax)

# Expected output:
Maximum Probability for N =  1 is, 0.5000
Maximum Probability for N = 2 is, 0.6667
Maximum Probability for N = 10 is, 0.9091
# program to implement standard deviation of grouped data | python program to implement standard deviation of grouped data . ; function to find mean of grouped data . ; function to find standard deviation of grouped data . ; formula to find standard deviation of grouped data . ; declare and initialize the lower limit of interval . ; declare and 

import math


def mean(mid, freq, n):
    sum = 0
    freqSum = 0
    for i in range(0, n):
        sum = sum + mid[i] * freq[i]
        freqSum = freqSum + freq[i]
    return sum / freqSum


def groupedSD(lower_limit, upper_limit, freq, n):
    mid = [[0]for i in range(0, n)]
    sum = 0
    freqSum = 0
    sd = 0
    for i in range(0, n):
        mid[i] = (lower_limit[i] + upper_limit[i]) / 2
        sum = sum + freq[i] * mid[i] * mid[i]
        freqSum = freqSum + freq[i]
    sd = math .sqrt((sum - freqSum * mean(mid, freq, n)
                    * mean(mid, freq, n)) / (freqSum - 1))
    return sd


lower_limit = [50, 61, 71, 86, 96]
upper_limit = [60, 70, 85, 95, 100]
freq = [9, 7, 9, 12, 8]
n = len(lower_limit)
print(groupedSD(lower_limit, upper_limit, freq, n))

# Expected output:
15.756968956847974
# average of first n even natural numbers | function to find average of sum of first n even numbers ; sum of first n even numbers ; calculating average ; 
def avg_of_even_num(n):
    sum = 0
    for i in range(1, n + 1):
        sum = sum + 2 * i
    return sum / n


n = 9
print(avg_of_even_num(n))

# Expected output:
10.0
# average of first n even natural numbers | return the average of sum of first n even numbers ; 
def avg_of_even_num(n):
    return n + 1


n = 8
print(avg_of_even_num(n))

# Expected output:
9
# sum of square of first n odd numbers | python3 code to find sum of square of first n odd numbers ; 
def squareSum(n):
    return int(n * (4 * n * n - 1) / 3)


ans = squareSum(8)
print(ans)

# Expected output:
680
# check whether given three numbers are adjacent primes | function checks whether given number is prime or not . ; check if n is a multiple of 2 ; if not , then just check the odds ; return next prime number ; start with next number ; breaks after finding next prime number ; check given three numbers are adjacent primes are not ; check given three numbers are primes are not ; find next prime of a ; if next is not same as 'a ; if next next is not same as 'c ; 
def isPrime(n):
    if (n % 2 == 0):
        return False
    i = 3
    while (i*i <= n):
        if (n % i == 0):
            return False
        i = i + 2
    return True


def nextPrime(start):
    nxt = start + 1
    while (isPrime(nxt) == False):
        nxt = nxt + 1

    return nxt


def areAdjacentPrimes(a, b, c):
    if (isPrime(a) == False or isPrime(b) == False
            or isPrime(c) == False):
        return False
    nxt = nextPrime(a)
    if (nxt != b):
        return False
    if (nextPrime(b) != c):
        return False

    return True


if (areAdjacentPrimes(11, 13, 19)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | python3 program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; function that find sum of series . ; 

import math


def sumOfSeries(n):
    return ((n * (n + 1) * (2 * n + 1)) / 6)


n = 10
print(sumOfSeries(n))

# Expected output:
385.0
# maximum binomial coefficient term value | returns value of binomial coefficient c ( n , k ) ; calculate value of binomial coefficient in bottom up manner ; base cases ; calculate value using previously stored values ; return maximum binomial coefficient term value . ; if n is even ; if n is odd ; 
def binomialCoeff(n, k):
    C = [[0 for x in range(k + 1)]for y in range(n + 1)]
    for i in range(n + 1):
        for j in range(min(i, k) + 1):
            if (j == 0 or j == i):
                C[i][j] = 1
            else:
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j]
    return C[n][k]


def maxcoefficientvalue(n):
    if (n % 2 == 0):
        return binomialCoeff(n, int(n / 2))
    else:
        return binomialCoeff(n, int((n + 1) / 2))


if __name__ == '__main__':
    n = 4
    print(maxcoefficientvalue(n))

# Expected output:
6
# smallest n digit number divisible by given three numbers | python3 code to find smallest n digit number which is divisible by x , y and z . ; lcm for x , y , z ; returns smallest n digit number divisible by x , y and z ; find the lcm ; find power of 10 for least number ; reminder after ; if smallest number itself divides lcm . ; add lcm - reminder number for next n digit number ; this condition check the n digit number is possible or not if it is possible it return the number else return 0 ; 

import math


def LCM(x, y, z):
    ans = int((x * y) / (math.gcd(x, y)))
    return int((z * ans) / (math.gcd(ans, z)))


def findDivisible(n, x, y, z):
    lcm = LCM(x, y, z)
    ndigitnumber = math .pow(10, n - 1)
    reminder = ndigitnumber % lcm
    if reminder == 0:
        return ndigitnumber
    ndigitnumber += lcm - reminder
    if ndigitnumber < math .pow(10, n):
        return int(ndigitnumber)
    else:
        return 0


n = 4
x = 2
y = 3
z = 5
res = findDivisible(n, x, y, z)
if res != 0:
    print(res)
else:
    print("Not possible")

# Expected output:
1020
# sum of squares of first n natural numbers | return the sum of square of first n natural numbers ; 
def squaresum(n):
    return (n * (n + 1) / 2) * (2 * n + 1) / 3


n = 4
print(squaresum(n))

# Expected output:
30.0
# program to calculate distance between two points | python3 program to calculate distance between two points ; function to calculate distance ; calculating distance ; 

import math


def distance(x1, y1, x2, y2):
    return math .sqrt(math .pow(x2 - x1, 2) + math .pow(y2 - y1, 2) * 1.0)


print("%.6f" % distance(3, 4, 4, 3))

# Expected output:
1.414214
# check if a large number is divisibility by 15 | to find sum ; function to check if a large number is divisible by 15 ; length of string ; check divisibility by 5 ; sum of digits ; if divisible by 3 ; 
def accumulate(s):
    acc = 0
    for i in range(len(s)):
        acc += ord(s[i]) - 48
    return acc


def isDivisible(s):
    n = len(s)
    if (s[n - 1] != '5' and s[n - 1] != '0'):
        return False
    sum = accumulate(s)
    return (sum % 3 == 0)


s = "15645746327462384723984023940239"
if isDivisible(s):
    print("Yes")
else:
    print("No")
s = "15645746327462384723984023940235"
if isDivisible(s):
    print("Yes")
else:
    print("No")

# Expected output:
No
Yes
# shortest path with exactly k edges in a directed and weighted graph | define number of vertices in the graph and inifinite value ; a naive recursive function to count walks from u to v with k edges ; base cases ; initialize result ; go to all adjacents of u and recur ; 

V = 4
INF = 999999999999


def shortestPath(graph, u, v, k):
    if k == 0 and u == v:
        return 0
    if k == 1 and graph[u][v] != INF:
        return graph[u][v]
    if k <= 0:
        return INF
    res = INF
    for i in range(V):
        if graph[u][i] != INF and u != i and v != i:
            rec_res = shortestPath(graph, i, v, k - 1)
            if rec_res != INF:
                res = min(res, graph[u][i] + rec_res)
    return res


if __name__ == '__main__':
    INF = 999999999999
    graph = [[0, 10, 3, 2], [INF, 0, INF, 7],
             [INF, INF, 0, 6], [INF, INF, INF, 0]]
    u = 0
    v = 3
    k = 2
    print("Weight of the shortest path is", shortestPath(graph, u, v, k))

# Expected output:
Weight of the shortest path is 9
# shortest path with exactly k edges in a directed and weighted graph | define number of vertices in the graph and inifinite value ; a dynamic programming based function to find the shortest path from u to v with exactly k edges . ; table to be filled up using dp . the value sp [ i ] [ j ] [ e ] will store weight of the shortest path from i to j with exactly k edges ; loop for number of edges from 0 to k ; for source ; for destination ; 

V = 4
INF = 999999999999


def shortestPath(graph, u, v, k):
    global V, INF
    sp = [[None] * V for i in range(V)]
    for i in range(V):
        for j in range(V):
            sp[i][j] = [None] * (k + 1)
    for e in range(k + 1):
        for i in range(V):
            for j in range(V):
                sp[i][j][e] = INF
                if (e == 0 and i == j):
                    sp[i][j][e] = 0
                if (e == 1 and graph[i][j] != INF):
                    sp[i][j][e] = graph[i][j]
                if (e > 1):
                    for a in range(V):
                        if (graph[i][a] != INF and i != a and j !=
                                a and sp[a][j][e - 1] != INF):
                            sp[i][j][e] = min(
                                sp[i][j][e], graph[i][a] + sp[a][j][e - 1])
    return sp[u][v][k]


graph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]]
u = 0
v = 3
k = 2
print("Weight of the shortest path is", shortestPath(graph, u, v, k))

# Expected output:
Weight of the shortest path is 9
# multistage graph ( shortest path ) | returns shortest distance from 0 to n - 1. ; dist [ i ] is going to store shortest distance from node i to node n - 1. ; calculating shortest path for rest of the nodes ; initialize distance from i to destination ( n - 1 ) ; check all nodes of next stages to find shortest distance from i to n - 1. ; reject if no edge exists ; we apply recursive equation to distance to target through j . and compare with minimum distance so far . ; 
def shortestDist(graph):
    global INF
    dist = [0] * N
    dist[N - 1] = 0
    for i in range(N - 2, -1, -1):
        dist[i] = INF
        for j in range(N):
            if graph[i][j] == INF:
                continue
            dist[i] = min(dist[i], graph[i][j] + dist[j])
    return dist[0]


N = 8
INF = 999999999999
graph = [
    [
        INF, 1, 2, 5, INF, INF, INF, INF], [
            INF, INF, INF, INF, 4, 11, INF, INF], [
                INF, INF, INF, INF, 9, 5, 16, INF], [
                    INF, INF, INF, INF, INF, INF, 2, INF], [
                        INF, INF, INF, INF, INF, INF, INF, 18], [
                            INF, INF, INF, INF, INF, INF, INF, 13], [
                                INF, INF, INF, INF, INF, INF, INF, 2]]
print(shortestDist(graph))

# Expected output:
9
# reverse level order traversal | a binary tree node ; function to print reverse level order traversal ; print nodes at a 

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


def printGivenLevel(root, level):
    if root is None:
        return
    if level == 1:
        print(root .data,)
    elif level > 1:
        printGivenLevel(root .left, level - 1)
        printGivenLevel(root .right, level - 1)


def height(node):
    if node is None:
        return 0
    else:
        lheight = height(node .left)
        rheight = height(node .right)
        if lheight > rheight:
            return lheight + 1
        else:
            return rheight + 1


def reverseLevelOrder(root):
    h = height(root)
    for i in reversed(range(1, h + 1)):
        printGivenLevel(root, i)


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
print("Level Order traversal of binary tree is")
reverseLevelOrder(root)

# Expected output:
Level Order traversal of binary tree is
4
5
2
3
1
# frequency of maximum occurring subsequence in given string | python3 program for the above approach ; function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i ] [ j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; increment the count of subsequence j and s [ i ] ; update the frequency array ; for 1 length subsequence ; for 2 length subsequence ; return the final result ; 

import numpy


def findCount(s):
    freq = [0] * 26
    dp = [[0] * 26] * 26
    freq = numpy .zeros(26)
    dp = numpy .zeros([26, 26])
    for i in range(0, len(s)):
        for j in range(26):
            dp[j][ord(s[i]) - ord('a')] += freq[j]
        freq[ord(s[i]) - ord('a')] += 1
    ans = 0
    for i in range(26):
        ans = max(freq[i], ans)
    for i in range(0, 26):
        for j in range(0, 26):
            ans = max(dp[i][j], ans)
    return int(ans)


str = "acbab"
print(findCount(str))

# Expected output:
3
# create an array such that xor of subarrays of length k is x | function to construct the array ; creating a list of size k , initialised with 0 ; initialising the first element with the given xor ; 
def constructArray(N, K, X):
    ans = []
    for i in range(0, K):
        ans .append(0)
    ans[0] = X
    for i in range(0, N):
        print(ans[i % K], end=" ")


N = 5
K = 2
X = 4
constructArray(N, K, X)

# Expected output:
4 0 4 0 4
# two player game in which a player can remove all occurrences of a number | python3 implementation for two player game in which a player can remove all occurrences of a number ; function that print whether player1 can wins or loses ; storing the number of occurrence of elements in unordered map ; variable to check if the occurrence of repeated elements is >= 4 and multiple of 2 or not ; count elements which occur more than once ; 

from collections import defaultdict


def game(v, n):
    m = defaultdict(int)
    for i in range(n):
        if (v[i]not in m):
            m[v[i]] = 1
        else:
            m[v[i]] += 1
    count = 0
    check = 0
    for i in m .values():
        if (i > 1):
            if (i >= 4 and i % 2 == 0):
                check += 1
            count += 1
    if (check % 2 != 0):
        flag = False
    if (check % 2 != 0):
        print("Yes")
    elif (n % 2 == 0 and count % 2 == 0):
        print("No")
    else:
        print("Yes")


if __name__ == "__main__":
    arr = [3, 2, 2, 3, 3, 5]
    size = len(arr)
    game(arr, size)

# Expected output:
No
# count of elements which form a loop in an array according to given constraints | python3 program to number of elements which form a cycle in an array ; function to count number of elements forming a cycle ; array to store parent node of traversal . ; array to determine whether current node is already counted in the cycle . ; check if current node is already traversed or not . if node is not traversed yet then parent value will be - 1. ; traverse the graph until an already visited node is not found . ; check parent value to ensure a cycle is present . ; count number of nodes in the cycle . ; 

import math
mod = 1000000007


def solve(A, n):
    cnt = 0
    parent = [-1] * n
    vis = [0] * n
    for i in range(n):
        j = i
        if (parent[j] == -1):
            while (parent[j] == -1):
                parent[j] = i
                j = math .gcd(j, A[j]) % n
            if (parent[j] == i):
                while (vis[j] == 0):
                    vis[j] = 1
                    cnt += 1
                    j = math .gcd(j, A[j]) % n
    return cnt


A = [1, 1, 6, 2]
n = len(A)
print(solve(A, n))

# Expected output:
2
# find farthest node from each node in tree | add edge between u and v in tree ; edge from u to v ; edge from v to u ; dfs to find the first end node of diameter ; calculating level of nodes ; go in opposite direction of parent ; function to clear the levels of the nodes ; set all value of lvl [ ] to 0 for next dfs ; set maximum with 0 ; dfs will calculate second end of the diameter ; calculating level of nodes ; store the node with maximum depth from end1 ; go in opposite direction of parent ; function to find the distance of the farthest distant node ; storing distance from end1 to node u ; function to find the distance of nodes from second end of diameter ; storing distance from end2 to node u ; joining edge between two nodes of the tree ; find the one end of the diameter of tree ; find the other end of the diameter of tree ; find the distance to each node from end1 ; find the distance to each node from end2 ; comparing distance between the two ends of diameter ; 
def AddEdge(u, v):
    global adj
    adj[u].append(v)
    adj[v].append(u)


def findFirstEnd(u, p):
    global lvl, adj, end1, maxi
    lvl[u] = 1 + lvl[p]
    if (lvl[u] > maxi):
        maxi = lvl[u]
        end1 = u
    for i in range(len(adj[u])):
        if (adj[u][i] != p):
            findFirstEnd(adj[u][i], u)


def clear(n):
    global lvl, dist1, dist2
    for i in range(n + 1):
        lvl[i] = 0
    maxi = 0
    dist1[0] = dist2[0] = -1


def findSecondEnd(u, p):
    global lvl, adj, maxi, end2
    lvl[u] = 1 + lvl[p]
    if (lvl[u] > maxi):
        maxi = lvl[u]
        end2 = u
    for i in range(len(adj[u])):
        if (adj[u][i] != p):
            findSecondEnd(adj[u][i], u)


def findDistancefromFirst(u, p):
    global dist1, adj
    dist1[u] = 1 + dist1[p]
    for i in range(len(adj[u])):
        if (adj[u][i] != p):
            findDistancefromFirst(adj[u][i], u)


def findDistancefromSecond(u, p):
    global dist2, adj
    dist2[u] = 1 + dist2[p]
    for i in range(len(adj[u])):
        if (adj[u][i] != p):
            findDistancefromSecond(adj[u][i], u)


def findNodes():
    global adj, lvl, dist1, dist2, end1, end2, maxi
    n = 5
    AddEdge(1, 2)
    AddEdge(1, 3)
    AddEdge(3, 4)
    AddEdge(3, 5)
    findFirstEnd(1, 0)
    clear(n)
    findSecondEnd(end1, 0)
    findDistancefromFirst(end1, 0)
    findDistancefromSecond(end2, 0)
    for i in range(1, n + 1):
        x = dist1[i]
        y = dist2[i]
        if (x >= y):
            print(end1, end=" ")
        else:
            print(end2, end=" ")


if __name__ == '__main__':
    adj = [[]for i in range(10000)]
    lvl = [0 for i in range(10000)]
    dist1 = [-1 for i in range(10000)]
    dist2 = [-1 for i in range(10000)]
    end1, end2, maxi = 0, 0, 0
    findNodes()

# Expected output:
4 4 2 2 2
# shortest palindromic substring | function return the shortest palindromic substring ; one by one consider every character as center point of even and length palindromes ; find the longest odd length palindrome with center point as i ; find the even length palindrome with center points as i - 1 and i . ; smallest substring which is not empty ; 
def ShortestPalindrome(s):
    n = len(s)
    v = []
    for i in range(n):
        l = i
        r = i
        ans1 = ""
        ans2 = ""
        while ((l >= 0) and (r < n) and (s[l] == s[r])):
            ans1 += s[l]
            l -= 1
            r += 1
        l = i - 1
        r = i
        while ((l >= 0) and (r < n) and (s[l] == s[r])):
            ans2 += s[l]
            l -= 1
            r += 1
        v .append(ans1)
        v .append(ans2)
    ans = v[0]
    for i in range(len(v)):
        if (v[i] != ""):
            ans = min(ans, v[i])
    return ans


s = "geeksforgeeks"
print(ShortestPalindrome(s))

# Expected output:
e
# find numbers which are multiples of first array and factors of second array | python3 implementation of the approach ; function to return the lcm of two numbers ; function to print the required numbers ; to store the lcm of array a [ ] elements and the gcd of array b [ ] elements ; finding lcm of first array ; finding gcd of second array ; no such element exists ; all the multiples of lcma which are less than or equal to gcdb and evenly divide gcdb will satisfy the conditions ; 

from math import gcd


def lcm(x, y):
    temp = (x * y) // gcd(x, y)
    return temp


def findNumbers(a, n, b, m):
    lcmA = 1
    __gcdB = 0
    for i in range(n):
        lcmA = lcm(lcmA, a[i])
    for i in range(m):
        __gcdB = gcd(__gcdB, b[i])
    if (__gcdB % lcmA != 0):
        print("-1")
        return
    num = lcmA
    while (num <= __gcdB):
        if (__gcdB % num == 0):
            print(num, end=" ")
        num += lcmA


if __name__ == "__main__":
    a = [1, 2, 2, 4]
    b = [16, 32, 64]
    n = len(a)
    m = len(b)
    findNumbers(a, n, b, m)

# Expected output:
4 8 16