The problem: find and return the first nonrepeating character in a string, if the string does not have a nonrepeating character return an empty string. For purposes of finding the nonrepeating character it's case insensitive so 't' and 'T' appearing in the string would imply that that 't' and 'T' are not candidates for a nonrepeating character. When you return the character you must return it as its original case.
My Solution:
def non_repeat(_str):
counts = {}
for pos, letter in enumerate(_str.lower()):
if letter not in counts:
counts[letter] = (0, pos)
incr_val = counts[letter][0] + 1
counts[letter] = (incr_val, pos)
for letter in _str.lower():
if counts[letter][0] == 1:
return _str[counts[letter][1]]
return ''
How can I improve the readability of my solution? In particular, I don't like:
counts[letter][0]
because the 0 index is a bit ambiguous.- calculating the incremented value as another line,
incr_val
; it'd be nice to do the incrementing and updating of the dict in one line.
Anything else you could make more readable? I should add that I'm aware of collections.Counter
; for this solution I'd like to avoid using it.
collections.Counter
? \$\endgroup\$ – Gareth Rees Dec 13 '18 at 19:50