MilosObradovic MilosObradovic - 2 months ago 6
Python Question

Hacker rank alternating character in python?

I have been trying to solve Hacker Rank alternating character problem but I got stuck. Can anybody give explanation or better approach to this problem. Thanks!

print("Enter the number of test cases: ")
T = int(input())
line = T
while line > 0:
test_string = input()
i = 0
counter = 0
while i < (len(test_string)):
if (test_string[i - 1] == test_string[i] and len(test_string) > 2):
test_string = test_string[i:]
counter += 1
elif (len(test_string) <= 2):
break
i += 1
print (counter)
line -= 1

Answer

We only need delete a char if the previous char is the same as the current:

T = int(input()) # get how many test cases
for test in range(T): # loop in range T test cases 
    line = input() # get each test 
    prev, changes  = line[0], 0
    for ch in line[1:]:
        if prev == ch:
            changes += 1
        prev = ch            
 print (changes)

Or use sum and range getting all groupings:

T = int(input())
for test in range(T):
    line = input()
    print(sum(line[i:i+2]  in {"BB","AA"}  for i in range(len(line))))