Parsing the Input

The input is given with each line containing a range, letter, and a password.

I found the easiest way to parse the input was using regular expressions or RegEx

Part 1

In part 1 we are given a character that has to be in the password between a certain amount of times. For example in the line

the character ‘a’ has to be in the password ‘abcde’ between 1 and 3 times inclusive.

we can set this up by iterating through the list of passwords and incrementing the correct count if it is valid. Python has a handy method for strings called str.count which allows you to count th enumber of occurences of a string (in this case the key) in a string (the password). Documentation. If the number of times the key occurs is between the bounds given, the password is valid, and we increment the counter. After we have incremented through the whole list, we return the valid count.

Part 2

Part 2 changes the rule of a valid password. A password is now valid if only one of the positions given by the bounds (starting at 1) is the key. We can iter through the list like before but the condition on when we increment the valid counter changes. We can use Python’s bitwise xor operator, ^, when checking against if the index of the list is the key for both locations to make sure one of them is the key but not both. After iterating through the whole list and incrementing the counter when we come across a valid password, we return the result.