Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
17
2.11k
code
stringlengths
82
3.44k
Maximum Prefix Sum possible by merging two given arrays | Python3 implementation of the above approach ; Stores the maximum prefix sum of the array A [ ] ; Traverse the array A [ ] ; Stores the maximum prefix sum of the array B [ ] ; Traverse the array B [ ] ; Driver code
def max_presum(a, b): """ Maximum Prefix Sum possible by merging two given arrays """ X = max(a[0], 0) for i in range(1, len(a)): a[i] += a[i - 1] X = max(X, a[i]) Y = max(b[0], 0) for i in range(1, len(b)): b[i] += b[i - 1] Y = max(Y, b[i]) return X + Y ...
Check if a number can be represented as sum of two positive perfect cubes | Python3 program for the above approach ; Function to check if N can be represented as sum of two perfect cubes or not ; If it is same return true ; ; If the curr smaller than n increment the lo ; If the curr is greater than curr decrement the h...
import math def sum_of_two_cubes(n): """ Check if a number can be represented as sum of two positive perfect cubes """ lo = 1 hi = round(math.pow(n, 1 / 3)) while (lo <= hi): curr = (lo * lo * lo + hi * hi * hi) if (curr == n): return True if (curr < n): ...
Nth natural number after removing all numbers consisting of the digit 9 | Function to find Nth number in base 9 ; Stores the Nth number ; Iterate while N is greater than 0 ; Update result ; Divide N by 9 ; Multiply p by 10 ; Return result ; Driver Code
def find_nth_number(N): """ Nth natural number after removing all numbers consisting of the digit 9 """ result = 0 p = 1 while (N > 0): result += (p * (N % 9)) N = N // 9 p = p * 10 return result if __name__ == '__main__': N = 9 print(find_nth_number(N))
Check if an integer is rotation of another given integer | Python3 implementation of the approach ; Function to check if the integer A is a rotation of the integer B ; Stores the count of digits in A ; Stores the count of digits in B ; If dig1 not equal to dig2 ; Stores position of first digit ; Stores the first digit ...
import math def check(A, B): """ Check if an integer is rotation of another given integer """ if (A == B): return 1 dig1 = math.floor(math.log10(A) + 1) dig2 = math.floor(math.log10(B) + 1) if (dig1 != dig2): return 0 temp = A while (True): power = pow(10, d...
Count of quadruples with product of a pair equal to the product of the remaining pair | Function to count the number of unique quadruples from an array that satisfies the given condition ; Hashmap to store the product of pairs ; Store the count of required quadruples ; Traverse the array arr [ ] and generate all possib...
def same_product_quadruples(nums, N): """ Count of quadruples with product of a pair equal to the product of the remaining pair """ umap = {} res = 0 for i in range(N): for j in range(i + 1, N): prod = nums[i] * nums[j] if prod in umap: res += 8 * ...
Check if a graph constructed from an array based on given conditions consists of a cycle or not | Function to check if the graph constructed from given array contains a cycle or not ; Traverse the array ; If arr [ i ] is less than arr [ i - 1 ] and arr [ i ] ; Driver Code ; Given array ; Size of the array
def is_cycle_exists(arr, N): """ Check if a graph constructed from an array based on given conditions consists of a cycle or not """ valley = 0 for i in range(1, N): if (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]): print("Yes") return print("No") if __name__ ==...
Maximize first array element by performing given operations at most K times | Function to maximize the first array element ; Traverse the array ; Initialize cur_val to a [ i ] ; If all operations are not over yet ; If current value is greater than zero ; Incrementing first element of array by 1 ; Decrementing current v...
def get_max(arr, N, K): """ Maximize first array element by performing given operations at most K times """ for i in range(1, N, 1): cur_val = arr[i] while (K >= i): if (cur_val > 0): arr[0] = arr[0] + 1 cur_val = cur_val - 1 K ...
Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct | Function to return number of moves to convert matrix into chessboard ; Size of the matrix ; Traverse the matrix ; Initialize rowSum to count 1 s in row ; Initialize colSum to count 1 s in column ; To store no . of row...
def min_swaps(b): """ Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct """ n = len(b) for i in range(n): for j in range(n): if (b[0][0] ^ b[0][j] ^ b[i][0] ^ b[i][j]): return -1 rowSum = 0 colSum = 0 ...
Minimum number of coins having value equal to powers of 2 required to obtain N | Function to count of set bit in N ; Stores count of set bit in N ; Iterate over the range [ 0 , 31 ] ; If current bit is set ; Update result ; Driver Code
def count_setbit(N): """ Minimum number of coins having value equal to powers of 2 required to obtain N """ result = 0 for i in range(32): if ((1 << i) & N): result = result + 1 print(result) if __name__ == '__main__': N = 43 count_setbit(N)
Evaluate the expression ( N1 * ( N | Python 3 program to implement the above approach ; Function to find the value of the expression ( N ^ 1 * ( N 1 ) ^ 2 * ... * 1 ^ N ) % ( 109 + 7 ) . ; factorial [ i ] : Stores factorial of i ; Base Case for factorial ; Precompute the factorial ; dp [ N ] : Stores the value of the e...
mod = 1000000007 def val_of_the_expression(n): """ Evaluate the expression ( N1 * ( N """ global mod factorial = [0 for i in range(n + 1)] factorial[0] = 1 factorial[1] = 1 for i in range(2, n + 1, 1): factorial[i] = ((factorial[i - 1] % mod) * (i % mod)) % mod dp = [0 for ...
Chocolate Distribution Problem | Set 2 | Function to print minimum number of candies required ; Distribute 1 chocolate to each ; Traverse from left to right ; Traverse from right to left ; Initialize sum ; Find total sum ; Return sum ; Driver Code ; Given array ; Size of the given array
def min_chocolates(A, N): """ Chocolate Distribution Problem """ B = [1 for i in range(N)] for i in range(1, N): if (A[i] > A[i - 1]): B[i] = B[i - 1] + 1 else: B[i] = 1 for i in range(N - 2, -1, -1): if (A[i] > A[i + 1]): B[i] = max(B[...
Construct longest possible sequence of unique elements with given LCM | Python3 program to implement the above approach ; Function to construct an array of unique elements whose LCM is N ; Stores array elements whose LCM is N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If N is divisible by i ; Insert i into newArr [ ...
from math import sqrt, ceil, floor def construct_array_with_given_lcm(N): """ Construct longest possible sequence of unique elements with given LCM """ newArr = [] for i in range(1, ceil(sqrt(N + 1))): if (N % i == 0): newArr.append(i) if (N // i != i): ...
Sum of first N natural numbers with alternate signs | Function to find the sum of First N natural numbers with alternate signs ; Stores sum of alternate sign of First N natural numbers ; If is an even number ; Update alternateSum ; If i is an odd number ; Update alternateSum ; Driver Code
def alternating_sum_of_first_n(N): """ Sum of first N natural numbers with alternate signs """ alternateSum = 0 for i in range(1, N + 1): if (i % 2 == 0): alternateSum += -i else: alternateSum += i return alternateSum if __name__ == "__main__": N = 6...
Count all distinct pairs of repeating elements from the array for every array element | Function to prthe required count of pairs excluding the current element ; Store the frequency ; Find all the count ; Delete the contribution of each element for equal pairs ; Print the answer ; Driver Code ; Given array arr [ ] ; Fu...
def solve(arr, n): """ Count all distinct pairs of repeating elements from the array for every array element """ mp = {} for i in arr: mp[i] = mp.get(i, 0) + 1 cnt = 0 for x in mp: cnt += ((mp[x]) * (mp[x] - 1) // 2) ans = [0] * n for i in range(n): ans[i] = c...
Mode in a stream of integers ( running integers ) | Function that prints the Mode values ; Map used to mp integers to its frequency ; To store the maximum frequency ; To store the element with the maximum frequency ; Loop used to read the elements one by one ; Updates the frequency of that element ; Checks for maximum ...
def find_mode(a, n): """ Mode in a stream of integers ( running integers ) """ mp = {} max = 0 mode = 0 for i in range(n): if a[i] in mp: mp[a[i]] += 1 else: mp[a[i]] = 1 if (mp[a[i]] >= max): max = mp[a[i]] mode = a[i] ...
Generate first K multiples of N using Bitwise operators | Function to print the first K multiples of N ; Print the value of N * i ; Iterate each bit of N and add pow ( 2 , pos ) , where pos is the index of each set bit ; Check if current bit at pos j is fixed or not ; For next set bit ; Driver Code
def kmultiples(n, k): """ Generate first K multiples of N using Bitwise operators """ a = n for i in range(1, k + 1): print("{} * {} = {}".format(n, i, a)) j = 0 while (n >= (1 << j)): a += n & (1 << j) j += 1 N = 16 K = 7 kmultiples(N, K)
Count of repeating digits in a given Number | Function that returns the count of repeating digits of the given number ; Initialize a variable to store count of Repeating digits ; Initialize cnt array to store digit count ; Iterate through the digits of N ; Retrieve the last digit of N ; Increase the count of digit ; Re...
def count_repeating_digits(N): """ Count of repeating digits in a given Number """ res = 0 cnt = [0] * 10 while (N > 0): rem = N % 10 cnt[rem] += 1 N = N // 10 for i in range(10): if (cnt[i] > 1): res += 1 return res N = 12 print(count_repeat...
Find temperature of missing days using given sum and average | Function for finding the temperature ; Store Day1 - Day2 in diff ; Remaining from s will be Day1 ; Print Day1 and Day2 ; Driver Code ; Functions
def find_temperature(x, y, s): """ Find temperature of missing days using given sum and average """ diff = (x - y) * 6 Day2 = (diff + s) // 2 Day1 = s - Day2 print("Day1 : ", Day1) print("Day2 : ", Day2) if __name__ == '__main__': x = 5 y = 10 s = 40 find_temperature(x,...
Find two numbers whose sum is N and does not contain any digit as K | Function to find two numbers whose sum is N and do not contain any digit as k ; Check every number i and ( n - i ) ; Check if i and n - i doesn 't contain k in them print i and n-i ; check if flag is 0 then print - 1 ; Driver Code ; Given N and K ; ...
def find_aand_b(n, k): """ Find two numbers whose sum is N and does not contain any digit as K """ flag = 0 for i in range(1, n): if str(i).count(chr(k + 48)) == 0 and str(n - i).count(chr(k + 48)) == 0: print(i, n - i) ...
Find the value of P and modular inverse of Q modulo 998244353 | Function to find the value of P * Q ^ - 1 mod 998244353 ; Loop to find the value until the expo is not zero ; Multiply p with q if expo is odd ; Reduce the value of expo by 2 ; Driver code ; Function call
def calculate(p, q): """ Find the value of P and modular inverse of Q modulo 998244353 """ mod = 998244353 expo = 0 expo = mod - 2 while (expo): if (expo & 1): p = (p * q) % mod q = (q * q) % mod expo >>= 1 return p if __name__ == '__main__': p =...
Find two numbers with given sum and maximum possible LCM | Function that print two numbers with the sum X and maximum possible LCM ; If X is odd ; If X is even ; If floor ( X / 2 ) is even ; If floor ( X / 2 ) is odd ; Print the result ; Driver Code ; Given Number ; Function call
def max_lcm_with_given_sum(X): """ Find two numbers with given sum and maximum possible LCM """ if X % 2 != 0: A = X / 2 B = X / 2 + 1 else: if (X / 2) % 2 == 0: A = X / 2 - 1 B = X / 2 + 1 else: A = X / 2 - 2 B = X / 2 ...
Length of longest subarray whose sum is not divisible by integer K | Function to find the longest subarray with sum is not divisible by k ; left is the index of the leftmost element that is not divisible by k ; sum of the array ; Find the element that is not multiple of k ; left = - 1 means we are finding the leftmost ...
def max_subarray_length(arr, n, k): """ Length of longest subarray whose sum is not divisible by integer K """ left = -1 sum = 0 for i in range(n): if ((arr[i] % k) != 0): if (left == -1): left = i right = i sum += arr[i] if ((sum % k) ...
Minimum steps to convert X to Y by repeated division and multiplication | Python3 implementation to find minimum steps to convert X to Y by repeated division and multiplication ; Check if X is greater than Y then swap the elements ; Check if X equals Y ; Driver code
def solve(X, Y): """ Minimum steps to convert X to Y by repeated division and multiplication """ if (X > Y): temp = X X = Y Y = temp if (X == Y): print(0) elif (Y % X == 0): print(1) else: print(2) X = 8 Y = 13 solve(X, Y)
Count quadruplets ( A , B , C , D ) till N such that sum of square of A and B is equal to that of C and D | Python3 program for the above approach ; Function to count the quadruples ; Counter variable ; Map to store the sum of pair ( a ^ 2 + b ^ 2 ) ; Iterate till N ; Calculate a ^ 2 + b ^ 2 ; Increment the value in ma...
from collections import defaultdict def count_quadraples(N): """ Count quadruplets ( A , B , C , D ) till N such that sum of square of A and B is equal to that of C and D """ cnt = 0 m = defaultdict(int) for a in range(1, N + 1): for b in range(1, N + 1): x = a * a + b * b ...
Count of distinct index pair ( i , j ) such that element sum of First Array is greater | Python3 program of the above approach ; Function to find the number of pairs . ; Array c [ ] where c [ i ] = a [ i ] - b [ i ] ; Sort the array c ; Initialise answer as 0 ; Iterate from index 0 to n - 1 ; If c [ i ] <= 0 then in th...
from bisect import bisect_left def number_of_pairs(a, b, n): """ Count of distinct index pair ( i , j ) such that element sum of First Array is greater """ c = [0 for i in range(n)] for i in range(n): c[i] = a[i] - b[i] c = sorted(c) answer = 0 for i in range(1, n): if ...
Find K for every Array element such that at least K prefixes are â ‰¥ K | Function to find the K - value for every index in the array ; Multiset to store the array in the form of red - black tree ; Iterating over the array ; Inserting the current value in the multiset ; Condition to check if the smallest value in the s...
def print_h_index(arr, N): """ Find K for every Array element such that at least K prefixes are â ‰¥ K """ ms = [] for i in range(N): ms.append(arr[i]) ms.sort() if (ms[0] < len(ms)): ms.pop(0) print(len(ms), end=' ') if __name__ == '__main__': arr =...
Prefix Product Array | Function to generate prefix product array ; Update the array with the product of prefixes ; Print the array ; Driver Code
def prefix_product(a, n): """ Prefix Product Array """ for i in range(1, n): a[i] = a[i] * a[i - 1] for j in range(0, n): print(a[j], end=", ") return 0 arr = [2, 4, 6, 5, 10] N = len(arr) prefix_product(arr, N)
Count of ways to distribute N items among 3 people with one person receiving maximum | Function to find the number of ways to distribute N items among 3 people ; No distribution possible ; Total number of ways to distribute N items among 3 people ; Store the number of distributions which are not possible ; Count possib...
def count_ways(N): """ Count of ways to distribute N items among 3 people with one person receiving maximum """ if (N < 4): return 0 ans = ((N - 1) * (N - 2)) // 2 s = 0 for i in range(2, N - 2, 1): for j in range(1, i, 1): if (N == 2 * i + j): s +...
Sum of sum | Function to find the sum ; Calculate sum - series for every natural number and add them ; Driver code
def sum_of_sum_series(N): """ Sum of sum """ _sum = 0 for i in range(N + 1): _sum = _sum + (i * (i + 1)) // 2 return _sum N = 5 print(sum_of_sum_series(N))
Sum of sum | Function to find the sum ; Driver code
def sum_of_sum_series(n): """ Sum of sum """ return (n * (n + 1) * (n + 2)) // 6 N = 5 print(sum_of_sum_series(N))
Digitally balanced numbers | Function to check if the digits in the number is the same number of digits ; Loop to iterate over the digits of the number N ; Loop to iterate over the map ; Driver code ; Function to check
def check_same(n, b): """ Digitally balanced numbers """ m = {} while (n != 0): r = n % b n = n // b if r in m: m[r] += 1 else: m[r] = 1 last = -1 for i in m: if last != -1 and m[i] != last: return False else...
Sum of series formed by difference between product and sum of N natural numbers | Function to calculate the sum upto Nth term ; Stores the sum of the series ; Stores the product of natural numbers upto the current term ; Stores the sum of natural numbers upto the upto current term ; Generate the remaining terms and cal...
def series_sum(n): """ Sum of series formed by difference between product and sum of N natural numbers """ sum1 = 0 currProd = 1 currSum = 1 for i in range(2, n + 1): currProd *= i currSum += i sum1 += currProd - currSum return sum1 N = 5 print(series_sum(N), en...
Count of elements not divisible by any other elements of Array | Function to count the number of elements of array which are not divisible by any other element in the array arr [ ] ; Iterate over the array ; Check if the element is itself or not ; Check for divisibility ; Return the final result ; Driver Code ; Given a...
def count(a, n): """ Count of elements not divisible by any other elements of Array """ countElements = 0 for i in range(n): flag = True for j in range(n): if (i == j): continue if (a[i] % a[j] == 0): flag = False ...
Smallest N digit number divisible by N | Python3 program for the above approach ; Function to find the smallest N - digit number divisible by N ; Return the smallest N - digit number calculated using above formula ; Given N ; Function Call
import math def smallest_number(N): """ Smallest N digit number divisible by N """ return N * math.ceil(pow(10, (N - 1)) // N) N = 2 print(smallest_number(N))
Count pairs in an array containing at least one even value | Function to count the pairs in the array such as there is at least one even element in each pair ; Generate all possible pairs and increment then count if the condition is satisfied ; Driver code ; Function call
def count_pairs(arr, n): """ Count pairs in an array containing at least one even value """ count = 0 for i in range(n): for j in range(i + 1, n): if (arr[i] % 2 == 0 or arr[j] % 2 == 0): count += 1 return count arr = [8, 2, 3, 1, 4, 2] n = len(arr) print(co...
Count pairs in an array containing at least one even value | Function to count the pairs in the array such as there is at least one even element in each pair ; Store count of even and odd elements ; Check element is even or odd ; Driver Code
def count_pairs(arr, n): """ Count pairs in an array containing at least one even value """ even = 0 odd = 0 for i in range(n): if (arr[i] % 2 == 0): even += 1 else: odd += 1 return ((even * (even - 1)) // 2 + (even * odd)) arr = [8, 2, 3, 1, 4, 2] n = len(arr) prin...
Droll Numbers | Python3 program for the above approach ; Function to check droll numbers ; To store sum of even prime factors ; To store sum of odd prime factors ; Add the number of 2 s that divide n in sum_even ; N must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i ...
import math def is_droll(n): """ Droll Numbers """ if (n == 1): return False sum_even = 0 sum_odd = 0 while (n % 2 == 0): sum_even += 2 n = n // 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while (n % i == 0): sum_odd += i n = n...
Count all pairs of divisors of a number N whose sum is coprime with N | Python3 program to count all pairs of divisors such that their sum is coprime with N ; Function to count all valid pairs ; initialize count ; Check if sum of pair and n are coprime ; Return the result ; Driver code
import math as m def count_pairs(n): """ Count all pairs of divisors of a number N whose sum is coprime with N """ cnt = 0 i = 1 while i * i <= n: if (n % i == 0): div1 = i div2 = n // i sum = div1 + div2 if (m.gcd(sum, n) == 1): ...
Check if A can be converted to B by reducing with a Prime number | Function to find if it is possible to make A equal to B ; Driver Code ; Function Call
def is_possible(A, B): """ Check if A can be converted to B by reducing with a Prime number """ return (A - B > 1) A = 10 B = 4 if (is_possible(A, B)): print("Yes") else: print("No")
Program to check if N is a Centered Cubic Number | Function to check if N is a centered cubic number ; Iterating from 1 ; Infinite loop ; Finding ith_term ; Checking if the number N is a centered cube number ; If ith_term > N then N is not a centered cube number ; Incrementing i ; Driver code ; Function call
def is_centeredcube(N): """ Program to check if N is a Centered Cubic Number """ i = 1 while (True): ith_term = ((2 * i + 1) * (i * i + i + 1)) if (ith_term == N): return True if (ith_term > N): return False i += 1 N = 9 if (is_centeredcube(N...
Product of N terms of a given Geometric series | Function to calculate product of geometric series ; Initialise final product with 1 ; Multiply product with each term stored in a ; Return the final product ; Given first term and common ratio ; Number of terms ; Function Call
def product_of_gp(a, r, n): """ Product of N terms of a given Geometric series """ product = 1 for i in range(0, n): product = product * a a = a * r return product a = 1 r = 2 N = 4 print(product_of_gp(a, r, N))
Find two numbers whose difference of fourth power is equal to N | Python3 implementation to find the values of x and y for the given equation with integer N ; Function which find required x & y ; Upper limit of x & y , if such x & y exists ; num1 stores x ^ 4 ; num2 stores y ^ 4 ; If condition is satisfied the print an...
from math import pow, ceil def solve(n): """ Find two numbers whose difference of fourth power is equal to N """ upper_limit = ceil(pow(n, 1.0 / 4)) for x in range(upper_limit + 1): for y in range(upper_limit + 1): num1 = x * x * x * x num2 = y * y * y * y ...
Check if count of even divisors of N is equal to count of odd divisors | Python3 program for the above approach ; Function to check if count of even and odd divisors are equal ; To store the count of even factors and odd factors ; Loop till [ 1 , sqrt ( N ) ] ; If divisors are equal add only one ; Check for even diviso...
import math def divisors_same(n): """ Check if count of even divisors of N is equal to count of odd divisors """ even_div = 0 odd_div = 0 for i in range(1, int(math.sqrt(n))): if (n % i == 0): if (n // i == i): if (i % 2 == 0): even_div +...
Count of integers up to N which represent a Binary number | Python3 program to count the number of integers upto N which are of the form of binary representations ; Function to return the count ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set ...
from math import * def count_binaries(N): """ Count of integers up to N which represent a Binary number """ ctr = 1 ans = 0 while (N > 0): if (N % 10 == 1): ans += pow(2, ctr - 1) elif (N % 10 > 1): ans = pow(2, ctr) - 1 ctr += 1 N //= 10...
Count of integers up to N which represent a Binary number | Function to return the count ; PreCompute and store the powers of 2 ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set answer as 2 ^ ctr - 1 as all possible binary integers with ctr num...
def count_binaries(N): """ Count of integers up to N which represent a Binary number """ powersOfTwo = [0] * 11 powersOfTwo[0] = 1 for i in range(1, 11): powersOfTwo[i] = powersOfTwo[i - 1] * 2 ctr = 1 ans = 0 while (N > 0): if (N % 10 == 1): ans += powers...
Program to check if N is a Octagonal Number | Python3 program for the above approach ; Function to check if N is a octagonal number ; Condition to check if the number is a octagonal number ; Driver Code ; Given number ; Function call
from math import sqrt def isoctagonal(N): """ Program to check if N is a Octagonal Number """ n = (2 + sqrt(12 * N + 4)) / 6 return (n - int(n)) == 0 if __name__ == "__main__": N = 8 if (isoctagonal(N)): print("Yes") else: print("No")
Program to check if N is a Pentadecagonal Number | Python3 program for the above approach ; Function to check if N is a pentadecagon number ; Condition to check if the number is a pentadecagon number ; Driver Code ; Given number ; Function call
from math import sqrt def is_pentadecagon(N): """ Program to check if N is a Pentadecagonal Number """ n = (11 + sqrt(104 * N + 121)) / 26 return (n - int(n) == 0) if __name__ == "__main__": N = 15 if (is_pentadecagon(N)): print("Yes") else: print("No")
Program to check if N is a Tetradecagonal Number | Python3 program for the above approach ; Function to check if N is a Tetradecagonal Number ; Condition to check if the number is a tetradecagonal number ; Given Number ; Function call
import math def istetradecagonal(N): """ Program to check if N is a Tetradecagonal Number """ n = (10 + math.sqrt(96 * N + 100)) / 24 if (n - int(n)) == 0: return True return False N = 11 if (istetradecagonal(N)): print("Yes") else: print("No")
Program to check if N is a Concentric Hexagonal Number | Python3 program to check if N is a concentric hexagonal number ; Function to check if the number is a concentric hexagonal number ; Condition to check if the number is a concentric hexagonal number ; Driver code ; Function call
import math def is_concentrichexagonal(N): """ Program to check if N is a Concentric Hexagonal Number """ n = math.sqrt((2 * N) / 3) return (n - int(n)) == 0 N = 6 if is_concentrichexagonal(N): print("Yes") else: print("No")
Count of ways to write N as a sum of three numbers | Function to find the number of ways ; Check if number is less than 2 ; Calculate the sum ; Driver code
def count_ways(N): """ Count of ways to write N as a sum of three numbers """ if (N <= 2): print("-1") else: ans = (N - 1) * (N - 2) / 2 print(ans) if __name__ == '__main__': N = 5 count_ways(N)
Logarithm tricks for Competitive Programming | Python3 implementation to check that a integer is a power of two ; Function to check if the number is a power of two ; Driver code
import math def is_power_of_two(n): """ Logarithm tricks for Competitive Programming """ return ( math.ceil( math.log(n) // math.log(2)) == math.floor( math.log(n) // math.log(2))) if __name__ == '__main__': N = 8 if is_power_of_two(N):...
Count of pairs having bit size at most X and Bitwise OR equal to X | Function to count the pairs ; Initializing answer with 1 ; Iterating through bits of x ; Check if bit is 1 ; Multiplying ans by 3 if bit is 1 ; Driver code
def count_pairs(x): """ Count of pairs having bit size at most X and Bitwise OR equal to X """ ans = 1 while (x > 0): if (x % 2 == 1): ans = ans * 3 x = x // 2 return ans if __name__ == '__main__': X = 6 print(count_pairs(X))
Find the Kth number which is not divisible by N | Python3 implementation for above approach ; Function to find the Kth not divisible by N ; Lowest possible value ; Highest possible value ; To store the Kth non divisible number of N ; Using binary search ; Calculating mid value ; Sol would have the value by subtracting ...
import sys def kth_non_divisible(N, K): """ Find the Kth number which is not divisible by N """ L = 1 H = sys .maxsize ans = 0 while (L <= H): mid = (L + H) // 2 sol = mid - mid // N if (sol > K): H = mid - 1 elif (sol < K): L = mid + 1 ...
Print any pair of integers with sum of GCD and LCM equals to N | Function to print the required pair ; Print the pair ; Driver code
def print_pair(n): """ Print any pair of integers with sum of GCD and LCM equals to N """ print("1", end=" ") print(n - 1) n = 14 print_pair(n)
Split N natural numbers into two sets having GCD of their sums greater than 1 | Function to create and print the two sets ; No such split possible for N <= 2 ; Print the first set consisting of even elements ; Print the second set consisting of odd ones ; Driver Code
def create_sets(N): """ Split N natural numbers into two sets having GCD of their sums greater than 1 """ if (N <= 2): print("-1") return for i in range(2, N + 1, 2): print(i, end=" ") print("") for i in range(1, N + 1, 2): print(i, end=" ") if __name__ == '...
Number of ways to color boundary of each block of M * N table | Function to compute all way to fill the boundary of all sides of the unit square ; Count possible ways to fill all upper and left side of the rectangle M * N ; Count possible ways to fill all side of the all squares unit size ; Number of rows ; Number of c...
def count_ways(N, M): """ Number of ways to color boundary of each block of M * N table """ count = 1 count = pow(3, M + N) count *= pow(2, M * N) return count N = 3 M = 2 print(count_ways(N, M))
Nth positive number whose absolute difference of adjacent digits is at most 1 | Return Nth number with absolute difference between all adjacent digits at most 1. ; To store all such numbers ; Enqueue all integers from 1 to 9 in increasing order . ; Perform the operation N times so that we can get all such N numbers . ;...
def find_nth_number(N): """ Nth positive number whose absolute difference of adjacent digits is at most 1 """ arr = [0 for i in range(N + 1)] q = [] for i in range(1, 10, 1): q.append(i) for i in range(1, N + 1, 1): arr[i] = q[0] q.remove(q[0]) if (arr[i] % 10...
Unique element in an array where all elements occur K times except one | Set 2 | Function that find the unique element in the array arr [ ] ; Store all unique element in set ; Sum of all element of the array ; Sum of element in the set ; Print the unique element using formula ; Driver Code ; Function call
def find_unique_elements(arr, N, K): """ Unique element in an array where all elements occur K times except one """ s = set() for x in arr: s.add(x) arr_sum = sum(arr) set_sum = 0 for x in s: set_sum += x print((K * set_sum - arr_sum) // (K - 1)) if __name__ == '__m...
Form the Cubic equation from the given roots | Function to find the cubic equation whose roots are a , b and c ; Find the value of coefficient ; Print the equation as per the above coefficients ; Driver Code ; Function Call
def find_equation(a, b, c): """ Form the Cubic equation from the given roots """ X = (a + b + c) Y = (a * b) + (b * c) + (c * a) Z = (a * b * c) print("x^3 - ", X, "x^2 + ", Y, "x - ", Z, " = 0") if __name__ == '__main__': a = 5 b = 2 c = 3 find_equation(a, b, c)
Program to print numbers from N to 1 in reverse order | Recursive function to print from N to 1 ; Driver code
def print_reverse_order(N): """ Program to print numbers from N to 1 in reverse order """ for i in range(N, 0, -1): print(i, end=" ") if __name__ == '__main__': N = 5 print_reverse_order(N)
Minimum decrements to make integer A divisible by integer B | Function that print number of moves required ; Calculate modulo ; Print the required answer ; Driver Code ; Initialise A and B
def moves_required(a, b): """ Minimum decrements to make integer A divisible by integer B """ total_moves = a % b print(total_moves) if __name__ == '__main__': A = 10 B = 3 moves_required(A, B)
Pythagorean Triplet with given sum using single loop | Function to calculate the Pythagorean triplet in O ( n ) ; Iterate a from 1 to N - 1. ; Calculate value of b ; The value of c = n - a - b ; Driver code ; Function call
def pythagorean_triplet(n): """ Pythagorean Triplet with given sum using single loop """ flag = 0 for a in range(1, n, 1): b = (n * n - 2 * n * a) // (2 * n - 2 * a) c = n - a - b if (a * a + b * b == c * c and b > 0 and c > 0): print(a, b, c) flag = 1...
Check if there exists a number with X factors out of which exactly K are prime | Python3 program to check if there exists a number with X factors out of which exactly K are prime ; Function to check if such number exists ; To store the sum of powers of prime factors of X which determines the maximum count of numbers wh...
from math import sqrt def check(X, K): """ Check if there exists a number with X factors out of which exactly K are prime """ prime = 0 temp = X sqr = int(sqrt(X)) for i in range(2, sqr + 1, 1): while (temp % i == 0): temp = temp // i prime += 1 if (temp...
Number of subsets with same AND , OR and XOR values in an Array | Python3 implementation to find the number of subsets with equal bitwise AND , OR and XOR values ; Function to find the number of subsets with equal bitwise AND , OR and XOR values ; Traverse through all the subsets ; Finding the subsets with the bits of ...
mod = 1000000007 def count_subsets(a, n): """ Number of subsets with same AND , OR and XOR values in an Array """ answer = 0 for i in range(1 << n): bitwiseAND = -1 bitwiseOR = 0 bitwiseXOR = 0 for j in range(n): if (i & (1 << j)): if (bi...
Count of Subsets containing only the given value K | Function to find the number of subsets formed by the given value K ; Count is used to maintain the number of continuous K 's ; Iterating through the array ; If the element in the array is equal to K ; count * ( count + 1 ) / 2 is the total number of subsets with only...
def count(arr, N, K): """ Count of Subsets containing only the given value K """ count = 0 ans = 0 for i in range(N): if (arr[i] == K): count = count + 1 else: ans += (count * (count + 1)) // 2 count = 0 ans = ans + (count * (count + 1)) //...
Largest number less than or equal to Z that leaves a remainder X when divided by Y | Function to get the number ; remainder can ' t ▁ be ▁ larger ▁ ▁ than ▁ the ▁ largest ▁ number , ▁ ▁ if ▁ so ▁ then ▁ answer ▁ doesn ' t exist . ; reduce number by x ; finding the possible number that is divisible by y ; this number is...
def get(x, y, z): """ Largest number less than or equal to Z that leaves a remainder X when divided by Y """ if (x > z): return -1 val = z - x div = (z - x) // y ans = div * y + x return ans x = 1 y = 5 z = 8 print(get(x, y, z))
Count of greater elements for each element in the Array | Python 3 implementation of the above approach ; Store the frequency of the array elements ; Store the sum of frequency of elements greater than the current element ; Driver code
def count_of_greater_elements(arr, n): """ Count of greater elements for each element in the Array """ mp = {i: 0 for i in range(1000)} for i in range(n): mp[arr[i]] += 1 x = 0 p = [] q = [] m = [] for key, value in mp.items(): m.append([key, value]) m = m[::-...
Minimum operations required to make two numbers equal | Python program to find minimum operations required to make two numbers equal ; Function to return the minimum operations required ; Keeping B always greater ; Reduce B such that gcd ( A , B ) becomes 1. ; Driver code
import math def min_operations(A, B): """ Minimum operations required to make two numbers equal """ if (A > B): swap(A, B) B = B // math.gcd(A, B) return B - 1 A = 7 B = 15 print(min_operations(A, B))
Product of all Subarrays of an Array | Function to find product of all subarrays ; Variable to store the product ; Compute the product while traversing for subarrays ; Printing product of all subarray ; Driver code ; Function call
def product_subarrays(arr, n): """ Product of all Subarrays of an Array """ product = 1 for i in range(0, n): for j in range(i, n): for k in range(i, j + 1): product *= arr[k] print(product, "") arr = [10, 3, 7] n = len(arr) product_subarrays(arr, n)
Find K distinct positive odd integers with sum N | Function to find K odd positive integers such that their summ is N ; Condition to check if there are enough values to check ; Driver Code
def find_distinct_oddsumm(n, k): """ Find K distinct positive odd integers with sum N """ if ((k * k) <= n and (n + k) % 2 == 0): val = 1 summ = 0 for i in range(1, k): print(val, end=" ") summ += val val += 2 print(n - summ) else: ...
Minimum number of operations to convert array A to array B by adding an integer into a subarray | Function to find the minimum number of operations in which array A can be converted to array B ; Loop to iterate over the array ; if both elements are equal then move to next element ; Calculate the difference between two ...
def check_array(a, b, n): """ Minimum number of operations to convert array A to array B by adding an integer into a subarray """ operations = 0 i = 0 while (i < n): if (a[i] - b[i] == 0): i += 1 continue diff = a[i] - b[i] i += 1 while (i ...
Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3 | Python3 implementation to find the number the number of ways to reach Nth stair by taking 1 or 2 steps at a time and 3 rd Step exactly once ; Function to find the number of ways ; Base Case ; Count of 2 - steps ; Count of 1 - steps ; In...
import math def ways(n): """ Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3 """ if n < 3: return 0 c2 = 0 c1 = n - 3 l = c1 + 1 s = 0 exp_c2 = c1 / 2 while exp_c2 >= c2: f1 = math.factorial(l) f2 = math.factorial(c1) ...
Find N from the value of N ! | Map to precompute and store the factorials of the numbers ; Function to precompute factorial ; Calculating the factorial for each i and storing in a map ; Driver code ; Precomputing the factorials
m = {} def precompute(): """ Find N from the value of N ! """ fact = 1 for i in range(1, 19): fact = fact * i m[fact] = i if __name__ == "__main__": precompute() K = 120 print(m[K]) K = 6 print(m[K])
Length of Smallest subarray in range 1 to N with sum greater than a given value | Function to return the count of minimum elements such that the sum of those elements is > S . ; Initialize currentSum = 0 ; Loop from N to 1 to add the numbers and check the condition . ; Driver code
def count_number(N, S): """ Length of Smallest subarray in range 1 to N with sum greater than a given value """ countElements = 0 currSum = 0 while (currSum <= S): currSum += N N = N - 1 countElements = countElements + 1 return countElements N = 5 S = 11 count = cou...
Find Number of Even cells in a Zero Matrix after Q queries | Function to find the number of even cell in a 2D matrix ; Maintain two arrays , one for rows operation and one for column operation ; Increment operation on row [ i ] ; Increment operation on col [ i ] ; Count odd and even values in both arrays and multiply t...
def find_number_of_even_cells(n, q, size): """ Find Number of Even cells in a Zero Matrix after Q queries """ row = [0] * n col = [0] * n for i in range(size): x = q[i][0] y = q[i][1] row[x - 1] += 1 col[y - 1] += 1 r1 = 0 r2 = 0 c1 = 0 c2 = 0 ...
Find maximum unreachable height using two ladders | Function to return the maximum height which can 't be reached ; Driver code
def max_height(h1, h2): """ Find maximum unreachable height using two ladders """ return ((h1 * h2) - h1 - h2) h1 = 7 h2 = 5 print(max(0, max_height(h1, h2)))
Fermat 's Factorization Method | Python 3 implementation of fermat 's factorization ; This function finds the value of a and b and returns a + b and a - b ; since fermat 's factorization applicable for odd positive integers only ; check if n is a even number ; if n is a perfect root , then both its square roots are it...
from math import ceil, sqrt def fermat_factors(n): """ Fermat 's Factorization Method """ if (n <= 0): return [n] if (n & 1) == 0: return [n / 2, 2] a = ceil(sqrt(n)) if (a * a == n): return [a, a] while (True): b1 = a * a - n b = int(sqrt(b1)) ...
Append two elements to make the array satisfy the given condition | Function to find the required numbers ; Find the sum and xor ; Print the required elements ; Driver code
def find_nums(arr, n): """ Append two elements to make the array satisfy the given condition """ S = 0 X = 0 for i in range(n): S += arr[i] X ^= arr[i] print(X, X + S) if __name__ == "__main__": arr = [1, 7] n = len(arr) find_nums(arr, n)
Satisfy the parabola when point ( A , B ) and the equation is given | Function to find the required values ; Driver code
def solve(A, B): """ Satisfy the parabola when point ( A , B ) and the equation is given """ p = B / 2 M = int(4 * p) N = 1 O = -2 * A Q = int(A * A + 4 * p * p) return [M, N, O, Q] a = 1 b = 1 print(*solve(a, b))
Largest number dividing maximum number of elements in the array | Python3 implementation of the approach ; Function to return the largest number that divides the maximum elements from the given array ; Finding gcd of all the numbers in the array ; Driver code
from math import gcd as __gcd def find_largest(arr, n): """ Largest number dividing maximum number of elements in the array """ gcd = 0 for i in range(n): gcd = __gcd(arr[i], gcd) return gcd if __name__ == '__main__': arr = [3, 6, 9] n = len(arr) print(find_largest(arr, n...
Find the value of N XOR 'ed to itself K times | Function to return n ^ n ^ ... k times ; If k is odd the answer is the number itself ; Else the answer is 0 ; Driver code
def xor_k(n, k): """ Find the value of N XOR 'ed to itself K times """ if (k % 2 == 1): return n return 0 n = 123 k = 3 print(xor_k(n, k))
Find the Nth digit in the proper fraction of two numbers | Function to print the Nth digit in the fraction ( p / q ) ; While N > 0 compute the Nth digit by dividing p and q and store the result into variable res and go to next digit ; Driver code
def find_nth_digit(p, q, N): """ Find the Nth digit in the proper fraction of two numbers """ while (N > 0): N -= 1 p *= 10 res = p // q p %= q return res if __name__ == "__main__": p = 1 q = 2 N = 1 print(find_nth_digit(p, q, N))
Find closest integer with the same weight | Python3 implementation of the approach ; Function to return the number closest to x which has equal number of set bits as x ; Loop for each bit in x and compare with the next bit ; Driver code
NumUnsignBits = 64 def find_num(x): """ Find closest integer with the same weight """ for i in range(NumUnsignBits - 1): if (((x >> i) & 1) != ((x >> (i + 1)) & 1)): x ^= (1 << i) | (1 << (i + 1)) return x if __name__ == "__main__": n = 92 print(find_num(n))
Find the number of squares inside the given square grid | Function to return the number of squares inside an n * n grid ; Driver code
def cnt_squares(n): """ Find the number of squares inside the given square grid """ return int(n * (n + 1) * (2 * n + 1) / 6) if __name__ == "__main__": print(cnt_squares(4))
Minimum number of moves to reach N starting from ( 1 , 1 ) | Python3 implementation of the approach ; Function to return the minimum number of moves required to reach the cell containing N starting from ( 1 , 1 ) ; To store the required answer ; For all possible values of divisors ; If i is a divisor of n ; Get the mov...
import sys from math import sqrt def min_moves(n): """ Minimum number of moves to reach N starting from ( 1 , 1 ) """ ans = sys .maxsize for i in range(1, int(sqrt(n)) + 1): if (n % i == 0): ans = min(ans, i + n // i - 2) return ans if __name__ == "__main__": n = 10 ...
Minimum possible value of ( i * j ) % 2019 | Python3 implementation of the approach ; Function to return the minimum possible value of ( i * j ) % 2019 ; If we can get a number divisible by 2019 ; Find the minimum value by running nested loops ; Driver code
MOD = 2019 def min_modulo(l, r): """ Minimum possible value of ( i * j ) % 2019 """ if (r - l >= MOD): return 0 else: ans = MOD - 1 for i in range(l, r + 1): for j in range(i + 1, r + 1): ans = min(ans, (i * j) % MOD) return ans if __na...
Represent ( 2 / N ) as the sum of three distinct positive integers of the form ( 1 / m ) | Function to find the required fractions ; Base condition ; For N > 1 ; Driver code
def find_numbers(N): """ Represent ( 2 / N ) as the sum of three distinct positive integers of the form ( 1 / m ) """ if (N == 1): print(-1, end="") else: print(N, N + 1, N * (N + 1)) if __name__ == "__main__": N = 5 find_numbers(N)
Count the pairs in an array such that the difference between them and their indices is equal | Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt -...
def count_pairs(arr, n): """ Count the pairs in an array such that the difference between them and their indices is equal """ map = dict() for i in range(n): map[arr[i] - i] = map.get(arr[i] - i, 0) + 1 res = 0 for x in map: cnt = map[x] res += ((cnt * (cnt - 1)) // 2...
Minimum possible number with the given operation | Function to return the minimum possible integer that can be obtained from the given integer after performing the given operations ; For every digit ; Digits less than 5 need not to be changed as changing them will lead to a larger number ; The resulting integer cannot ...
def min_int(str1): """ Minimum possible number with the given operation """ for i in range(len(str1)): if (str1[i] >= 5): str1[i] = (9 - str1[i]) if (str1[0] == 0): str1[0] = 9 temp = "" for i in str1: temp += str(i) return temp str1 = "589" str1 = [...
Reduce N to 1 with minimum number of given operations | Function to return the minimum number of given operations required to reduce n to 1 ; To store the count of operations ; To store the digit ; If n is already then no operation is required ; Extract all the digits except the first digit ; Store the maximum of that ...
def min_operations(n): """ Reduce N to 1 with minimum number of given operations """ count = 0 d = 0 if (n == 1): return 0 while (n > 9): d = max(n % 10, d) n //= 10 count += 10 d = max(d, n - 1) count += abs(d) return count - 1 if __name__ == '_...
Find the largest number that can be formed by changing at most K digits | Function to return the maximum number that can be formed by changing at most k digits in str ; For every digit of the number ; If no more digits can be replaced ; If current digit is not already 9 ; Replace it with 9 ; One digit has been used ; D...
def find_maximum_num(st, n, k): """ Find the largest number that can be formed by changing at most K digits """ for i in range(n): if (k < 1): break if (st[i] != '9'): st = st[0:i] + '9' + st[i + 1:] k -= 1 return st st = "569431" n = len(st) k =...
Check if two Integer are anagrams of each other | Function that returns true if a and b are anagarams of each other ; Converting numbers to strings ; Checking if the sorting values of two strings are equal ; Driver code
def are_anagrams(a, b): """ Check if two Integer are anagrams of each other """ a = str(a) b = str(b) if (sorted(a) == sorted(b)): return True else: return False a = 240 b = 204 if (are_anagrams(a, b)): print("Yes") else: print("No")
Number of occurrences of a given angle formed using 3 vertices of a n | Function that calculates occurrences of given angle that can be created using any 3 sides ; Maximum angle in a regular n - gon is equal to the interior angle If the given angle is greater than the interior angle then the given angle cannot be creat...
def solve(ang, n): """ Number of occurrences of a given angle formed using 3 vertices of a n """ if ((ang * n) > (180 * (n - 2))): return 0 elif ((ang * n) % 180 != 0): return 0 ans = 1 freq = (ang * n) // 180 ans = ans * (n - 1 - freq) ans = ans * n return ans ...
Compute the maximum power with a given condition | Function to return the largest power ; If n is greater than given M ; If n == m ; Checking for the next power ; Driver 's code
def calculate(n, k, m, power): """ Compute the maximum power with a given condition """ if n > m: if power == 0: return 0 else: return power - 1 elif n == m: return power else: return calculate(n * k, k, m, power + 1) if __name__ == "__ma...
Program to find the number from given holes | Function that will find out the number ; If number of holes equal 0 then return 1 ; If number of holes equal 0 then return 0 ; If number of holes is more than 0 or 1. ; If number of holes is odd ; Driver code ; Calling Function
def print_number(holes): """ Program to find the number from given holes """ if (holes == 0): print("1") elif (holes == 1): print("0", end="") else: rem = 0 quo = 0 rem = holes % 2 quo = holes // 2 if (rem == 1): print("4", end=...
Minimum cost to make all array elements equal | Function to return the minimum cost to make each array element equal ; To store the count of even numbers present in the array ; To store the count of odd numbers present in the array ; Iterate through the array and find the count of even numbers and odd numbers ; Driver ...
def min_cost(arr, n): """ Minimum cost to make all array elements equal """ count_even = 0 count_odd = 0 for i in range(n): if (arr[i] % 2 == 0): count_even += 1 else: count_odd += 1 return min(count_even, count_odd) arr = [2, 4, 3, 1, 5] n = len(arr...
Probability that a N digit number is palindrome | Find the probability that a n digit number is palindrome ; Denominator ; Assign 10 ^ ( floor ( n / 2 ) ) to denominator ; Display the answer ; Driver code
def solve(n): """ Probability that a N digit number is palindrome """ n_2 = n // 2 den = "1" while (n_2): den += '0' n_2 -= 1 print(str(1) + "/" + str(den)) if __name__ == "__main__": N = 5 solve(N)
Ways to choose balls such that at least one ball is chosen | Python3 implementation of the approach ; Function to return the count of ways to choose the balls ; Return ( ( 2 ^ n ) - 1 ) % MOD ; Driver code
MOD = 1000000007 def count_ways(n): """ Ways to choose balls such that at least one ball is chosen """ return (((2 ** n) - 1) % MOD) n = 3 print(count_ways(n))
Minimize the sum of the array according the given condition | Function to return the minimum sum ; sort the array to find the minimum element ; finding the number to divide ; Checking to what instance the sum has decreased ; getting the max difference ; Driver Code
def find_min(arr, n): """ Minimize the sum of the array according the given condition """ sum = 0 for i in range(0, n): sum = sum + arr[i] arr.sort() min = arr[0] max = 0 for i in range(n - 1, 0, -1): num = arr[i] total = num + min for j in range(2, nu...
Number of possible permutations when absolute difference between number of elements to the right and left are given | Function to find the number of permutations possible of the original array to satisfy the given absolute differences ; To store the count of each a [ i ] in a map ; if n is odd ; check the count of each...
def totalways(arr, n): """ Number of possible permutations when absolute difference between number of elements to the right and left are given """ cnt = dict() for i in range(n): cnt[arr[i]] = cnt.get(arr[i], 0) + 1 if (n % 2 == 1): start, endd = 0, n - 1 for i in range(s...
End of preview. Expand in Data Studio

Dataset Card for "xlcost_clean"

Python functions extracted from the xlcost benchmark and cleaned.

Downloads last month
7