Predict the output
What does this print?
text = "abacdc"
last = {ch: i for i, ch in enumerate(text)}
print(last, [last[ch] for ch in text])Choose an answer, then open Show answer below to check it.
Show answer
Answer: A {'a': 2, 'b': 1, 'c': 5, 'd': 4} [2, 1, 2, 5, 4, 5]
Right: a later index overwrites an earlier one, leaving each letter's last position.
With these last positions, the piece starting at 'a' must run to index 2, and the next must run to index 5: lengths [3, 3].
Why not the others?
- B {'a': 0, 'b': 1, 'c': 3, 'd': 4} [0, 1, 0, 3, 4, 3]. Those are first positions; the dict keeps the last assignment.
- C {'a': 2, 'b': 1, 'c': 5, 'd': 4} [2, 1, 2, 3, 4, 5]. Each list entry looks up the letter's last index, so both c's give 5.