Okay.
Code:
d = {'a':'a','g':'c','c':'b'} # key is actually talking about a triple 'aaa':'a'
while True:
stuff = raw_input("string: ").lower()
if stuff == "exit":
break
s = ""
for triple in range(0,len(stuff),3):
decoded_str = d.get(stuff[triple],"error")
if decoded_str == "error":
s = "error"
break
s += decoded_str
if s != "error":
print s.upper()
else:
print "One of the triples in your code could not be decoded."
Line 1 makes d, a new dictionary. This dictionary has three keys: a, g, and c. Their values are a, c, b, respectively. They're all strings. The keys are the code letters, and the values are the decoded letters.
Line 3 is the start of the infinite loop.
Line 4 gets the code (let's take "AAAGGGCCC") and the .lower() on the end there stores the string in all lowercase. So now "stuff" contains "aaagggccc."
Lines 5 and 6 contain a check. If you type in "exit," it ends the program.
Line 7 creates an empty string 's'. This will be the result of the decoding.
The for loop on lines 8-13 decodes your message. So here was my thought process:
- The code is going to have triples of letters, so we only need to check every third letter.
So the for loop starts at 0 and goes to the len of stuff by threes. I used this number as the index of the string "stuff."
Line 9 is simple. The get() command for dictionaries retrieves the value, otherwise it sets the variable at a default value. So here, we get stuff[triple] (triple is the number assigned by the for loop) from the dictionary (we're retrieving key stuff[triple]). If stuff[triple] is not in the dictionary, it returns the default value, which I have set to "error." This is the syntax for get(): var = dictionary.get(key,default). The next several lines end the while loop if there was an error. If there is no error, the decoded value is added to the s string.
This is what happens for stuff = aaagggccc.
First time through the loop, triple = 0.
stuff[0] now equals a
Line 9 retrieves the value of key 'a' in dictionary d. That value is 'a'. (In the dictionary, 'a':'a')
No error... decoded_str ('a' right now) is added to s.
Next time around the loop... the for loop goes by 3, so now triple = 3
stuff[3] now equals g... it gets key 'g' from dictionary d. The value is 'c'.
No error... 'c' is added to s.
Now s equals "ac"
Third time around... triple = 6
stuff[6] = c
After going through the loop, the loops is done.
s = "acb"
There was never an error, so Line 15 runs and prints s in uppercase (that's what .upper() does)
So we get "ACB"
Let's say we put in "HHHAAABBB."
When it the for loop runs for the first time, triple set to 0, so stuff[0] = h. When it looks for key 'h' and finds none, "decoded_str" is set to "error". The condition on Line 10 is True, so s is set to "error" and the for loop ends with the break statement. The condition on Line 14 is false because s IS "error", so Line 17 prints.
I hope that helped. Sorry my explanation is so lengthy.