Как мне увеличить позицию буквы в списке на позицию буквы? - PullRequest
0 голосов
/ 02 апреля 2019

У меня есть программа, которая принимает позицию буквы и увеличивает позицию на величину сдвига, а затем дает мне новую позицию букв, это функция списка цезаря.Однако мне нужно иметь возможность увеличить положение буквы на величину сдвига, а также на положение буквы, поэтому, если у меня "привет" и сдвиг равен 15, h = 7, так что 7 +15 +0 = 22и е будет 4 + 15 + 1 (позиция е) = 20 Однако я не уверен, как отредактировать свой код, чтобы я мог увеличить позицию каждой буквы на значение их позиции.Код работает нормально, мне просто нужна помощь, чтобы понять этот шаг.

alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] 
def caesar(plaintext,shift):  
# initialize ciphertext as blank string
    ciphertext = ""
# loop through the length of the plaintext
    for i in range(len(plaintext)):        
    # get the ith letter from the plaintext
        letter = plaintext[i]
    # find the number position of the ith letter
        num_in_alphabet = alphabet.index(letter)
        print (num_in_alphabet)
    # find the number position of the cipher by adding the shift 
        cipher_num = (num_in_alphabet + shift + 3) % len(alphabet) 
    # find the cipher letter for the cipher number you computed
        cipher_letter = alphabet[cipher_num] 
    # add the cipher letter to the ciphertext
        ciphertext = ciphertext + cipher_letter 

# return the computed ciphertext
    return ciphertext
def main():

    plaintext = ("hello")
    shift = 16

    text = caesar(plaintext,shift)
    print (text)

main()

1 Ответ

0 голосов
/ 02 апреля 2019
cipher_num = (num_in_alphabet + shift + i) % len(alphabet) 

Или намного проще

shift = 16
chiper =  ''.join([chr(((ord(c)-ord('a')+shift+i)%26)+ord('a')) for i, c in enumerate("hellow")])
assert  chiper == 'xvdeir'
...