aboutsummaryrefslogtreecommitdiff
path: root/challenge-216/sgreen/python
diff options
context:
space:
mode:
Diffstat (limited to 'challenge-216/sgreen/python')
-rwxr-xr-xchallenge-216/sgreen/python/ch-1.py36
-rwxr-xr-xchallenge-216/sgreen/python/ch-2.py57
2 files changed, 93 insertions, 0 deletions
diff --git a/challenge-216/sgreen/python/ch-1.py b/challenge-216/sgreen/python/ch-1.py
new file mode 100755
index 0000000000..649ebed4be
--- /dev/null
+++ b/challenge-216/sgreen/python/ch-1.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+
+import sys
+
+
+def get_frequency(word):
+ '''Return a dict with the frequency of each letter'''
+ freq = {}
+ for letter in word.upper():
+ if 'A' <= letter <= 'Z':
+ freq[letter] = freq.get(letter, 0) + 1
+
+ return freq
+
+
+def main(words):
+ # The last value is the plate we are matching
+ plate = words.pop()
+ plate_freq = get_frequency(plate)
+ solution = []
+
+ for word in words:
+ # Calculate the frequency of letters in the current word
+ word_freq = get_frequency(word)
+ for letter, cnt in plate_freq.items():
+ # Check that letters in the plate appear in the word
+ if letter not in word_freq or cnt > word_freq[letter]:
+ break
+ else:
+ solution.append(word)
+
+ print(*solution, sep=', ')
+
+
+if __name__ == '__main__':
+ main(sys.argv[1:])
diff --git a/challenge-216/sgreen/python/ch-2.py b/challenge-216/sgreen/python/ch-2.py
new file mode 100755
index 0000000000..62544df0a8
--- /dev/null
+++ b/challenge-216/sgreen/python/ch-2.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+
+import itertools
+import math
+import sys
+
+
+def get_frequency(word):
+ freq = {}
+ for letter in word:
+ if 'a' <= letter <= 'z':
+ freq[letter] = freq.get(letter, 0) + 1
+
+ return freq
+
+
+def main(words):
+ # The last value is the word we are matching
+ target_word = words.pop()
+ target_freq = get_frequency(target_word)
+
+ # Lets check that a solution is possible
+ combined = ''.join(words)
+ for letter in target_freq:
+ if letter not in combined:
+ # The letter doesn't exist in the words, so no solution is possible
+ print(0)
+ return
+
+ # What is the highest frequency
+ highest = max(target_freq.values())
+ word_count = len(words)
+ min_stickers = math.inf
+
+ for freq in itertools.product(range(highest+1), repeat=word_count):
+ if sum(freq) >= min_stickers:
+ # This solution won't be better, so skip it
+ continue
+
+ # Combine all the words with the defined frequency
+ sticker_letters = ''.join([words[x] * freq[x]
+ for x in range(word_count)])
+ sticker_freq = get_frequency(sticker_letters)
+
+ for letter in target_freq:
+ if letter not in sticker_freq or sticker_freq[letter] < target_freq[letter]:
+ # Either a letter is missing, or doesn't occur enough times
+ break
+ else:
+ # We have a new solution with fewer letters
+ min_stickers = sum(freq)
+
+ print(min_stickers)
+
+
+if __name__ == '__main__':
+ main(sys.argv[1:])