Mutations - Hackerrank Solution

 

Mutations


Objective


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.


Solution:

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)

Note:

This Code is Verified by all Test Cases.If any error occurs then Comment correct code Below in comment box.

Disclaimer:-

The above hole problem statement is given by hackerrank.com, but the solution is generated by the CodexRitik . if any of the query regarding this post or website fill the following contact form Thank You.

Mutations - Hackerrank Solution Mutations - Hackerrank Solution Reviewed by CodexRitik on March 24, 2020 Rating: 5

2 comments:

  1. def mutate_string(string, position, character):
    l = list(string)
    l[position] = character
    string = ''.join(l)
    return string


    if __name__ == '__main__':
    s = input()
    i, c = input().split()
    s_new = mutate_string(s, int(i), c)
    print(s_new)

    ReplyDelete
    Replies
    1. Thanks For Solution.I have Already Given this solution but there are two same post of mutations So it was creating a cause.Now i have solved this issue.

      Delete

Powered by Blogger.