Minimum Keystrokes Python Calculator Problem

Viewed 417

I am having trouble with calculating the minimum number of times you have to press the keyboard to type a certain string. The rules are as follows:

  • Each letter you type counts as 1 keystroke
  • Activating caps lock counts as 1 keystroke
  • Deactivating caps lock counts as 1 keystroke
  • Pressing shift counts as 1 keystroke
  • You may not hold down shift for more than one letter
  • You need to write a function that takes in a string and returns the minimum number (an integer) of keystrokes needed to type that string

I am having some slight issues attempting to code this in Python. My code so far:

def getAns(string):
    uppercase_count = 0
    keystrokes = 0
    for i in range(len(string)):
        if string[i] == string[i].upper():
            uppercase_count += 1 
            if uppercase_count == 1:
                keystrokes += 1
        else:
            if uppercase_count > 1:
                keystrokes += 1
            uppercase_count = 0
        keystrokes += 1     
    return keystrokes

Test string:

"EWlweWXZXxcscSDSDcccsdcfdsFvccDCcDCcdDcGvTvEEdddEEddEdEdAs"

My function is returning 79 instead of 78, which it should be. I cannot find any problem in my logic. Can anybody help me?

This is the correct answer code, but I don't get the difference

def getAns(self, s):
    if not s:
        return 0
    
    cap = 0
    res = 0
    chars = ["abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
            
    for i,c in enumerate(s):

        if c in chars[cap]:
            res+=1 
        else:
            t = abs(cap - 1)
            
            if i+1 < len(s) and s[i+1] in chars[t]:
                cap = t
                
            res+=2

    return res
1 Answers

When you reduce the input string to the minimal substring for which you still get a different output, you will identify this substring:

"DCcD"

For this input, your function will return 7, while the correct code returns 6.

Your function identifies this sequence:

Caps ON D C Caps OFF c Shift+D = 7

But... and here it comes... the correct solution identifies this sequence:

Caps ON D C Shift+c D = 6

It takes into account that you can use Shift while CAPS-LOCK is on, which will produce a lowercase letter!

Related