Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created March 31, 2022 10:52
Show Gist options
  • Save les-peters/3db77dc04adc85a4a0d16fee0e26c675 to your computer and use it in GitHub Desktop.
Save les-peters/3db77dc04adc85a4a0d16fee0e26c675 to your computer and use it in GitHub Desktop.
Contained Items
question = """
Given a string that represents items as asterisks (*) and compartment walls as pipes (|),
a start index, and an end index, return the number of items in a closed compartment.
Example:
let str = '|**|*|*'
> containedItems(str, 0, 5)
> 2
> containedItems(str, 0, 6)
> 3
> containedItems(str, 1, 7)
> 1
Extra credit: What if you had multiple pairs of start and end indices? You can do it in O(n) time!
"""
import re
def containedItems(s, start, end):
b = len(re.sub(r'[^\*]', '', re.sub(r'\*+$', '', re.sub(r'^\*+', '', s[start:end]))))
print(b)
str = '|**|*|*'
containedItems(str, 0, 5)
containedItems(str, 0, 6)
containedItems(str, 1, 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment