为什么我的代码中出现类型错误?

时间:2019-06-10 22:07:59

标签: python encryption vigenere

我正在尝试编写一个vigenere密码。我对此的假意是: -以明文形式找到每个字母的索引 -在关键消息中找到每个字母的索引 -将索引加在一起 -新字母将位于索引总和的位置

我相信我的代码组织正确,但是我不确定是否因为输入错误而丢失了某些内容。

# global constants:
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
ALPHABET_SIZE = len(ALPHABET)

# main function definition:
def main():
    # User interface:
    print("Welcome to the Vigenere Cipher!")

    keep_running = True

    while(keep_running):
        print("Enter 1 to encrypt a message")
        print("Enter 2 to decrypt a message")
        print("Enter 0 to exit")
        print()

        user_choice = int(input("What would you like to do? " ))

        if user_choice == 0:
            keep_running = False

        if user_choice == 1:
            plaintext = input("Enter a plaintext message to encrypt: ")
            key = str(input("Enter a message to use as the key: "))
            ciphertext = enc(key, plaintext)
            print("Resulting cipertext:", ciphertext)
            print()


        if user_choice == 2:
            ciphertext = str(input("Enter a ciphertext message to decrypt: "))
            key = str(input("Enter a message to use as the key: "))
            plaintext = dec(key, ciphertext)
            print("Resulting plaintext:", plaintext)
            print()


def enc(key, plaintext):
    ciphertext = []
    for cipher_char in plaintext:
        char_pos = ALPHABET.index(cipher_char)
    for key_char in key:
        message_pos = ALPHABET.index(key_char)
    new_pos = (char_pos + key_char)
    enc_char = ALPHABET(new_pos)
    plaintext += enc_char
    return plaintext






# call to main:
main()

1 个答案:

答案 0 :(得分:1)

错误在这一行

M=10
N=10
c=2
n=seq(1, 4, by=1)
p=0.25
q=seq(1,0.25, by =-0.05)
ntrials = 10

params <- expand.grid(
  trial = 1:10,
  M = M,
  N = N,
  c = c,
  n = n,
  p = p,
  q = q
) %>%
  as_tibble()

View(params)

# > nrow(params)
# [1] 640

# replace with your own, of course
my_madeup_function <-
  function(M, N, c, n, p, q) {
    matrix(data = rep(M * N + c - n * p * q, 100),
           nrow = 10,
           ncol = 10)
  }

# we use `purrr::pmap`, an apply-type function to pass all of the parameters (except for trials) to the function:

result <- tibble(matrix = pmap(select(params, -trial), my_madeup_function)) 


summary <- bind_cols(params, result)

char_pos是一个位置,类型为int。 key_char是一个字符,类型为字符串。您不能将一个添加到另一个。

也在上述正上方的这些行中:

new_pos = (char_pos + key_char)

每个for循环都反复设置变量(分别为char_pos和message_pos)。因此,仅考虑字母中每个字符串(分别为纯文本和键)中最后一个字符的位置。因此,您需要重新考虑一下逻辑。

最后,我建议您在ALPHABET中包含大写字母。第一次尝试输入值错误,因为尝试了大写输入。