iT邦幫忙

2022 iThome 鐵人賽

DAY 27
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 27

[Day27] Codewars >>> First non-repeating character (Python)

  • 分享至 

  • xImage
  •  

題目(5kyu):

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.

解題思路

題目理解:設計一函數,代入字串string後,返還第一個不重複出現於字串中的字元。另外英文大寫被視為相同字元,但返還時須返還首字母的正確大小寫形式。

def first_non_repeating_letter(string:str):
    """返還第一個於string中不重複的字元"""
    #因不計大小寫差異,故先將string皆轉換為小寫形式
    str_lower = string.lower()
    for i in range(len(str_lower)):
        #依序檢查字串中各個字元的數量,若發現數量為1的字元即返還
        if str_lower.count(str_lower[i]) == 1:
            #注意返還時索引需使用在原字串string上,來取得原本的字元的大小寫形式
            return string[i]
    return ""

上一篇
[Day26] Codewars >>> Pete, the baker (Python)
下一篇
[Day28] Codewars >>> Consecutive k-Primes (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言