giulio98/xlcost-single-prompt huggingface dataset:
# how to validate a domain name using regular expression | python3 program to validate domain name using regular expression ; function to validate domain name . ; regex to check valid domain name . ; compile the regex ; if the string is empty return false ; return if the string matched the regex ; test case 1 : ; test case 2 : ; test case 3 : ; test case 4 : ; 

import re


def isValidDomain(str):
    regex = "^((?!-)[A-Za-z0-9-]"+"{1,63}(?<!-)\.)"
    p = re .compile(regex)
    if (str is None):
        return False
    if (re .search(p, str)):
        return True
    else:
        return False


str1 = "geeksforgeeks.org"
print(isValidDomain(str1))
str2 = "contribute.geeksforgeeks.org"
print(isValidDomain(str2))
str3 = "-geeksforgeeks.org"
print(isValidDomain(str3))
str4 = "geeksforgeeks.o"
print(isValidDomain(str4))
str5 = ".org"
print(isValidDomain(str5))

# Expected output:
True
True
False
True
False
# how to validate ssn ( social security number ) using regular expression | python3 program to validate ssn ( social security number ) using regular expression ; function to validate ssn ( social security number ) . ; regex to check valid ssn ( social security number ) . ; compile the regex ; if the string is empty return false ; return if the string matched the regex ; test case 1 : ; test case 2 : ; test case 3 : ; 

import re


def isValidSSN(str):
    regex = "^(?!666 000 9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$"
    p = re .compile(regex)
    if (str is None):
        return False
    if (re .search(p, str)):
        return True
    else:
        return False


str1 = "856-45-6789"
print(isValidSSN(str1))
str2 = "000-45-6789"
print(isValidSSN(str2))
str3 = "856-452-6789"
print(isValidSSN(str3))
str4 = "856-45-0000"
print(isValidSSN(str4))

# Expected output:
True
True
False
False
# how to check aadhar number is valid or not using regular expression | python3 program to validate aadhar number using regex . ; function to validate aadhar number . ; regex to check valid aadhar number . ; compile the regex ; if the string is empty return false ; return if the string matched the regex ; test case 1 : ; test case 2 : ; test case 3 : ; test case 4 : str4 = "3675 ▁ 98af ▁ 602" ; 

import re


def isValidAadharNumber(str):
    regex = ("^[2-9]{1}[0-9]{3}\\" + "s[0-9]{4}\\s[0-9]{4}$")
    p = re .compile(regex)
    if (str is None):
        return False
    if (re .search(p, str)):
        return True
    else:
        return False


str1 = "3675 9834 6015"
print(isValidAadharNumber(str1))
str2 = "4675 9834 6012 8"
print(isValidAadharNumber(str2))
str3 = "0175 9834 6012"
print(isValidAadharNumber(str3))
str5 = "417598346012"
print(isValidAadharNumber(str5))

# Expected output:
True
False
False
False
# how to validate pin code of india using regular expression | python3 program to validate the pin code of india using regular expression . ; function to validate the pin code of india . ; regex to check valid pin code of india . ; compile the regex ; if the pin code is empty return false ; pattern class contains matcher ( ) method to find matching between given pin code and regular expression . ; return true if the pin code matched the regex else false ; 

import re


def isValidPinCode(pinCode):
    regex = "^[1-9]{1}[0-9]{2}\\s{0,1}[0-9]{3}$"
    p = re .compile(regex)
    if (pinCode == ''):
        return False
    m = re .match(p, pinCode)
    if m is None:
        return False
    else:
        return True


if __name__ == "__main__":
    num1 = "132103"
    print(num1, ": ", isValidPinCode(num1))
    num2 = "201 305"
    print(num2, ": ", isValidPinCode(num2))
    num3 = "014205"
    print(num3, ": ", isValidPinCode(num3))
    num4 = "1473598"
    print(num4, ": ", isValidPinCode(num4))

# Expected output:
132103 :  True
201 305 :  True
014205 :  False
1473598 :  False
# how to validate time in 24 | python3 program to validate the time in 24 - hour format using regular expression . ; function to validate the time in 24 - hour format ; regex to check valid time in 24 - hour format . ; compile the regex ; if the time is empty return false ; pattern class contains matcher ( ) method to find matching between given time and regular expression . ; return true if the time matched the regex otherwise false ; 

import re


def isValidTime(time):
    regex = "^([01]?[0-9] 2[0-3]):[0-5][0-9]$"
    p = re .compile(regex)
    if (time == ""):
        return False
    m = re .search(p, time)
    if m is None:
        return False
    else:
        return True


if __name__ == "__main__":
    str1 = "13:05"
    print(str1, ": ", isValidTime(str1))
    str2 = "02:15"
    print(str2, ": ", isValidTime(str2))
    str3 = "24:00"
    print(str3, ": ", isValidTime(str3))
    str4 = "10:60"
    print(str4, ": ", isValidTime(str4))
    str5 = "10:15 PM"
    print(str5, ": ", isValidTime(str5))

# Expected output:
13:05 :  False
02:15 :  False
24:00 :  False
10:60 :  False
10:15 PM :  False
# how to validate pan card number using regular expression | python3 program to validate the pan card number using regular expression ; function to validate the pan card number . ; regex to check valid pan card number ; compile the regex ; if the pan card number is empty return false ; return if the pan card number matched the regex ; test case 1 : ; test case 2 : ; test case 3 : ; test case 4 : ; 

import re


def isValidPanCardNo(panCardNo):
    regex = "[A-Z]{5}[0-9]{4}[A-Z]{1}"
    p = re .compile(regex)
    if (panCardNo is None):
        return False
    if (re .search(p, panCardNo) and len(panCardNo) == 10):
        return True
    else:
        return False


str1 = "BNZAA2318J"
print(isValidPanCardNo(str1))
str2 = "23ZAABN18J"
print(isValidPanCardNo(str2))
str3 = "BNZAA2318JM"
print(isValidPanCardNo(str3))
str4 = "BNZAA23184"
print(isValidPanCardNo(str4))
str5 = "BNZAA 23184"
print(isValidPanCardNo(str5))

# Expected output:
True
False
False
False
False
# program to build a dfa that checks if a string ends with "01" or "10" | end position is checked using the string length value . q0 is the starting state . q1 and q2 are intermediate states . q3 and q4 are final states . ; state transitions 0 takes to q1 , 1 takes to q3 ; state transitions 0 takes to q4 , 1 takes to q2 ; state transitions 0 takes to q4 , 1 takes to q2 ; state transitions 0 takes to q1 , 1 takes to q3 ; state transitions 0 takes to q1 , 1 takes to q2 ; 
def q1(s, i):
    print("q1->", end="")
    if (i == len(s)):
        print("NO")
        return
    if (s[i] == '0'):
        q1(s, i + 1)
    else:
        q3(s, i + 1)


def q2(s, i):
    print("q2->", end="")
    if (i == len(s)):
        print("NO")
        return
    if (s[i] == '0'):
        q4(s, i + 1)
    else:
        q2(s, i + 1)


def q3(s, i):
    print("q3->", end="")
    if (i == len(s)):
        print("YES")
        return
    if (s[i] == '0'):
        q4(s, i + 1)
    else:
        q2(s, i + 1)


def q4(s, i):
    print("q4->", end="")
    if (i == len(s)):
        print("YES")
        return
    if (s[i] == '0'):
        q1(s, i + 1)
    else:
        q3(s, i + 1)


def q0(s, i):
    print("q0->", end="")
    if (i == len(s)):
        print("NO")
        return
    if (s[i] == '0'):
        q1(s, i + 1)
    else:
        q2(s, i + 1)


if __name__ == "__main__":
    s = "010101"
    print("State transitions are", end=" ")
    q0(s, 0)

# Expected output:
State transitions are q0->q1->q3->q4->q3->q4->q3->YES
# check whether two strings contain same characters in same order | python3 implementation of approach ; if length of the b = 0 then we return true ; if length of a = 0 that means b is not present in a so we return false ; 
def checkSequence(a, b):
    if len(b) == 0:
        return True
    if len(a) == 0:
        return False
    if (a[0] == b[0]):
        return checkSequence(a[1:], b[1:])
    else:
        return checkSequence(a[1:], b)


if __name__ == '__main__':
    s1 = "Geeks"
    s2 = "Geks"
    if (checkSequence(s1, s2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# string matching with * ( that matches with any ) in any of the two strings | function to check if the two strings can be matched or not ; if the string don 't have *  then character t that position  must be same. ; 
def doMatch(A, B):
    for i in range(len(A)):
        if A[i] != '*' and B[i] != '*':
            if A[i] != B[i]:
                return False
    return True


if __name__ == '__main__':
    A = "gee*sforgeeks"
    B = "geeksforgeeks"
    print(int(doMatch(A, B)))

# Expected output:
1
# find nth term of the series 0 , 2 , 4 , 8 , 12 , 18. . . | calculate nth term of series ; 
def nthTerm(N):
    return (N + N * (N - 1)) // 2


if __name__ == "__main__":
    N = 5
    print(nthTerm(N))

# Expected output:
12
# find nth term of series 1 , 4 , 15 , 72 , 420. . . | function for finding factorial of n ; return factorial of n ; function for calculating nth term of series ; 
def factorial(N):
    fact = 1
    for i in range(1, N + 1):
        fact = fact * i
    return fact


def nthTerm(N):
    return (factorial(N) * (N + 2) // 2)


if __name__ == "__main__":
    N = 6
    print(nthTerm(N))

# Expected output:
2880
# sum of nodes at maximum depth of a binary tree | constructor ; function to find the sum of nodes at maximum depth arguments are node and max , where max is to match the depth of node at every call to node , if max will be equal to 1 , means we are at deepest node . ; base case ; max == 1 to track the node at deepest level ; recursive call to left and right nodes ; maxdepth function to find the max depth of the tree ; base case ; either leftdepth of rightdepth is greater add 1 to include height of node at which call is ; call to function to calculate max depth ; 

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


def sumMaxLevelRec(node, Max):
    if node is None:
        return 0
    if Max == 1:
        return node .data
    return (
        sumMaxLevelRec(
            node .left,
            Max -
            1) +
        sumMaxLevelRec(
            node .right,
            Max -
            1))


def maxDepth(node):
    if node is None:
        return 0
    return 1 + max(maxDepth(node .left), maxDepth(node .right))


def sumMaxLevel(root):
    MaxDepth = maxDepth(root)
    return sumMaxLevelRec(root, MaxDepth)


if __name__ == "__main__":
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .right .left = Node(6)
    root .right .right = Node(7)
    print(sumMaxLevel(root))

# Expected output:
22
# sum of manhattan distances between repetitions in a string | function to find the sum of the manhattan distances between same characters in string ; vector to store indices for each unique character of the string ; append the position of each character in their respective vectors ; store the required result ; iterate over all the characters ; calculate sum of all elements present in the vector ; traverse the current vector ; find suffix [ i + 1 ] ; adding distance of all pairs whose first element is i and second element belongs to [ i + 1 , n ] ; prthe result ; 
def SumofDistances(s):
    v = [[]for i in range(26)]
    for i in range(len(s)):
        v[ord(s[i]) - ord('a')].append(i)
    ans = 0
    for i in range(26):
        sum = 0
        for j in range(len(v[i])):
            sum += v[i][j]
        for j in range(len(v[i])):
            sum -= v[i][j]
            ans += (sum - (len(v[i]) - 1 - j) * (v[i][j]))
    print(ans)


if __name__ == '__main__':
    s = "ababa"
    SumofDistances(s)

# Expected output:
10
# minimum prefixes required to be flipped to convert a binary string to another | function to count flips required to make strings a and b equal ; stores the count of the number of operations ; stores the length of the chosen prefixes ; stores if operations are performed even or odd times ; traverse the given string ; if current characters in the two strings are unequal ; if a [ i ] is not flipped ; increment count of operations ; insert the length of the chosen prefix ; update invert to true ; if a [ i ] is flipped ; increment count of operations ; insert length of the chosen prefix ; update invert to false ; print the number of operations required ; print the chosen prefix length in each operation ; 
def findOperations(A, B, N):
    operations = 0
    ops = []
    invert = False
    for i in range(N - 1, -1, -1):
        if (A[i] != B[i]):
            if (not invert):
                operations += 1
                ops .append(i + 1)
                invert = True
        else:
            if (invert):
                operations += 1
                ops .append(i + 1)
                invert = False
    print(operations)
    if (operations != 0):
        for x in ops:
            print(x, end=" ")


if __name__ == '__main__':
    A, B = "001", "000"
    N = len(A)
    findOperations(A, B, N)

# Expected output:
2
3 2
# maximize cost of forming a set of words using given set of characters | function to find the maximum cost of any valid set of words formed by using the given letters ; stores frequency of characters ; find the maximum cost ; utility function to find maximum cost of generating any possible subsets of strings ; base case ; stores the current cost ; stores the cost of by the current word ; create a copy of the lettercounts array ; traverse the current word ; store the current index & check if its frequency is 0 or not ; if true , then update wordscore to - 1 ; otherwise , add the cost of the current index to wordscore ; decrease its frequency ; if wordscore > 0 , then recursively call for next index ; find the cost by not including current word ; return the maximum score ; 
def helper(words, start, letterCounts, score):
    if (start == len(words)):
        return 0
    currScore = 0
    wordScore = 1
    nextCounts = letterCounts
    for i in range(len(words[start])):
        idx = ord(words[start][i]) - ord('a')
        if (nextCounts[idx] == 0):
            wordScore = -1
            break
        wordScore += score[idx]
        nextCounts[idx] -= 1
    if (wordScore > 0):
        currScore = helper(words, start + 1, nextCounts, score) + wordScore
    currScore = max(currScore, helper(words, start + 1, letterCounts, score))
    return currScore

def maxScoreWords(words, letters, score):
    letterCounts = [0] * (26)
    for letter in letters:
        letterCounts[ord(letter) - ord('a')] += 1
    return helper(words, 0, letterCounts, score)


words = ["dog", "cat", "dad", "good"]
letters = ['a', 'a', 'c', 'd', 'd', 'd', 'g', 'o', 'o']
score = [1, 0, 9, 5, 0, 0, 3, 0, 0, 0, 0, 0,
         0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
print(maxScoreWords(words, letters, score))

# Expected output:
23
# modify string by sorting characters after removal of characters whose frequency is not equal to power of 2 | python3 program for the above approach ; function to remove all the characters from a that whose frequencies are not equal to a perfect power of 2 ; stores the frequency of each character in s ; iterate over characters of string ; update frequency of current character in the array freq [ ] ; traverse the array freq [ ] ; check if the i - th letter is absent from s ; calculate log of frequency of the current character in the s ; calculate power of 2 of lg ; check if freq [ i ] is a power of 2 ; print letter i + ' a ' freq [ i ] times ; 

from math import log2


def countFrequency(S, N):
    freq = [0] * 26
    for i in range(N):
        freq[ord(S[i]) - ord('a')] += 1
    for i in range(26):
        if (freq[i] == 0):
            continue
        lg = int(log2(freq[i]))
        a = pow(2, lg)
        if (a == freq[i]):
            while (freq[i]):
                print(chr(i + ord('a')), end="")
                freq[i] -= 1


if __name__ == '__main__':
    S = "aaacbb"
    N = len(S)
    countFrequency(S, N)

# Expected output:
bbc
# longest common subsequence ( lcs ) by repeatedly swapping characters of a string with characters of another string | function to find the length of lcs possible by swapping any character of a with that of another string ; store the size of the strings ; stores frequency of characters ; iterate over characters of the a ; update frequency of character a [ i ] ; iterate over characters of the b ; update frequency of character b [ i ] ; store the count of all pairs of similar characters ; traverse the array freq [ ] ; update cnt ; print the minimum of cnt , n and m ; 
def lcsBySwapping(A, B):
    N = len(A)
    M = len(B)
    freq = [0] * 26
    for i in range(len(A)):
        freq[ord(A[i]) - ord('a')] += 1
    for i in range(len(B)):
        freq[ord(B[i]) - ord('a')] += 1
    cnt = 0
    for i in range(26):
        cnt += freq[i] // 2
    print(min(cnt, min(N, M)))


if __name__ == '__main__':
    A = "abdeff"
    B = "abbet"
    lcsBySwapping(A, B)

# Expected output:
4
# length of longest subsequence whose difference between maximum and minimum ascii value of characters is exactly one | function to find the maximum length of subsequence having difference of ascii value of longest and smallest character as 1 ; stores frequency of characters ; iterate over characters of the string ; stores the resultant length of subsequence ; check if there exists any elements with ascii value one less than character ch ; size of current subsequence ; update the value of ans ; print the resultant count ; 
def maximumLengthSubsequence(str):
    mp = {}
    for ch in str:
        if ch in mp .keys():
            mp[ch] += 1
        else:
            mp[ch] = 1
    ans = 0
    for ch in str:
        if chr(ord(ch) - 1) in mp .keys():
            curr_max = mp[ch]
            if chr(ord(ch) - 1) in mp .keys():
                curr_max += mp[chr(ord(ch) - 1)]
            ans = max(ans, curr_max)
    print(ans)


S = "acbbebcg"
maximumLengthSubsequence(S)

# Expected output:
5
# minimum increments by 1 or k required to convert a string into another given string | function to count minimum increments by 1 or k required to convert x to y ; traverse the string x ; case 1 ; case 2 ; add the difference / k to the count ; add the difference % k to the count ; case 3 ; add the difference / k to the count ; add the difference % k to the count ; print the answer ; 
def countOperations(X, Y, K):
    count = 0
    for i in range(len(X)):
        c = 0
        if (X[i] == Y[i]):
            continue
        elif (X[i] < Y[i]):
            if ((ord(Y[i]) - ord(X[i])) >= K):
                c = (ord(Y[i]) - ord(X[i])) // K
            c += (ord(Y[i]) - ord(X[i])) % K
        else:
            t = 90 - ord(X[i])
            t += ord(Y[i]) - 65 + 1
            if (t >= K):
                c = t // K
            c += (t % K)
        count += c
    print(count)


X = "ABCT"
Y = "PBDI"
K = 6
countOperations(X, Y, K)

# Expected output:
11
# minimum number of swaps required such that a given substring consists of exactly k 1 s | function to find the minimum number of swaps required such that the substring { s [ l ] , . . , s [ r ] } consists of exactly k 1 s ; store the size of the string ; store the total number of 1 s and 0 s in the entire string ; traverse the string s to find the frequency of 1 and 0 ; store the number of 1 s and 0 s in the substring s [ l , r ] ; traverse the substring s [ l , r ] to find the frequency of 1 s and 0 s in it ; store the count of 1 s and 0 s outside substring s [ l , r ] ; check if the sum of the substring is at most k ; store number of 1 s required ; check if there are enough 1 s remaining to be swapped ; if the count of 1 s in the substring exceeds k ; store the number of 0 s required ; check if there are enough 0 s remaining to be swapped ; in all other cases , print - 1 ; 
def minimumSwaps(s, l, r, k):
    n = len(s)
    tot_ones, tot_zeros = 0, 0
    for i in range(0, len(s)):
        if (s[i] == '1'):
            tot_ones += 1
        else:
            tot_zeros += 1
    ones, zeros, Sum = 0, 0, 0
    for i in range(l - 1, r):
        if (s[i] == '1'):
            ones += 1
            Sum += 1
        else:
            zeros += 1
    rem_ones = tot_ones - ones
    rem_zeros = tot_zeros - zeros
    if (k >= Sum):
        rem = k - Sum
        if (zeros >= rem and rem_ones >= rem):
            return rem
    elif (k < Sum):
        rem = Sum - k
        if (ones >= rem and rem_zeros >= rem):
            return rem
    return -1


S = "110011111000101"
L, R, K = 5, 8, 2
print(minimumSwaps(S, L, R, K))

# Expected output:
2
# check if given number contains only “ 01 ” and “ 10 ” as substring in its binary representation | python3 program to implement the above approach ; function to generate all numbers having "01" and "10" as a substring ; insert 2 and 5 ; iterate till x is 10 ^ 15 ; multiply x by 2 ; update x as x * 2 + 1 ; function to check if binary representation of n contains only "01" and "10" as substring ; function call to generate all such numbers ; check if a number n exists in ans [ ] or not ; if the number exists ; 

Ans = []


def populateNumber():
    Ans .append(2)
    Ans .append(5)
    x = 5
    while (x < 1000000000001):
        x *= 2
        Ans .append(x)
        x = x * 2 + 1
        Ans .append(x)


def checkString(N):
    populateNumber()
    for it in Ans:
        if (it == N):
            return "Yes"
    return "No"


N = 5
print(checkString(N))

# Expected output:
Yes
# count minimum substring removals required to reduce string to a single distinct character | python3 program for the above approach ; function to find minimum removals required to convert given string to single distinct characters only ; unordered map to store positions of characters x , y and z ; update indices of x , y , z ; ; stores the count of minimum removals ; traverse the map ; count the number of removals required for current character ; update the answer ; print the answer ; 

import sys
INT_MAX = sys .maxsize


def minimumOperations(s, n):
    mp = {}
    for i in range(n):
        if s[i] in mp:
            mp[s[i]].append(i)
        else:
            mp[s[i]] = [i]
    ans = INT_MAX
    for x in mp:
        curr = 0
        prev = 0
        first = True
        for index in mp[x]:
            if (first):
                if (index > 0):
                    curr += 1
                prev = index
                first = False
            else:
                if (index != prev + 1):
                    curr += 1
                prev = index
        if (prev != n - 1):
            curr += 1
        ans = min(ans, curr)
    print(ans)


if __name__ == "__main__":
    s = "YYXYZYXYZXY"
    N = len(s)
    minimumOperations(s, N)

# Expected output:
3
# program to construct dfa accepting odd number of 0 s and odd number of 1 s | function to check whether the given is accepted by dfa or not ; stores initial state of dfa ; stores final state of dfa ; stores previous state of dfa ; iterate through the string ; checking for all combinations ; update the previous_state ; if final state is reached ; otherwise ; 
def checkValidDFA(s):
    initial_state = 0
    final_state = 0
    previous_state = 0
    for i in range(len(s)):
        if ((s[i] == '0' and previous_state == 0) or (
                s[i] == '1' and previous_state == 3)):
            final_state = 1
        elif ((s[i] == '0' and previous_state == 3) or (s[i] == '1' and previous_state == 0)):
            final_state = 2
        elif ((s[i] == '0' and previous_state == 1) or (s[i] == '1' and previous_state == 2)):
            final_state = 0
        elif ((s[i] == '0' and previous_state == 2) or (s[i] == '1' and previous_state == 1)):
            final_state = 3
        previous_state = final_state
    if (final_state == 3):
        print("Accepted")
    else:
        print("Not Accepted")


if __name__ == '__main__':
    s = "010011"
    checkValidDFA(s)

# Expected output:
Accepted