在 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 次浏览

开启你的 职业 生涯

通过完成课程获得认证

开始学习
广告