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