def duplicate_count(s):
return len([c for c in set(s.lower()) if s.lower().count(c)>1])
我很難理解這段代碼的工作原理。我正在做一個codewars挑戰,以返回字符串中重複元素的數量。我很難找出這個精簡代碼
例如。 Asasd - > 2
我想出了我自己的暗示,但我無法真正理解這段代碼的作用。如果有人可以指出我的方向,它將不勝感激:)
def duplicate_count(s):
return len([c for c in set(s.lower()) if s.lower().count(c)>1])
我很難理解這段代碼的工作原理。我正在做一個codewars挑戰,以返回字符串中重複元素的數量。我很難找出這個精簡代碼
例如。 Asasd - > 2
我想出了我自己的暗示,但我無法真正理解這段代碼的作用。如果有人可以指出我的方向,它將不勝感激:)
它返回重複字符的數量(如函數名稱暗示) set(s.lower())給出字符串中的唯一字母。 杉木在本組中的每個字母,如果該信字符串中的出現次數大於1,存在重複,因此計數被遞增
s="aaabbcdd"
print(set(s.lower()))
#{'a', 'b', 'd', 'c'}
count=0
for c in set(s.lower()):
if(s.lower().count(c)>1):
print("charcter with more than 1 occurence : ",c)
print("\toccurences : ",s.lower().count(c))
count=count+1
print("count : ",count)
# charcter with more than 1 occurence : a
# occurences : 3
# charcter with more than 1 occurence : d
# occurences : 2
# charcter with more than 1 occurence : b
# occurences : 2
# count : 3
def duplicate_count(s):
result = []
for c in set(s.lower()):
if s.lower().count(c) > 1:
result.append(c)
return len(result)
是這樣的,首先,一個的解決這個問題的效率非常低。但是,讓我們來分析一下:
s.lower()
將所有字符轉換成字符串爲小寫:
In [1]: s = "Hello, WORLD"
In [2]: s.lower()
Out[2]: 'hello, world'
set(s.lower())
將一個(請務必閱讀有關集)的set創建字符串中的字符 - 刪除所有重複項:
In [3]: set(s.lower())
Out[3]: {' ', ',', 'd', 'e', 'h', 'l', 'o', 'r', 'w'}
for c in set(s.lower())
迭代我們創建的集合中的每個字符都是if s.lower().count(c)>1
的情況下應用此項。 count(c)
這裏將計算c
在字符串中出現的次數。 >1
幫助我們留下字符串中遇到超過1次的字符[c for c in set(s.lower()) if s.lower().count(c)>1]
是被稱爲list comprehension。這基本上是創建列表的簡短方式。在這裏,我們創建一個字符串列表,不止一次出現在一個字符串中。退房this topic about how to verbalize and read the list comprehensions。len()
然後就得到我們的名單總結的長度,你遍歷一個給定的字符串中唯一的字符和計數這其中發生在一個字符串超過一次。
set(s.lower()) # gives unique elements in lower case
和
s.lower().count(c)>1 #checks if an element shows up more than once
總而言之函數發現在一個字符串不是唯一的元素數量,忽略大小寫。
我相信使用collections.Counter
更高效:
In [7]: from collections import Counter
In [8]: sum(v > 1 for v in Counter("Aabcc".lower()).values())
Out[8]: 2
可能值得用''Aabcc'替換'(x.lower()for x'in'Aabcc')'.lower()' –
@JaredGoguen好點,固定的。 – Akavall
閱讀有關 –
你不知道自己的代碼的文檔列表理解? –