Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Last active November 21, 2020 04:42
Show Gist options
  • Save Gerst20051/f4ecaf2677e2d23b53c7a2cf8b004a6f to your computer and use it in GitHub Desktop.
Save Gerst20051/f4ecaf2677e2d23b53c7a2cf8b004a6f to your computer and use it in GitHub Desktop.
Count Subarrays
#!/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