Skip to content

Instantly share code, notes, and snippets.

@fisher6
Created January 22, 2019 21:15
Show Gist options
  • Save fisher6/8a144eb5967f411736202968b9c21976 to your computer and use it in GitHub Desktop.
Save fisher6/8a144eb5967f411736202968b9c21976 to your computer and use it in GitHub Desktop.
"""
If a sticker is the collection of
the letters of "givecampusinc", return the
number of stickers needed to complete an input
string. "mice span" would require one sticker,
"give mice span" would require 2 because
the 2nd 'e' requires a new sticker. Treat it as case-insensitive.
"""
def how_many_sticks(sticker, letters_input):
letters_input = letters_input.replace(' ', '')
abcs = [chr(c) for c in range(ord('a'), ord('z') + 1)]
sticker_letters_count = {letter: 0 for letter in abcs} # {'a': 0, 'b': 0, ..., 'z': 0}
input_letters_count = {letter: 0 for letter in abcs}
for letter in sticker:
sticker_letters_count[letter.lower()] += 1
for letter in letters_input:
input_letters_count[letter.lower()] += 1
max_stickers = 1
for letter in letters_input:
try:
max_stickers = max(max_stickers, division_round_up(input_letters_count[letter], sticker_letters_count[
letter]))
except ZeroDivisionError:
return -1
return max_stickers
def division_round_up(top, bottom):
return top / bottom + (1 if top % bottom != 0 else 0)
print how_many_sticks('givecampusinc', 'mice span') # 1
print how_many_sticks('givecampusinc', 'give mice span') # 2
@fisher6
Copy link
Author

fisher6 commented Jan 22, 2019

And I was remembered back from my python hacking days of the wonderful defaultdict that will let me skip that abcs initialization, you can set by default both sticker_letters_count and input_letters_count to return 0 for every letter:

from collections import defaultdict
sticker_letters_count = defaultdict(lambda: 0)
input_letters_count = defaultdict(lambda: 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment