MilosObradovic MilosObradovic - 2 years ago 95
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):
i += 1
print (counter)
line -= 1

Answer Source

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))))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download