4
\$\begingroup\$

I wrote a solution to first-unique-character-in-a-string:

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

If there is better way for me to build the dictionary seems? and find the first key when value is 1 and index is lowest?

def firstUniqChar(string) -> int:
 seems = dict()
 index = len(string)
 c = ''
 for i, char in string:
 if char not in seems:
 seems.setdefault(char, (i,1))
 else:
 seems[char] = (seems[char][0], seems[char][1] + 1)
 for k, value in seems.items():
 if value[1] == 1 and value[0] < index:
 index = value[0]
 c = k
 return index if c else -1
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Oct 31, 2018 at 0:34
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

The code is too convoluted and unreadable for such a simple task

  • seems is a dictionary where the values are (first index, occurrences) pairs. That's an unconventional data structure. You'd be better off with two separate dictionaries.
  • seems is a weird variable name. What does it mean, anyway?
  • Why is the index = len(string) statement necessary?

This solution is less cluttered, and more clearly expresses the idea that you are counting the characters, then finding the first unique one.

from collections import Counter
def first_uniq_char(s):
 counts = Counter(s)
 return next((i for i, c in enumerate(s) if counts[c] == 1), -1)
answered Oct 31, 2018 at 1:31
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.