0

I needed the result as a char array of the secret key combined with alphabets in 5x5:

import numpy as np
def playfair():
    key=input("Enter the secret key")
    key+='abcdefghiklmnopqrstuvwxyz'
    size=len(key)
    for i in range(size):
        if key[i]=='j':
            key[i]='i'
        for j in range(i+1,size):
            if key[j]==key[i]:
                for k in range(j,size):
                    key[k]=key[k+1]
                size-=1
            else: j+=1
    play = np.zeros((5, 5), 'U1')
    play.flat[:32] = list(key)

playfair()
play

But i got this error instead on entering the secret key , in this case the key i entered is "secret"

Enter the secret key



---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-e0a72d62bfc0> in <module>
     18     play = np.zeros((5, 5), 'U1')
     19     play.flat[:32] = list(key)
---> 20 playfair()
     21 play
     22 

<ipython-input-49-e0a72d62bfc0> in playfair()
     11             if key[j]==key[i]:
     12                 for k in range(j,size):
---> 13                     key[k]=key[k+1]
     14                 size-=1
     15             else: j+=1

TypeError: 'str' object does not support item assignment
richinrix
  • 434
  • 1
  • 3
  • 13
  • 3
    Strings in python are immutable, so you'll have to create a new string. See https://stackoverflow.com/questions/41752946/replacing-a-character-from-a-certain-index – user Jun 23 '20 at 18:28
  • 1
    ^ Alternatively you can do some string splitting and concatenation to achieve you're desired output. – plum 0 Jun 23 '20 at 18:29
  • Thank you ,I used list now to correct it because they are mutable – richinrix Jun 24 '20 at 18:07

1 Answers1

0

I corrected it by converting the key string to list and then operated on the list and at the end converted the list back to string.

import numpy as np

key=input("Enter the secret key")
key+='abcdefghiklmnopqrstuvwxyz '
size=len(key)
l_key=list(key)

for i in range(size):
    if l_key[i]=='j':
        l_key[i]='i'
    for j in range(i+1,size):
        if l_key[j]==l_key[i]:
            for k in range(j,size-1):
                l_key[k]=l_key[k+1]
            size-=1
        else: j+=1
final_key=''.join(l_key)

play = np.zeros((5, 5), 'U1')
play.flat[:32] = list(final_key)

final_key

It works now because lists are mutable.

richinrix
  • 434
  • 1
  • 3
  • 13