有这样一种程序,程序会向用户显示一个编码的单词,允许用户输入一个字符,以查看该字符是否在编码的单词中。如果输入了一个字符,允许用户删除一次输入并恢复数组中的原始字符。
如下是当前的代码片段,该程序将每个输入字符追加到列表中。问题是如何恢复到原始字符。
while Encoded_Team != Team:
print("\nThe encoded team is", Encoded_Team,"\n")
Choose = input("Choose a letter in in the encoded team that you would replace: ")
Replace = input("What letter would you like to replace it with? ")
array.append(Choose)
array.append(Replace)
Encoded_Team = Encoded_Team.replace(Choose, Replace)
Delete = input("\nWould you like to delete a character - yes or no: ")
以下是一些解决方法:
2、解决方案:
-
使用列表来保存原始的字符串。 当用户输入一个字符时,将该字符添加到列表中,然后用用户输入的替换字符替换编码的单词中的该字符。当用户要删除一个字符时,从列表中删除最后一个字符,并将编码的单词恢复到删除前的状态。
-
使用栈来保存原始字符串。 栈是后进先出的数据结构,这意味着最后添加的元素是第一个被删除的元素。当用户输入一个字符时,将该字符压入栈中,然后用用户输入的替换字符替换编码的单词中的该字符。当用户要删除一个字符时,从栈中弹出最后一个字符,并将编码的单词恢复到删除前的状态。
以下是一个使用栈来实现的示例代码:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
stack = Stack()
while Encoded_Team != Team:
print("\nThe encoded team is", Encoded_Team,"\n")
Choose = input("Choose a letter in in the encoded team that you would replace: ")
Replace = input("What letter would you like to replace it with? ")
# Push the original character to the stack
stack.push(Choose)
# Replace the character in the encoded word
Encoded_Team = Encoded_Team.replace(Choose, Replace)
Delete = input("\nWould you like to delete a character - yes or no: ")
# Delete the last character from the stack and restore the original character
if Delete == "yes":
original_character = stack.pop()
Encoded_Team = Encoded_Team.replace(Replace, original_character)
-
使用元组来保存原始字符串。 元组是不可变的数据类型,这意味着一旦创建就无法更改。当用户输入一个字符时,将该字符创建一个元组并将元组追加到列表中,然后用用户输入的替换字符替换编码的单词中的该字符。当用户要删除一个字符时,从列表中删除最后一个元组,并将编码的单词恢复到删除前的状态。
-
使用字典来保存原始字符串。 字典是一种键值对的数据结构,这意味着可以将一个键映射到一个值。当用户输入一个字符时,将该字符作为键,并将编码的单词中的该字符作为值创建一个键值对,然后用用户输入的替换字符替换编码的单词中的该字符。当用户要删除一个字符时,从字典中删除最后一个键值对,并将编码单词恢复到删除前的状态。