Question

I am writing a program where the program displays a word to the user which is encoded. The program allows the user to enter a character to see if that character is in the encoded word. If the character enters a character, I want to allow them one go at deleting their entry and restoring the original character back to the array.

Here is my code so far - I have started to develop the part of the program that will append each entered character to a list. My question is how I can revert back to the original character.

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: ")

Any ideas?

Was it helpful?

Solution

This might be easier to handle with a list:

encoded = list(Encoded_Team)
plaintext = list(Team)
changes = []
while encoded != plaintext:
    print("\nThe encoded team is {0}\n".format("".join(encoded)))
    old = input("Which letter would you like to replace? ")
    indices = [i for i, c in enumerate(encoded) if c == old]
    new = input("What letter would you like to replace it with? ")
    for i in indices:
        encoded[i] = new
    changes.append((old, new, indices))

Note the "list comprehension", which is a short-hand version of the following:

indices = []
for i, c in enumerate(encoded):
    if c == old:
        indices.append(i)

Now you can easily reverse the operations, even if choose was already in encoded:

for old, new, indices in changes:
    print("Replaced '{0}' with '{1}'".format(old, new))
    undo = "Would you like to undo that change (y/n)? ".lower()
    if undo == "y":
        for i in indices:
            encoded[i] = old
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top