Count the number of Duplicates
Write a function that will return the count of distinct case-insensitive alphabetic >characters and numeric digits that occur more than once in the input string. The input >string can be assumed to contain only alphabets (both uppercase and lowercase) and >numeric digits.Example
"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (b
andB
)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice
題目理解:輸入字串text,返還其重複字元的種類數量。其中字母大小寫差異會被視作同一種字母,可假設text僅會輸入字母&數字。
def duplicate_count(text):
#使用string.upper(),將字母皆轉換為大寫保存
string = text.upper()
reslut = 0
#使用set()來獲取所有字元種類,利用count()檢查字元在字串中的數量
for character in set(string):
if string.count(character)>1:
reslut += 1
return reslut
由於字母大小寫需視為同一存在,故可使用upper()或lower()來統一字串大小寫。
可以留意到字串中的數字並不會因此被改變或使程式出現錯誤,同理可用在其他特殊字元上。
print("abcABC_123+=&".upper()) #輸出:ABCABC_123+=&
print("abcABC_123+=&".lower()) #輸出:abcabc_123+=&
此特性可以配合lower()用來刪選出其他非字母字元,如下示例:
def string_del_english_alphabet(text):
reslut = ""
for character in text :
if character.upper() == character.lower():
reslut += character
return reslut
print(string_del_english_alphabet("abcABC_123+=&")) #輸出:_123+=&