我一直在努力解决黑客等级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
答案 0 :(得分:2)
如果允许使用标准python库,可以使用itertools.groupby
进行尝试:
import itertools as it
def shashank(word):
new_word = ''.join(char for char,_ in it.groupby(word))
return new_word, len(word) - len(new_word)
shashank('ABCD') # returns ('ABCD', 0)
shashank('AAABBB') # returns ('AB', 4)
这是Linux'命令uniq
的Python版本。
答案 1 :(得分: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))))
答案 2 :(得分:0)
Python版本:通过基本编码
很容易:)
$mdDialog
答案 3 :(得分:0)
我们需要做的就是计算字符串中相等的相邻字符(字符序列)...
注意,尽管以下脚本很长,但是解决方案很短。我添加了一个通用解决方案和更多示例。通用解决方案让您选择允许的相邻字符数。对于给定的问题,该数字将为0。所有解决方案均使用任意字符集,因此不仅限于A和B。
现在的问题是,如何轻松地检查一定数量的相邻字符是否相同?
"""
Example: 3 different characters A, B and C. Allow for 2 Consecutive Elements,
hence three equal adjacent elements are not allowed.
AAABBABAABBCCABAAAB given string
AAABBABAABBCCABAAAB initial string
AAABBABAABBCCABAAAB shift by 1
AAABBABAABBCCABAAAB shift by 2
ABBABAABBCCABAAAB use overlapping elements
AABBABAABBCCABAAA check for columns with same character
AAABBABAABBCCABAA and count these columns
sum(10000000000000010) = 2 deletions
"""
好吗?
if __name__ == '__main__':
# Read in from the command line first the integer we put
# into the range generator and input than as many strings
# into the list as the range suggests.
strings = ['AAAA', 'BBBBB', 'ABABABAB', 'BABABA', 'AAABBB']
#
# You can read from the command line by commenting in the
# next line.
#
# strings = [str(input()) for _ in range(int(input()))]
#
#
# Whenever we find two successive equal strings we
# need to delete one. Which means, we count this deletions.
# but we do not perform the deletions, because this
# was not asked!
#
# But how to search for adjacent equal characters, this is
# what we need to find an algorithm for!
#
# Suppose you have the following sequence of
# characters
#
# AABABAABBBABA
#
# Then we create two sequences out of it:
# One, where we drop the first element, and
# the other, where we drop the last element
#
# ABABAABBBABA
# AABABAABBBAB
#
# In other words, we duplicate the sequences
# and shift one to the right by one char and
# keep the overlapping elements.
#
# AABABAABBBABA
# AABABAABBBABA
#
# ABABAABBBABA
# AABABAABBBAB
#
# I think you know by looking at the pattern, why
# I do that.
#
# Now, all we need to do is to count the occurences
# of having the same character at the same vertical
# position (column) in the two shortened sequences
#
# Since I'm lazy and don't like coding myself, I
# use the len() operation on lists for counting and
# conditional list comprehension for finding the matches.
#
print("---------------- show deletions ----------")
for string in strings:
chars = [*string]
deletions = 0 if len(chars) == 0 else len([b for a, b in zip(chars[1:], chars[:-1]) if a == b])
print(deletions)
#
#
# If you are interested in the resulting strings, you
# could do the following: You change the condition in the
# list comprehension and additionally keep the first element!
#
print("---------------- show strings -------------")
for string in strings:
if string == '':
print(string)
continue
chars = [*string]
keep = [a for a, b in zip(chars[1:], chars[:-1]) if a != b]
# Note: we need to add the first char 'manually', that one
# is always kept ... given that there is one
new_string = ''.join((chars[0], *keep))
print(new_string)
#
# Let's solve this on a higher level. Suppose we have an additional
# parameter telling us how many adjacent characters can be the same.
# If we set it to zero we end up with the given excercise.
#
print("--------------- general solution -------------")
def deletions(string, n_adjacent=0):
chars = [*string]
if len(chars) < n_adjacent:
return 0
deletions = sum([len(set(chars[i:i+2+n_adjacent])) == 1 for i in range(len(chars) - (1 + n_adjacent))])
return deletions, string
#
# The given exercise has n_adjacent=0
#
n_adjacent = 0
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
#
# Let's try a few others now ...
#
n_adjacent = 1
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
n_adjacent = 2
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
#
# Note, this algorithm works for arbitrary different
# characters. Look at the following for example ...
#
strings = [
'AAABBBCCC',
'ABCCCCCDEEEEEFAGGAGAGABABAAABBBA',
]
n_adjacent = 0
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
n_adjacent = 1
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
n_adjacent = 2
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
#
# Will it work for n_adjacent = -1, hence 0 elements in a group?
# We would need to delete all elements.
#
n_adjacent = -1
print(f'------ {n_adjacent + 1} consecutive elements allowed --')
for string in strings:
print(deletions(string, n_adjacent=n_adjacent))
如果运行此脚本,输出将如下所示...
"""
---------------- show deletions ----------
3
4
0
0
4
---------------- show strings -------------
A
B
ABABABAB
BABABA
AB
--------------- general solution -------------
------ 1 consecutive elements allowed --
(3, 'AAAA')
(4, 'BBBBB')
(0, 'ABABABAB')
(0, 'BABABA')
(4, 'AAABBB')
------ 2 consecutive elements allowed --
(2, 'AAAA')
(3, 'BBBBB')
(0, 'ABABABAB')
(0, 'BABABA')
(2, 'AAABBB')
------ 3 consecutive elements allowed --
(1, 'AAAA')
(2, 'BBBBB')
(0, 'ABABABAB')
(0, 'BABABA')
(0, 'AAABBB')
------ 1 consecutive elements allowed --
(6, 'AAABBBCCC')
(13, 'ABCCCCCDEEEEEFAGGAGAGABABAAABBBA')
------ 2 consecutive elements allowed --
(3, 'AAABBBCCC')
(8, 'ABCCCCCDEEEEEFAGGAGAGABABAAABBBA')
------ 3 consecutive elements allowed --
(0, 'AAABBBCCC')
(4, 'ABCCCCCDEEEEEFAGGAGAGABABAAABBBA')
------ 0 consecutive elements allowed --
(9, 'AAABBBCCC')
(32, 'ABCCCCCDEEEEEFAGGAGAGABABAAABBBA')
"""
答案 4 :(得分:0)
循环遍历字符串,如果找到与第一个相似的下一个直接字符串,则增加计数器值。
def alterChar(string):
count = 0
for i in range(len(string)-1):
if string[i] == string[i+1]:
count += 1 # Increments if we find next string same
return count
答案 5 :(得分:-1)
所有输入/输出管理除了您需要做的唯一事情是通过输入测试用例并检查字符是否与前一个相同。如果是这种情况,则增加抑制次数。
number_test_cases = int(input("Enter the number of test cases: "))
for idx in range(number_test_cases):
test_case = input("Test case #{} ".format(idx+1))
suppression = 0
for i, c in enumerate(test_case):
if i < 1:
continue
if c == test_case[i-1]:
suppression += 1
print("{} suppression(s) for '{}'".format(suppression, test_case))