codewars——First non-repeating character

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 ""
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值