41. First unique character
Write a function first_unique(text) that takes a string of lower-case letters and returns the index of the first
letter that appears exactly once in it. Indexes count from 0. If every letter appears more than once, or the text is
empty, return -1.
"First" means first in the text: in "swiss", w and i both appear once, and w comes first.
Example 1
text = "swiss"1Example 2
text = "level"2Example 3
text = "aabb"-1Constraints
texthas 0 to 100 characters, each a lower-case letteratoz.
Submit also runs 9 more tests you can't see.
Practises Dictionaries (lesson 11).
- Count every letter first, in a dictionary:
counts[ch] = counts.get(ch, 0) + 1adds one, starting from 0 for a new letter. - Then go through the text again, in order, with
for i, ch in enumerate(text):, which gives each index and its letter. - Return the first
iwhose letter has a count of 1. If the loop ends without one, return -1: that covers the empty text too.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def first_unique(text):
"""Find the first letter that appears only once.
text: str, lower-case letters; may be empty
Returns: int, the index of that letter, or -1 if there
is none
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.