text stringlengths 39 1.18k | code stringlengths 113 2.19k | quality_prob float64 0.5 0.86 | learning_prob float64 0.17 0.98 |
|---|---|---|---|
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))
| 0.562417 | 0.37668 |
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 * ... | 0.517083 | 0.572245 |
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__ ==... | 0.538255 | 0.435661 |
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
... | 0.613005 | 0.444263 |
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)
| 0.514644 | 0.436682 |
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,... | 0.639511 | 0.597843 |
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 =... | 0.592077 | 0.452234 |
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
... | 0.68658 | 0.371108 |
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 ... | 0.614278 | 0.466359 |
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))
| 0.592431 | 0.742352 |
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
... | 0.709422 | 0.428532 |
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... | 0.676192 | 0.330647 |
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... | 0.546496 | 0.602442 |
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")
| 0.703142 | 0.31703 |
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")
| 0.628179 | 0.204461 |
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))
| 0.559771 | 0.548492 |
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))
| 0.635449 | 0.679794 |
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)
| 0.610802 | 0.466177 |
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)
| 0.692538 | 0.33353 |
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... | 0.556641 | 0.356503 |
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))
| 0.501953 | 0.551272 |
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 ... | 0.555676 | 0.546678 |
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
... | 0.516352 | 0.491944 |
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)))
| 0.590189 | 0.41253 |
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))
... | 0.563858 | 0.372876 |
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))
| 0.587233 | 0.794345 |
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... | 0.593138 | 0.237808 |
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))
| 0.619011 | 0.460713 |
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))
| 0.667473 | 0.424531 |
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)
| 0.522689 | 0.429788 |
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__ == '_... | 0.58818 | 0.406332 |
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 =... | 0.557123 | 0.347205 |
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
... | 0.681727 | 0.792745 |
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... | 0.665628 | 0.506164 |
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)
| 0.552057 | 0.388618 |
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))
| 0.549399 | 0.458773 |
Find the sum of elements of the Matrix generated by the given rules | Function to return the required ssum ; To store the ssum ; For every row ; Update the ssum as A appears i number of times in the current row ; Update A for the next row ; Return the ssum ; Driver code | def sum(A, B, R):
"""
Find the sum of elements of the Matrix generated by the given rules
"""
ssum = 0
for i in range(1, R + 1):
ssum = ssum + (i * A)
A = A + B
return ssum
A, B, R = 5, 3, 3
print(sum(A, B, R))
| 0.53777 | 0.861887 |
Find the height of a right | Function to return the height of the right - angled triangle whose area is X times its base ; Driver code | def get_height(X):
"""
Find the height of a right
"""
return (2 * X)
if __name__ == '__main__':
X = 35
print(get_height(X))
| 0.61173 | 0.389779 |
Find sum of inverse of the divisors when sum of divisors and the number is given | Function to return the sum of inverse of divisors ; Calculating the answer ; Return the answer ; Driver code ; Function call | def sumof_inverse_divisors(N, Sum):
"""
Find sum of inverse of the divisors when sum of divisors and the number is given
"""
ans = float(Sum) * 1.0 / float(N)
return round(ans, 2)
N = 9
Sum = 13
print sumof_inverse_divisors(N, Sum)
| 0.693577 | 0.977926 |
Number of triplets such that each value is less than N and each pair sum is a multiple of K | Function to return the number of triplets ; Initializing the count array ; Storing the frequency of each modulo class ; If K is odd ; If K is even ; Driver Code ; Function Call | def noof_triplets(N, K):
"""
Number of triplets such that each value is less than N and each pair sum is a multiple of K
"""
cnt = [0] * K
for i in range(1, N + 1):
cnt[i % K] += 1
if (K & 1):
rslt = cnt[0] * cnt[0] * cnt[0]
return rslt
else:
rslt = (cnt[0] * ... | 0.554229 | 0.477311 |
Find a number containing N | Function to compute number using our deduced formula ; Initialize num to n - 1 ; Driver code | def find_number(n):
"""
Find a number containing N
"""
num = n - 1
num = 2 * (4 ** num)
num = num // 3
return num
if __name__ == "__main__":
n = 5
print(find_number(n))
| 0.562177 | 0.463141 |
Maximum value of | arr [ 0 ] | Function to return the maximum required value ; Driver code | def max_value(n):
"""
Maximum value of
"""
if (n == 1):
return 0
return ((n * n // 2) - 1)
n = 4
print(max_value(n))
| 0.562177 | 0.460107 |
Find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . | Function to find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . ; Driver code | def numbers(n):
"""
Find the count of numbers that can be formed using digits 3 , 4 only and having length at max N .
"""
return pow(2, n + 1) - 2
n = 2
print(numbers(n))
| 0.506591 | 0.88696 |
Ways to place 4 items in n ^ 2 positions such that no row / column contains more than one | Function to return the number of ways to place 4 items in n ^ 2 positions ; Driver code | def numbersof_ways(n):
"""
Ways to place 4 items in n ^ 2 positions such that no row / column contains more than one
"""
x = (n * (n - 1) * (n - 2) * (n - 3)) // (4 * 3 * 2 * 1)
y = n * (n - 1) * (n - 2) * (n - 3)
return x * y
n = 4
print(numbersof_ways(n))
| 0.507324 | 0.565659 |
Minimum matches the team needs to win to qualify | Function to return the minimum number of matches to win to qualify for next round ; Do a binary search to find ; Find mid element ; Check for condition to qualify for next round ; Driver Code | def find_minimum(x, y):
"""
Minimum matches the team needs to win to qualify
"""
low = 0
high = y
while (low <= high):
mid = (low + high) >> 1
if ((mid * 2 + (y - mid)) >= x):
high = mid - 1
else:
low = mid + 1
return low
if __name__ == '__ma... | 0.561696 | 0.440409 |
Minimum possible sum of array elements after performing the given operation | Function to return the minimized sum ; To store the largest element from the array which is divisible by x ; Sum of array elements before performing any operation ; If current element is divisible by x and it is maximum so far ; Update the mi... | def min_sum(arr, n, x):
"""
Minimum possible sum of array elements after performing the given operation
"""
Sum = 0
largestDivisible, minimum = -1, arr[0]
for i in range(0, n):
Sum += arr[i]
if (arr[i] % x == 0 and largestDivisible < arr[i]):
largestDivisible = arr[i]... | 0.556882 | 0.515803 |
Maximum Bitwise AND pair from given range | Function to return the maximum bitwise AND possible among all the possible pairs ; If there is only a single value in the range [ L , R ] ; If there are only two values in the range [ L , R ] ; Driver code | def max_and(L, R):
"""
Maximum Bitwise AND pair from given range
"""
if (L == R):
return L
elif ((R - L) == 1):
return (R & L)
else:
if (((R - 1) & R) > ((R - 2) & (R - 1))):
return ((R - 1) & R)
else:
return ((R - 2) & (R - 1))
L = 1
R =... | 0.501221 | 0.491944 |
Maximum positive integer divisible by C and is in the range [ A , B ] | Function to return the required number ; If b % c = 0 then b is the required number ; Else get the maximum multiple of c smaller than b ; Driver code | def get_max_num(a, b, c):
"""
Maximum positive integer divisible by C and is in the range [ A , B ]
"""
if (b % c == 0):
return b
x = ((b // c) * c)
if (x >= a and x <= b):
return x
else:
return -1
a, b, c = 2, 10, 3
print(get_max_num(a, b, c))
| 0.52074 | 0.399519 |
Count the total number of squares that can be visited by Bishop in one move | Function to return the count of total positions the Bishop can visit in a single move ; Count top left squares ; Count bottom right squares ; Count top right squares ; Count bottom left squares ; Return total count ; Bishop 's Position | def count_squares(row, column):
"""
Count the total number of squares that can be visited by Bishop in one move
"""
topLeft = min(row, column) - 1
bottomRight = 8 - max(row, column)
topRight = min(row, 9 - column) - 1
bottomLeft = 8 - max(row, 9 - column)
return (topLeft + topRight + bot... | 0.605099 | 0.537406 |
Maximize the value of x + y + z such that ax + by + cz = n | Python3 implementation of the approach ; Function to return the maximum value of ( x + y + z ) such that ( ax + by + cz = n ) ; i represents possible values of a * x ; j represents possible values of b * y ; If z is an integer ; Driver code ; Function Call | from math import *
def max_result(n, a, b, c):
"""
Maximize the value of x + y + z such that ax + by + cz = n
"""
maxVal = 0
for i in range(0, n + 1, a):
for j in range(0, n - i + 1, b):
z = (n - (i + j)) / c
if (floor(z) == ceil(z)):
x = i // a
... | 0.555435 | 0.313052 |
Make all numbers of an array equal | Function that returns true if all the array elements can be made equal with the given operation ; Divide number by 2 ; Divide number by 3 ; Driver code | def equal_numbers(a, n):
"""
Make all numbers of an array equal
"""
for i in range(0, n):
while a[i] % 2 == 0:
a[i] //= 2
while a[i] % 3 == 0:
a[i] //= 3
if a[i] != a[0]:
return False
return True
if __name__ == "__main__":
a = [50, 75... | 0.500244 | 0.387314 |
Program to find sum of harmonic series | Python program to find sum of harmonic series using recursion ; Base condition ; Driven Code | def sum(n):
"""
Program to find sum of harmonic series
"""
if n < 2:
return 1
else:
return 1 / n + (sum(n - 1))
print(sum(8))
print(sum(10))
| 0.504394 | 0.532304 |
Minimum absolute difference between N and a power of 2 | Python3 implementation of the above approach ; Function to return the minimum difference between N and a power of 2 ; Power of 2 closest to n on its left ; Power of 2 closest to n on its right ; Return the minimum abs difference ; Driver code | import math
def min_abs_diff(n):
"""
Minimum absolute difference between N and a power of 2
"""
left = 1 << (int)(math.floor(math.log2(n)))
right = left * 2
return min((n - left), (right - n))
if __name__ == "__main__":
n = 15
print(min_abs_diff(n))
| 0.588061 | 0.44059 |
Find probability that a player wins when probabilities of hitting the target are given | Function to return the probability of the winner ; Driver Code ; Will print 9 digits after the decimal point | def find_probability(p, q, r, s):
"""
Find probability that a player wins when probabilities of hitting the target are given
"""
t = (1 - p / q) * (1 - r / s)
ans = (p / q) / (1 - t)
return round(ans, 9)
if __name__ == "__main__":
p, q, r, s = 1, 2, 1, 2
print(find_probability(p, q, r,... | 0.693473 | 0.567757 |
Sum of first N natural numbers which are divisible by X or Y | Python 3 program to find sum of numbers from 1 to N which are divisible by X or Y ; Function to calculate the sum of numbers divisible by X or Y ; Driver code | from math import ceil, floor
def sum(N, X, Y):
"""
Sum of first N natural numbers which are divisible by X or Y
"""
S1 = floor(floor(N / X) * floor(2 * X + floor(N / X - 1) * X) / 2)
S2 = floor(floor(N / Y)) * floor(2 * Y + floor(N / Y - 1) * Y) / 2
S3 = floor(floor(N / (X * Y))) * floor(2 * (... | 0.754282 | 0.355607 |
Count ordered pairs with product less than N | Python3 implementation of above approach ; Function to return count of Ordered pairs whose product are less than N ; Initialize count to 0 ; count total pairs ; multiply by 2 to get ordered_pairs ; subtract redundant pairs ( a , b ) where a == b . ; return answer ; Driver ... | from math import sqrt
def count_ordered_pairs(N):
"""
Count ordered pairs with product less than N
"""
count_pairs = 0
p = int(sqrt(N - 1)) + 1
q = int(sqrt(N)) + 2
for i in range(1, p, 1):
for j in range(i, q, 1):
count_pairs += 1
count_pairs *= 2
count_pairs -... | 0.58059 | 0.440289 |
Absolute Difference of all pairwise consecutive elements in an array | Function to print pairwise absolute difference of consecutive elements ; absolute difference between consecutive numbers ; Driver Code | def pairwise_difference(arr, n):
"""
Absolute Difference of all pairwise consecutive elements in an array
"""
for i in range(n - 1):
diff = abs(arr[i] - arr[i + 1])
print(diff, end=" ")
if __name__ == "__main__":
arr = [4, 10, 15, 5, 6]
n = len(arr)
pairwise_difference(arr,... | 0.534612 | 0.472318 |
Find sum of N | calculate sum of Nth group ; Driver code | def nth_group(n):
"""
Find sum of N
"""
return n * (2 * pow(n, 2) + 1)
N = 5
print(nth_group(N))
| 0.539954 | 0.467879 |
Find the number of rectangles of size 2 * 1 which can be placed inside a rectangle of size n * m | function to Find the number of rectangles of size 2 * 1 can be placed inside a rectangle of size n * m ; if n is even ; if m is even ; if both are odd ; Driver code ; function call | def number_of_rectangles(n, m):
"""
Find the number of rectangles of size 2 * 1 which can be placed inside a rectangle of size n * m
"""
if (n % 2 == 0):
return (n / 2) * m
elif (m % 2 == 0):
return (m // 2) * n
return (n * m - 1) // 2
if __name__ == "__main__":
n = 3
m... | 0.700075 | 0.643035 |
Absolute difference between sum and product of roots of a quartic equation | Function taking coefficient of each term of equation as input ; Finding sum of roots ; Finding product of roots ; Absolute difference ; Driver Code | def sum_product_difference(a, b, c, d, e):
"""
Absolute difference between sum and product of roots of a quartic equation
"""
rootSum = (-1 * b) / a
rootProduct = e / a
return abs(rootSum - rootProduct)
print(sum_product_difference(8, 4, 6, 4, 1))
| 0.674801 | 0.438665 |
Count Numbers with N digits which consists of odd number of 0 's | Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code | def count_numbers(N):
"""
Count Numbers with N digits which consists of odd number of 0 's
"""
return (pow(10, N) - pow(8, N)) // 2
if __name__ == "__main__":
n = 5
print(count_numbers(n))
| 0.661814 | 0.441131 |
Sum of the first N terms of the series 5 , 12 , 23 , 38. ... | Function to calculate the sum ; Driver code ; number of terms to be included in sum ; find the Sn | def calculate_sum(n):
"""
Sum of the first N terms of the series 5 , 12 , 23 , 38. ...
"""
return (2 * (n * (n + 1) * (2 * n + 1) // 6) + n * (n + 1) // 2 + 2 * (n))
if __name__ == "__main__":
n = 3
print("Sum =", calculate_sum(n))
| 0.613468 | 0.434161 |
Find the sum of the series x ( x + y ) + x ^ 2 ( x ^ 2 + y ^ 2 ) + x ^ 3 ( x ^ 3 + y ^ 3 ) + ... + x ^ n ( x ^ n + y ^ n ) | Function to return required sum ; sum of first series ; sum of second series ; Driver Code ; function call to print sum | def sum(x, y, n):
"""
Find the sum of the series x ( x + y ) + x ^ 2 ( x ^ 2 + y ^ 2 ) + x ^ 3 ( x ^ 3 + y ^ 3 ) + ... + x ^ n ( x ^ n + y ^ n )
"""
sum1 = ((x ** 2) * (x ** (2 * n) - 1)) // (x ** 2 - 1)
sum2 = (x * y * (x ** n * y ** n - 1)) // (x * y - 1)
return (sum1 + sum2)
if __name__ == ... | 0.569374 | 0.769427 |
Sum of first n terms of a given series 3 , 6 , 11 , ... . . | Function to calculate the sum ; starting number ; common ratio of GP ; common difference Of AP ; no . of the terms for the sum ; Find the Sn | def calculate_sum(n):
"""
Sum of first n terms of a given series 3 , 6 , 11 , ... . .
"""
a1 = 1
a2 = 2
r = 2
d = 1
return ((n) * (2 * a1 + (n - 1) * d) / 2 + a2 * (pow(r, n) - 1) / (r - 1))
n = 5
print("Sum =", int(calculate_sum(n)))
| 0.570092 | 0.631708 |
Count of subsets of integers from 1 to N having no adjacent elements | Function to count subsets ; Driver Code | def count_subsets(N):
"""
Count of subsets of integers from 1 to N having no adjacent elements
"""
if (N <= 2):
return N
if (N == 3):
return 2
DP = [0] * (N + 1)
DP[0] = 0
DP[1] = 1
DP[2] = 2
DP[3] = 2
for i in range(4, N + 1):
DP[i] = DP[i - 2] + DP[i... | 0.577019 | 0.532121 |
Count the Arithmetic sequences in the Array of size at least 3 | Function to find all arithmetic sequences of size atleast 3 ; If array size is less than 3 ; Finding arithmetic subarray length ; To store all arithmetic subarray of length at least 3 ; Check if current element makes arithmetic sequence with previous two ... | def number_of_arithmetic_sequences(L, N):
"""
Count the Arithmetic sequences in the Array of size at least 3
"""
if (N <= 2):
return 0
count = 0
res = 0
for i in range(2, N):
if ((L[i] - L[i - 1]) == (L[i - 1] - L[i - 2])):
count += 1
else:
cou... | 0.529993 | 0.61708 |
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming... | def count_of_triplets(a, n):
"""
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ]
"""
answer = 0
x = 0
count = [0 for i in range(100005)]
ways = [0 for i in range(100005)]
for i in range(n):
x ^= a[i]
answer += count[x] *... | 0.508788 | 0.474144 |
Shortest path with exactly k edges in a directed and weighted graph | Set 2 | Python3 implementation of the above approach ; Function to find the smallest path with exactly K edges ; Array to store dp ; Loop to solve DP ; Initialising next state ; Recurrence relation ; Returning final answer ; Driver code ; Input edges... | inf = 100000000
def sm_path(s, d, ed, n, k):
"""
Shortest path with exactly k edges in a directed and weighted graph
"""
dis = [inf] * (n + 1)
dis[s] = 0
for i in range(k):
dis1 = [inf] * (n + 1)
for it in ed:
dis1[it[1]] = min(dis1[it[1]], dis[it[0]] + it[2])
... | 0.517571 | 0.477189 |
Maximum value obtained by performing given operations in an Array | Python3 implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code | import numpy as np
def find_max(a, n):
"""
Maximum value obtained by performing given operations in an Array
"""
dp = np.zeros((n, 2))
dp[0][0] = a[0] + a[1]
dp[0][1] = a[0] * a[1]
for i in range(1, n - 1):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]) + a[i + 1]
dp[i][1] = dp... | 0.524638 | 0.410993 |
Maximum possible array sum after performing the given operation | Function to return the maximum possible sum after performing the given operation ; Dp vector to store the answer ; Base value ; Return the maximum sum ; Driver code | def max_sum(a, n):
"""
Maximum possible array sum after performing the given operation
"""
dp = [[0 for i in range(2)]for j in range(n + 1)]
dp[0][0] = 0
dp[0][1] = -999999
for i in range(0, n):
dp[i + 1][0] = max(dp[i][0] + a[i], dp[i][1] - a[i])
dp[i + 1][1] = max(dp[i][0] ... | 0.617859 | 0.407628 |
Minimize the sum after choosing elements from the given three arrays | Python3 implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen ... | import numpy as np
SIZE = 3
N = 3
def min_sum(A, B, C, i, n, curr, dp):
"""
Minimize the sum after choosing elements from the given three arrays
"""
if (n <= 0):
return 0
if (dp[n][curr] != -1):
return dp[n][curr]
if (curr == 0):
dp[n][curr] = min(
B[i] +
... | 0.53437 | 0.422803 |
Minimum number of cubes whose sum equals to given number N | Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code | def min_of_cubed(k):
"""
Minimum number of cubes whose sum equals to given number N
"""
if (k < 8):
return k
res = k
for i in range(1, k + 1):
if ((i * i * i) > k):
return res
res = min(res, min_of_cubed(k - (i * i * i)) + 1)
return res
num = 15
print(mi... | 0.512693 | 0.515376 |
Maximum Subarray Sum after inverting at most two elements | Function to return the maximum required sub - array sum ; Creating one based indexing ; 2d array to contain solution for each step ; Case 1 : Choosing current or ( current + previous ) whichever is smaller ; Case 2 : ( a ) Altering sign and add to previous cas... | def max_sum(a, n):
"""
Maximum Subarray Sum after inverting at most two elements
"""
ans = 0
arr = [0] * (n + 1)
for i in range(1, n + 1):
arr[i] = a[i - 1]
dp = [[0 for i in range(3)]for j in range(n + 1)]
for i in range(0, n + 1):
dp[i][0] = max(arr[i], dp[i - 1][0] + a... | 0.518059 | 0.455501 |
Maximum sum possible for a sub | Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first elemen... | def max_sum(arr, k, n):
"""
Maximum sum possible for a sub
"""
if (n == 0):
return 0
if (n == 1):
return arr[0]
if (n == 2):
return max(arr[0], arr[1])
dp = [0] * n
dp[0] = arr[0]
for i in range(1, k + 1):
dp[i] = max(arr[i], dp[i - 1])
for i in ra... | 0.54698 | 0.426381 |
Minimum cost to form a number X by adding up powers of 2 | Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code | def minimum_cost(a, n, x):
"""
Minimum cost to form a number X by adding up powers of 2
"""
for i in range(1, n, 1):
a[i] = min(a[i], 2 * a[i - 1])
ind = 0
sum = 0
while (x):
if (x & 1):
sum += a[ind]
ind += 1
x = x >> 1
return sum
if __name_... | 0.584508 | 0.523908 |
Color N boxes using M colors such that K boxes have different color from the box on its left | Python3 Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of box... | M = 1001
MOD = 998244353
dp = [[-1] * M] * M
def solve(idx, diff, N, M, K):
"""
Color N boxes using M colors such that K boxes have different color from the box on its left
"""
if (idx > N):
if (diff == K):
return 1
return 0
if (dp[idx][diff] != -1):
return dp[i... | 0.607081 | 0.345989 |
Count of Numbers in Range where first digit is equal to last digit of the number | Python3 program to implement the above approach ; Base Case ; Calculating the last digit ; Calculating the first digit ; Driver Code | def solve(x):
"""
Count of Numbers in Range where first digit is equal to last digit of the number
"""
ans, temp = 0, x
if (x < 10):
return x
last = x % 10
while (x):
first = x % 10
x = x // 10
if (first <= last):
ans = 9 + temp // 10
else:
ans... | 0.577614 | 0.686149 |
Find maximum points which can be obtained by deleting elements from array | function to return maximum cost obtained ; find maximum element of the array . ; create and initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum rang... | def max_cost(a, n, l, r):
"""
Find maximum points which can be obtained by deleting elements from array
"""
mx = 0
for i in range(n):
mx = max(mx, a[i])
count = [0] * (mx + 1)
for i in range(n):
count[a[i]] += 1
res = [0] * (mx + 1)
res[0] = 0
l = min(l, r)
fo... | 0.503662 | 0.430566 |
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver code | def count_paths(m, n):
"""
Count the number of ways to traverse a Matrix
"""
if m == 1 or n == 1:
return 1
return (count_paths(m - 1, n) + count_paths(m, n - 1))
if __name__ == "__main__":
n = 5
m = 5
print(count_paths(n, m))
| 0.634317 | 0.49469 |
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code | def count_paths(m, n):
"""
Count the number of ways to traverse a Matrix
"""
dp = [[0 for i in range(m + 1)]for j in range(n + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if (i == 1 or j == 1):
dp[i][j] = 1
else:
dp[i][j] = ... | 0.526099 | 0.401981 |
Minimal moves to form a string by adding characters or appending string itself | Python program to print the Minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check ... | INT_MAX = 100000000
def minimal_steps(s, n):
"""
Minimal moves to form a string by adding characters or appending string itself
"""
dp = [INT_MAX for i in range(n)]
s1 = ""
s2 = ""
dp[0] = 1
s1 += s[0]
for i in range(1, n):
s1 += s[i]
s2 = s[i + 1:i + 1 + i + 1]
... | 0.501221 | 0.361644 |
Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; u... | def find_length(string, n):
"""
Maximum difference of zeros and ones in binary string
"""
current_sum = 0
max_sum = 0
for i in range(n):
current_sum += (1 if string[i] == '0'else -1)
if current_sum < 0:
current_sum = 0
max_sum = max(current_sum, max_sum)
r... | 0.50415 | 0.485905 |
Paper Cut into Minimum Number of Squares | Set 2 | Python3 program to find minimum number of squares to cut a paper using Dynamic Programming ; Returns min number of squares needed ; Initializing max values to vertical_min and horizontal_min ; N = 11 & M = 13 is a special case ; If the given rectangle is already a squa... | MAX = 300
dp = [[0 for i in range(MAX)]for i in range(MAX)]
def minimum_square(m, n):
"""
Paper Cut into Minimum Number of Squares
"""
vertical_min = 10000000000
horizontal_min = 10000000000
if n == 13 and m == 11:
return 6
if m == 13 and n == 11:
return 6
if m == n:
... | 0.570092 | 0.262381 |
Painting Fence Algorithm | Returns count of ways to color k posts using k colors ; There are k ways to color first post ; There are 0 ways for single post to violate ( same color_ and k ways to not violate ( different color ) ; Fill for 2 posts onwards ; Current same is same as previous diff ; We always have k - 1 choi... | def count_ways(n, k):
"""
Painting Fence Algorithm
"""
total = k
mod = 1000000007
same, diff = 0, k
for i in range(2, n + 1):
same = diff
diff = total * (k - 1)
diff = diff % mod
total = (same + diff) % mod
return total
if __name__ == "__main__":
n, ... | 0.508544 | 0.345133 |
Sequences of given length where every element is more than or equal to twice of previous | Recursive function to find the number of special sequences ; A special sequence cannot exist if length n is more than the maximum value m . ; If n is 0 , found an empty special sequence ; There can be two possibilities : ( 1 ) Re... | def get_total_number_of_sequences(m, n):
"""
Sequences of given length where every element is more than or equal to twice of previous
"""
if m < n:
return 0
if n == 0:
return 1
res = (get_total_number_of_sequences(m - 1, n) +
get_total_number_of_sequences(m // 2, n - 1... | 0.698227 | 0.360377 |
Sequences of given length where every element is more than or equal to twice of previous | DP based function to find the number of special sequence ; define T and build in bottom manner to store number of special sequences of length n and maximum value m ; Base case : If length of sequence is 0 or maximum value is 0 , ... | def get_total_number_of_sequences(m, n):
"""
Sequences of given length where every element is more than or equal to twice of previous
"""
T = [[0 for i in range(n + 1)]for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
T[i][j... | 0.520496 | 0.332459 |
Clustering / Partitioning an array such that sum of square differences is minimum | Python3 program to find minimum cost k partitions of array . ; Returns minimum cost of partitioning a [ ] in k clusters . ; Create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal parti... | inf = 1000000000
def min_cost(a, n, k):
"""
Clustering / Partitioning an array such that sum of square differences is minimum
"""
dp = [[inf for i in range(k + 1)]for j in range(n + 1)]
dp[0][0] = 0
for i in range(1, n + 1):
for j in range(1, k + 1):
for m in range(i - 1, -... | 0.539954 | 0.42179 |
Modify array to maximize sum of adjacent differences | Returns maximum - difference - sum with array modifications allowed . ; Initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + ab... | def maximum_difference_sum(arr, N):
"""
Modify array to maximize sum of adjacent differences
"""
dp = [[0, 0]for i in range(N)]
for i in range(N):
dp[i][0] = dp[i][1] = 0
for i in range(N - 1):
dp[i + 1][0] = max(dp[i][0], dp[i][1] + abs(1 - arr[i]))
dp[i + 1][1] = max(dp... | 0.571049 | 0.357203 |
Count digit groupings of a number with given constraints | Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as pre... | def count_groups(position, previous_sum, length, num):
"""
Count digit groupings of a number with given constraints
"""
if (position == length):
return 1
res = 0
sum = 0
for i in range(position, length):
sum = sum + int(num[i])
if (sum >= previous_sum):
re... | 0.55254 | 0.434581 |
A Space Optimized DP solution for 0 | val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag dp [ W + 1 ] to store final result ; initially profit with 0 to W KnapSack capacity is 0 ; iterate through all items ; traverse dp array from right to left... | def knap_sack(val, wt, n, W):
"""
A Space Optimized DP solution for 0
"""
dp = [0] * (W + 1)
for i in range(n):
for j in range(W, wt[i], -1):
dp[j] = max(dp[j], val[i] + dp[j - wt[i]])
return dp[W]
val = [7, 8, 4]
wt = [3, 8, 6]
W = 10
n = 3
print(knap_sack(val, wt, n, W))
| 0.522689 | 0.436922 |
Find number of solutions of a linear equation of n variables | Recursive function that returns count of solutions for given rhs value and coefficients coeff [ stat ... end ] ; Base case ; Initialize count of solutions ; One by one subtract all smaller or equal coefficients and recur ; Driver Code | def count_sol(coeff, start, end, rhs):
"""
Find number of solutions of a linear equation of n variables
"""
if (rhs == 0):
return 1
result = 0
for i in range(start, end + 1):
if (coeff[i] <= rhs):
result += count_sol(coeff, i, end, rhs - coeff[i])
return result
... | 0.66072 | 0.60711 |
Number of cycles in a Polygon with lines from Centroid to Vertices | Function to find the Number of Cycles ; Driver code | def n_cycle(N):
"""
Number of cycles in a Polygon with lines from Centroid to Vertices
"""
return (N) * (N - 1) + 1
N = 4
print(n_cycle(N))
| 0.632616 | 0.959762 |
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ... | Function to find Nth term ; Nth term ; Driver Method | def nth_term(N):
"""
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ...
"""
nth = 0
if (N % 2 == 1):
nth = (N * N) + 1
else:
nth = (N * N) - 1
return nth
if __name__ == "__main__":
N = 5
print(nth_term(N))
| 0.506591 | 0.384161 |
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... | Function to find Nth term ; Nth term ; Driver code | def nth_term(N):
"""
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ...
"""
nth = 0
first_term = 4
pi = 1
po = 1
n = N
while (n > 1):
pi *= n - 1
n -= 1
po *= 2
nth = (first_term * pi) // po
return nth
if __name__ == "__main__":
N = 5
print(... | 0.555918 | 0.431584 |
Find value after N operations to remove N characters of string S with given constraints | Function to find the value after N operations to remove all the N characters of String S ; Iterate till N ; Remove character at ind and decrease n ( size of String ) ; Increase count by ind + 1 ; Driver Code ; Given String str ; F... | def characters_count(str, n):
"""
Find value after N operations to remove N characters of string S with given constraints
"""
count = 0
while (n > 0):
cur = str[0]
ind = 0
for j in range(1, n):
if (str[j] < cur):
cur = str[j]
ind = ... | 0.530723 | 0.375621 |
Generate all possible permutations of a Number divisible by N | Function to generate all permutations and print the ones that are divisible by the N ; Convert string to integer ; Check for divisibility and print it ; Print all the permutations ; Swap characters ; Permute remaining characters ; Revoke the swaps ; Driver... | def permute(st, l, r, n):
"""
Generate all possible permutations of a Number divisible by N
"""
if (l == r):
p = ''.join(st)
j = int(p)
if (j % n == 0):
print(p)
return
for i in range(l, r):
st[l], st[i] = st[i], st[l]
permute(st, l + 1, r,... | 0.518302 | 0.37051 |
Find the largest Alphabetic character present in the string | Function to find the Largest Alphabetic Character ; Array for keeping track of both uppercase and lowercase english alphabets ; Iterate from right side of array to get the largest index character ; Check for the character if both its uppercase and lowercase ... | def largest_character(str):
"""
Find the largest Alphabetic character present in the string
"""
uppercase = [False] * 26
lowercase = [False] * 26
arr = list(str)
for c in arr:
if (c.islower()):
lowercase[ord(c) - ord('a')] = True
if (c.isupper()):
uppe... | 0.577614 | 0.387574 |
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency | Function to find the maximum possible prefix of the string ; Hash map to store the frequency of the characters in the string ; Iterate over the string to find the occurence of each Character ; Minimum fre... | def max_prefix(string):
"""
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
"""
Dict = {}
maxprefix = 0
for i in string:
Dict[i] = Dict.get(i, 0) + 1
minfrequency = min(Dict.values())
countminFrequency = 0
for ... | 0.639061 | 0.437643 |
Longest equal substring with cost less than K | Function to find the maximum length ; Fill the prefix array with the difference of letters ; Update the maximum length ; Driver code | def solve(X, Y, N, K):
"""
Longest equal substring with cost less than K
"""
count = [0] * (N + 1)
sol = 0
count[0] = 0
for i in range(1, N + 1):
count[i] = (count[i - 1] + abs(ord(X[i - 1]) - ord(Y[i - 1])))
j = 0
for i in range(1, N + 1):
while ((count[i] - count[j]... | 0.536313 | 0.430626 |
Print the frequency of each character in Alphabetical order | Python3 implementation of the approach ; Function to print the frequency of each of the characters of s in alphabetical order ; To store the frequency of the characters ; Update the frequency array ; Print the frequency in alphatecial order ; If the current ... | MAX = 26
def compress_string(s, n):
"""
Print the frequency of each character in Alphabetical order
"""
freq = [0] * MAX
for i in range(n):
freq[ord(s[i]) - ord('a')] += 1
for i in range(MAX):
if (freq[i] == 0):
continue
print((chr)(i + ord('a')), freq[i], e... | 0.501221 | 0.33928 |
End of preview. Expand in Data Studio
- Downloads last month
- 6