Last active
November 21, 2020 04:42
-
-
Save Gerst20051/f4ecaf2677e2d23b53c7a2cf8b004a6f to your computer and use it in GitHub Desktop.
Count Subarrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
# | |
# Complete the 'countSubarrays' function below. | |
# | |
# The function is expected to return a LONG_INTEGER. | |
# The function accepts following parameters: | |
# 1. INTEGER_ARRAY numbers | |
# 2. INTEGER k | |
# | |
def countSubarrays(numbers, k): | |
return countSubarraysLoop(numbers, k) | |
def countSubarraysLoop(numbers, k): | |
count = 0 | |
for i in range(len(numbers)): | |
for j in range(i + 1, len(numbers) + 1): | |
if arrayProduct(numbers[i:j]) <= k: | |
count += 1 | |
return count | |
def countSubarraysFunctional(numbers, k): | |
subarrays = generateSubarrays(numbers) | |
products = calcProductOfSubarrays(subarrays) | |
filteredArray = filterProductsByThreshold(products, k) | |
return len(filteredArray) | |
def generateSubarrays(numbers): | |
subarrays = [] | |
for i in range(len(numbers)): | |
for j in range(i + 1, len(numbers) + 1): | |
subarrays.append(numbers[i:j]) | |
return subarrays | |
def calcProductOfSubarrays(numbers): | |
return [arrayProduct(i) for i in numbers] | |
def arrayProduct(numbers): | |
product = 1 | |
for number in numbers: | |
product *= number | |
return product | |
def filterProductsByThreshold(products, threshold): | |
return [p for p in products if p <= threshold] | |
if __name__ == '__main__': | |
print(countSubarrays([1, 2, 3], 4)) # 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment