我们必须检查在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!