Question: Python Mutations [Strings]
We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
Let's try to understand this with an example.
You are given an immutable string, and you want to make changes to it.
Example
>>> string = "abracadabra"
You can access an index by:
>>> print string[5]
a
What if you would like to assign a value?
>>> string[5] = 'k'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
How would you approach this?
- One solution is to convert the string to a list and then change the value.
Example
>>> string = "abracadabra"
>>> l = list(string)
>>> l[5] = 'k'
>>> string = ''.join(l)
>>> print string
abrackdabra
- Another approach is to slice the string and join it back.
Example
>>> string = string[:5] + "k" + string[6:]
>>> print string
abrackdabra
Task
Read a given string, change the character at a given index and then print the modified string.
Function Description
Complete the mutate_string
function in the editor below.
mutate_string
has the following parameters:
- string string: the string to change
- int position: the index to insert the character at
- string character: the character to insert
Returns
- string:Â the altered string
The next line contains an integer position, the index location and a string character, separated by a space.
Sample Input
STDIN Function
----- --------
abracadabra s = 'abracadabra'
5 k position = 5, character = 'k'
Sample Output
abrackdabra
Possible Solutions
Now, we will discuss the possible solutions for the given problem. We have already been given the following code on hacker rank.
def mutate_string(string, position, character):
return
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
Now, let us jump into the possible solutions
Solution-1: Using a while loop
Let us first solve the problem using the while loop in Python.
def mutate_string(string, position, character):
l, i = list(), 0
while i < len(string):
if (i == position):
l += [character]
else:
l += [string[i]]
i += 1
return ''.join(l)
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
This solution defines a function called "mutate_string
" that takes in three parameters: a string, a position, and a character. It creates an empty list called "l
" and a variable called "i
" initialized to 0
. It then enters a while loop that iterates for as many times as there are characters in the input string. Within the loop, if the current iteration index "i
" is equal to the input position, it appends the input character to "l
", otherwise it appends the character at the corresponding index in the input string. Once the loop completes, it converts the list "l
" to a string and returns it. This function effectively replaces a character at a specified position in the input string with a new specified character.
Solution-2: One-line solution
We can solve the given problem in one line of code as well. Let us return the required output from the function in one line of code.
def mutate_string(string, position, character):
return string[:position]+character+string[position+1:]
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
This solution defines a function called "mutate_string
" that takes in three parameters: a string, a position, and a character. It returns a new string that is created by concatenating three parts: the substring from the beginning of the input string up to the specified position, the input character, and the substring from the specified position+1 to the end of the input string. This function effectively replaces a character at a specified position in the input string with a new specified character by using string slicing.
Solution-3: Using list comprehension
Let us now use list comprehension to solve the problem.
def mutate_string(string,pos,charac):
x = [i for i in string]
x[pos] = charac
return ''.join(x)
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
Similar to previous solutions, this solution also defines a function called "mutate_string
" that takes in three parameters: a string, a position, and a character. It creates a list "x
" using list comprehension, where each element in the list is a character from the input string. Then it replaces the element at the specified position with the input character. After that it joins all elements of the list using join()
function, which returns a string. This function effectively replaces a character at a specified position in the input string with a new specified character by using list comprehension and join function.
This implementation is different from the previous ones in that it creates a list from the input string, modifies the element at the specified position, and then joins the elements of the list to return a new string. The first implementation used a while loop to iterate through the string and the second implementation used string slicing to create the new string.
Solution-4: Using for loop
Similar to the while loop, we can also use the for loop to solve the problem as shown below:
def mutate_string(string, position, character):
str1=""
str2=""
for i in range(len(string)):
if(i == position):
break
else:
str1+=string[i]
for i in range(len(str1)+1,len(string)):
str2+=string[i]
string=str1+character+str2
return string
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
Similar to previous solutions, this also defines a function called "mutate_string
" that takes in three parameters: a string, a position, and a character. It creates two empty strings, 'str1
' and 'str2
' and then uses two for loops to iterate through the input string. In the first for loop, it iterates through the input string and if the current iteration index is equal to the input position, it breaks the loop otherwise it appends the current character to 'str1
'. In the second for loop, it starts from the length of 'str1'+1
and iterates through the rest of the characters in the input string and appends each character to 'str2
'. Then it concatenates 'str1
', input character and 'str2' and assigns the result to 'string
' and returns it. This function effectively replaces a character at a specified position in the input string with a new specified character by using two loops to create two new strings and then concatenating them.
Summary
In this short article, we discussed how we can solve the mutations problem on hacker rank using four different solutions. We explained each solution in detail.
Further Reading
Question on hacker Rank: Python Mutations [Strings]