使用 collections.Counter() 在 Python 程式中檢查字謎


如果兩個字串的字元相同,即使順序不同,則這兩個字串互為字謎。在本教程中,我們將使用collections.Counter()方法來檢查 Python 中的字謎。

Input:
string_one = "cat"
string_two = "tac"
Ouput:
True

collections.Counter()

collection.Counter()返回一個字典,其中包含字串中每個字元的頻率。Counter物件具有不同的方法來查詢最常見元素、唯一元素、計數等。

讓我們看一個例子。

例子

# importing the collections module
import collections
# creating Counter object
counter = collections.Counter("Hafeez")
# printing the counter
print(counter)
# displaying most common character from the string
print("\nMost common character")
print(counter.most_common(1))

輸出

如果您執行以上程式,您將得到以下結果。

Counter({'e': 2, 'H': 1, 'a': 1, 'f': 1, 'z': 1})
Most common character
[('e', 2)]

檢查字謎的步驟。

演算法

1. Initialise two strings.
2. Create collections.Counter() objects for both strings.
3. If both of the objects are equal.
   3.1. Print True
4. Else print False

讓我們看一個例子。

例子

# importing the collections module
import collections
# initializing strings
string_one = "cat"
string_two = "atc"
# checking the Counter objects of both strings
if collections.Counter(string_one) == collections.Counter(string_two):
   # they are equal so, printing True
   print(True)
else:
   # they are not equal so, printing False
   print(False)

輸出

如果您執行以上程式,您將得到以下結果。

True

結論

如果您在學習本教程時遇到任何問題,請在評論區指出。

已於以下時間更新: 04-11-2019

146 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.