檢查字串兩半是否具有相同字元集的 Python 程式。


給定一個字串,我們的任務是檢查字串的兩半是否具有相同的字元集。為解決此問題,我們首先將字串從中間分開,這樣我們得到兩半,現在我們檢查每一半是否具有相同的字元集。如果字串的長度不偶數,則忽略中間元素並檢查其餘部分。

演算法

Step 1: Given a string.
Step 2: Break the input string into two parts.
Step 3: Then convert both parts into a dictionary using Counter(iterator) method and each dictionary contains its character as key and frequency as value.
Step 4: Now compare these two dictionaries. Here we use == operator. First we checks keys of both dictionaries are same or not,
then checks for values of each key. If both cases are true then two halves have the same set of characters.

示例程式碼

from collections import Counter
def checkhalves(input):
   length = len(input)
   if (length % 2 != 0):
      first = input[0:int(length / 2)]
      second = input[(int(length / 2)) + 1:]
   else:
      first = input[0:int(length / 2)]
      second = input[int(length / 2):]
   if Counter(first) == Counter(second):
      print ("Both halves are same")
   else:
      print ("Both halves are not same ")
# Driver program
if __name__ == "__main__":
input = input("Enter The String")
checkhalves(input)

輸出

Enter The String abba
Both halves are same

更新於: 23-6月-2020

194 次瀏覽

開始你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.