在 Python 中檢查字串的兩個半部分是否具有相同的字元集


我們必須檢查字串的兩個半部分是否具有相同的字元集,且字元頻率必須相同。如果字串的長度是奇數,則忽略中間部分,並檢查剩餘字元。請遵循以下步驟為程式編寫程式碼。

演算法

1. Initialize a string.
2. Initialize an empty dictionary variable alphabets.
3. Initialize a variable mid with length / 2.
4. Write a loop until mid element.
   4.1. Initialize the corresponding dictionary item by alphabets[char] with one if it's not
initialized.
   4.2. If it's already initialized, increment the count by 1.
5. Run the loop from the mid element to the last item.
   5.1. Check if the char is in the dictionary or not.
      5.1.1. Decrement the count of char by one if it's in the dictionary
6. Run a loop over the dictionary alphabets.
   6.1. If you find any item with more than 0 value.
      6.1.1. Print **No!**.
   6.2. Else print Yes!

讓我們編寫程式碼。

示例

## initializing the string
string = "aabccbaa"
## initializing an empty string
alphabets = {}
## initializing the mid variable
mid = len(string) // 2
## loop to count the frequency of char in the first half
for i in range(mid):
   ## setting the value of char count to 1 if it's not in the dictionary
   if not alphabets.get(string[i], 0):
      alphabets[string[i]] = 1
   else:
      ## incrementing the count of char by 1 if it's already initialized
      alphabets[string[i]] += 1
## loop to decrement the count of char by 1 if it's present in second half of the string
for i in range(len(string) - 1, mid - 1, -1):
   ## checking whether the char is in second half or not
   if alphabets.get(string[i], 0):
   ## if it's present, decrementing the count by 1
   alphabets[string[i]] -= 1
## initializing a flag variable for the track
flag = 1
## loop to check the values after decrementing
for i in alphabets.values():
## checking for zeroes
if i != 0:
   ## if it's not zero breaking the loop and printing No!
   print("No!")
   ## setting 0 for track
   flag = 0
   break
## if flag value still 1 then, it's Yes!
if flag == 1:
   ## printing Yes!
   print("Yes!")

輸出

如果執行上述程式,你將得到以下輸出。

Yes!

結論

如果你對教程有任何疑問,請在評論部分中提出。

更新時間: 2019 年 10 月 23 日

99 次瀏覽

開啟你的 職業 生涯

透過完成課程獲得認證

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