0

i am changing a cpp code to python. but python code dosent run. This is my python code :

n,k=input().split()
s=input()
l = len(s)
ans = 0
k=int(k)
for i in range(l):
    ans += max(ord(s[i]) - ord('a'), ord('z') - ord(s[i]))
if (ans < k):
    print("-1")
for i in range(l):
    if ((ord(s[i]) - ord('a')) > (ord('z') - ord(s[i]))):
        now = ord(s[i]) - ord('a')
        if (now >= k) :
            s[i] -= k
            k=0
        else :
            s[i] = chr(ord('a'))
            k -= now
    else:
        now = ord('z') - ord(s[i])
        if (now >= k):
            s[i] =chr(ord(s[i])+ k)
            k=0
        else:
            s[i] ='z'
            k -= now
print(s)

and i get this error :

...line 22, in <module>
    s[i] =chr(ord(s[i])+ k)
TypeError: 'str' object does not support item assignment

can anybody help me? Thanks a lot

Mohammad
  • 13
  • 4

1 Answers1

1
  • string are immutable in python
  • You are trying to change a string
  • I would recommend you to convert your string to a list by doing this:

    string = "abs"
    string_list = list(string)
    print(string_list)
    
  • Output:

    ['a', 'b', 's']
    
  • Now operate on this list because list is mutable string_list
  • In your code you have to convert the variable s to a list and then operate on it
Jai
  • 3,211
  • 2
  • 17
  • 26