gpt4 book ai didi

python - 黑客在 python 中排名交替字符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:58:36 26 4
gpt4 key购买 nike

我一直在努力解决Hacker Rank alternating character problem但我卡住了。任何人都可以解释或更好地解决这个问题。谢谢!

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

最佳答案

如果前一个字符与当前字符相同,我们只需要删除一个字符:

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)

或者使用 sum 和 range 获取所有分组:

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))))

关于python - 黑客在 python 中排名交替字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com