Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string.For example, if given the input ‘stress’, the function should return ‘t’, since the letter t only occurs once in the string, and occurs first in the string.As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input ‘sTreSS’ should return ‘T’.If a string contains all repeating characters, it should return an empty string ("") or None – see sample tests.
Test.describe(‘Basic Tests’)
Test.it(‘should handle simple tests’)
Test.assert_equals(first_non_repeating_letter(‘a’), ‘a’)
Test.assert_equals(first_non_repeating_letter(‘stress’), ‘t’)
Test.assert_equals(first_non_repeating_letter(‘moonmen’), ‘e’)
Test.it(‘should handle empty strings’)
Test.assert_equals(first_non_repeating_letter(’’), ‘’)
Test.it(‘should handle all repeating strings’)
Test.assert_equals(first_non_repeating_letter(‘abba’), ‘’)
Test.assert_equals(first_non_repeating_letter(‘aa’), ‘’)
Test.it(‘should handle odd characters’)
Test.assert_equals(first_non_repeating_letter(’><#><’), ‘#’)
Test.assert_equals(first_non_repeating_letter(‘hello world, eh?’), ‘w’)
Test.it(‘should handle letter cases’)
Test.assert_equals(first_non_repeating_letter(‘sTreSS’), ‘T’)
Test.assert_equals(first_non_repeating_letter(‘Go hang a salami, I’m a lasagna hog!’), ‘,’)
我的思路
我的思路就是直接先把所有的字符串大写化或者小写化,挨个遍历,第一个元素取值是1的就可以输出了。遍历时候用原字符串,避免出现输出大小写混乱的问题。
涉及到一部分asc码的知识。
def first_non_repeating_letter(string):
s1 = string.lower()
for letter in string:
if letter == " ":
continue
if 97 <= ord(letter) <= 122:
if s1.count(letter) == 1:
return letter
if 65 <= ord(letter) <= 90:
if s1.count(chr(ord(letter)+32)) == 1:
return letter
else:
if s1.count(letter) == 1:
return letter
return ""