gpt4 book ai didi

python - 如果基于此算法存在,我如何弹出这封信?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:12:01 28 4
gpt4 key购买 nike

我试图弹出用户给出的任何字母,例如,如果他们给你一个关键字“ROSES”,那么这些字母应该从列表中弹出。

注意:在SOURCE CODE

之后我有很多解释

源代码

  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"]
encrypted_message = []
key_word = str(input("Please enter a word:"))
key_word = list(key_word)
#print(key_word)

check_for_dup = 0


for letter in key_word:
for character in alphabet:
if letter in character:
check_for_dup +=1
alphabet.pop(check_for_dup)

print(alphabet)
print(encrypted_message)

样本输入

假设关键字是“玫瑰”

这就是它给了我以下列表的内容 ['A', 'C', 'E', 'G', 'I', 'K', 'L', 'M', ' N'、'O'、'P'、'Q'、'R'、'S'、'T'、'U'、'V'、'W'、'X'、'Y'、'Z' ]

但那是错误的 它应该只是删除用户给定的关键字中存在的字符,例如单词“Roses”每个字母应该被删除而不是在弹出的列表中。正如您在列表中看到的那样,字母“B”、“D”、“F”、“H”等都不见了。我要做的是弹出关键字存在的字母索引。

这是应该发生的事情。

["A","B","C","D","F","G","H","I","J","K","L","M","N","P","Q","T","U","V","W","X","Y","Z"]

关键字“ROSES”的字母已从列表中删除

最佳答案

您的代码中存在一些缺点,这里是一个有效的实现:

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"]
key_word = str(input("Please enter a word:"))

for letter in key_word.upper():
if letter in alphabet:
alphabet.remove(letter)

print(alphabet)

解释

  1. 您可以迭代一个字符串,无需将其转换为列表
  2. 使用 remove 因为你可以直接使用 str 类型
  3. 你需要.upper()输入,因为如果用户输入 a
  4. ,你想删除 A

请注意,我没有处理 encrypted_message,因为它目前未被使用。

此外,正如一些评论所说,您可以使用 set而不是列表,因为集合的查找速度更快。

alphabet = {"A","B","C","D",...}

编辑

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"]
key_word = str(input("Please enter a word:"))
encrypted_message = []
for letter in key_word.upper():
if letter in alphabet:
alphabet.remove(letter)
encrypted_message.append(letter)

encrypted_message.extend(alphabet)

这是处理您的encrypted_message 的新实现。这将在用户输入后保持字母表的顺序。此外,如果您想知道为什么没有重复项,您将仅在 letter is in alphabet 时附加,这意味着第二次它不会在 alphabet 中,因此未添加到您的 encrypted_message

关于python - 如果基于此算法存在,我如何弹出这封信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47335380/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com