Write a recursive function block_count(string) to return the number of blocks consisting of the same letter in the given input string. Example.
>>> block_count ('AABBCCBBDDD')
5
>>>block_count ('GGABAA')
4
Code in python (code to copy) with explanation in comments
def block_count(string):
# base case
if(len(string)<=1):
return len(string)
# recursive case
# If the first character is same as the second character
# then the answer to this string is same as the answer to
# this string being read from index 1
if(string[0]==string[1]):
return block_count(string[1:])
# If the above is false then the answer is 1 plus the answer to
# the string being read from index 1
else:
return 1 + block_count(string[1:])
# Print test results to console
print("block_count ('AABBCCBBDDD') = ", block_count('AABBCCBBDDD'))
print("block_count ('GGABAA') = ", block_count('GGABAA'))
python code screenshot
Output Screnshot
Get Answers For Free
Most questions answered within 1 hours.