Home > Article > Backend Development > Good keys
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Challenge, My solutions
You are given a positive integer, $int, having 3 or more digits.
Write a script to return the Good Integer in the given integer or -1 if none found. A good integer is exactly three consecutive matching digits.
I original thought this task could be done with a regular expression pattern, but it seems I was wrong. I'll be looking at other TPW members to see if they can do it that way.
For this task I have a variable pos that iterates from 0 to three less than the length of the string. I then check four things:
If these are all true, I return those three digits. This is done as a string in Python, because '000' is not a real integer. If the iterator is exhausted, I return -1.
def good_integer(n: int) -> str: value = str(n) length = len(value) for pos in range(length-2): if ( value[pos] == value[pos+1] and value[pos] == value[pos+2] and (pos == 0 or value[pos] != value[pos-1]) and (pos + 3 == length or value[pos] != value[pos+3]) ): return value[pos:pos+3] return '-1'
$ ./ch-1.py 12344456 444 $ ./ch-1.py 1233334 -1 $ ./ch-1.py 10020003 000
You are given an alphabetic string, $str, as typed by user.
Write a script to find the number of times user had to change the key to type the given string. Changing key is defined as using a key different from the last used key. The "shift" and "caps lock" keys won’t be counted.
Fun fact. When I get a new keyboard (every few years), I see how long it takes before I rip the caps lock key out. Most keyboards don't last a day!
For this task, I convert the string to lower case and start with two variables. The current_key value is the current key pressed, and is initialized with the first letter from our input. The changes variable is the number of key changes I make, and starts with 0.
I then loop through each letter in the input string. If that letter is different from current_key, I update it with the new letter, and increment changes by 1.
def key_changes(s: str) -> int: s = s.lower() current_key = s[0] changes = 0 for letter in s: if letter != current_key: current_key = letter changes += 1 return changes
$ ./ch-2.py pPeERrLl 3 $ ./ch-2.py rRr 0 $ ./ch-2.py GoO 1
The above is the detailed content of Good keys. For more information, please follow other related articles on the PHP Chinese website!