Part 1
In this puzzle we have a list of strings containing some ID. We should count the number of strings containing a single character either twice or thrice.We used the collections.Counter class for counting the number each characters appears in the strings. Once we have that, we can check if a character is counted 2 or 3 times:
num_twos = 0
num_threes = 0
for box_id in box_ids:
counter = Counter(box_id)
if 2 in counter.values():
num_twos += 1
if 3 in counter.values():
num_threes += 1
Part 2
In part 2, we should find the pair of IDs which only differ by a single character. Once we have the pair, we should return the common characters without the difference.
Since all IDs are of equal length, we can find the common characters with the function zip:
def common(str1, str2):
common_string = ""
for ch1, ch2 in zip(str1, str2):
if ch1 == ch2:
common_string += ch1
return common_string
If the length of the common strings is only 1 less than the originals, we have found our answer.
We could have also split it into two parts: Counting the number of differences and only creating the common strings once we found the answer. But this combined approach was fast enough.
No comments:
Post a Comment