HackerRank Python: Mutations Solution

Table of Contents

Question

Solution

				
					def mutate_string(string, position, character):
    # Convert the string to a list
    string_list = list(string)
    
    # Modify the value at the desired index
    string_list[position] = character
    
    # Convert the list back to a string
    modified_string = ''.join(string_list)
    
    return modified_string

				
			
				
					def mutate_string(string, position, character):
    # Slice the string before the desired index
    part1 = string[:position]
    
    # Slice the string after the desired index
    part2 = string[position+1:]
    
    # Concatenate the modified character at the desired position
    modified_string = part1 + character + part2
    
    return modified_string

				
			

Approach 1: Convert the string to a list, modify the value at the desired index, and convert the list back to a string.

  1. Convert the string to a list: In this approach, we first convert the given string into a list using the list() function. This splits the string into individual characters and stores them as elements in a list. For example, the string “abracadabra” would be converted to the list ['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a'].

  2. Modify the value at the desired index: Next, we modify the value at the desired index by assigning a new character to that specific position in the list. For example, if we want to change the character at index 5 to ‘k’, we access string_list[5] and assign it the value ‘k’. The list would now become ['a', 'b', 'r', 'a', 'c', 'k', 'd', 'a', 'b', 'r', 'a'].

  3. Convert the list back to a string: Finally, we convert the modified list back to a string using the ''.join() function. This function joins all the elements of the list together, using an empty string '' as the separator. The resulting string would be 'abrackdabra', which is the modified version of the original string.

Approach 2: Slice the string and concatenate the modified character in the desired position.

    1. Slice the string before the desired index: In this approach, we slice the original string into two parts. The first part is from the beginning of the string up to (but not including) the desired index position.

    2. Slice the string after the desired index: The second part is from the position after the desired index until the end of the string.

    3. Concatenate the modified character at the desired position: We then concatenate these two sliced parts along with the modified character in the desired position. This creates the modified string.

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment