Python – 檢查字串中所有字元的頻率是否不同
在本文中,我們將學習如何查詢給定字串中每個字元的頻率,然後檢視給定字串中是否存在兩個或多個字元具有相同頻率。我們將分兩步完成此操作。在第一個程式中,我們將只找出每個字元的頻率。
每個字元的頻率
在這裡,我們找到給定輸入字串中每個字元的頻率。我們宣告一個空字典,然後新增每個字元作為字串。我們還為每個字元分配鍵,以建立字典所需的鍵值對。
示例
in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
if k in dic1.keys():
dic1[k]+=1
else:
dic1[k]=1
print(dic1)
for k in dic1.keys():
print(k, " repeats ",dic1[k]," time's")輸出
執行上述程式碼得到以下結果:
{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
S repeats 1 time's
h repeats 2 time's
e repeats 4 time's
repeats 3 time's
s repeats 5 time's
l repeats 4 time's
a repeats 1 time's每個字元的唯一頻率
接下來,我們擴充套件上述程式以找出每個唯一字元的頻率。如果頻率的唯一值大於一,則我們得出結論:並非所有字元都具有相同的頻率。
示例
in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
if k in dic1.keys():
dic1[k]+=1
else:
dic1[k]=1
print(dic1)
u_value = set( val for udic in dic1 for val in (dic1.values()))
print("Number of Unique frequencies: ",len(u_value))
if len(u_value) == 1:
print("All character have same frequiency")
else:
print("The characters have different frequencies.")輸出
執行上述程式碼得到以下結果:
{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
Number of Unique frequencies: 5
The characters have different frequencies.
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP