当前位置: 首页 > 编程笔记 >

检查字符串的两半在Python中是否具有相同的字符集

狄飞尘
2023-03-14
本文向大家介绍检查字符串的两半在Python中是否具有相同的字符集,包括了检查字符串的两半在Python中是否具有相同的字符集的使用技巧和注意事项,需要的朋友参考一下

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

结论

 类似资料:
  • "给定两个字符串s和t,编写一个函数来检查s是否包含t的所有字符(顺序与字符串t相同)。返回true或false。递归不一定。这是我用java写的代码片段。问题是输入: string1="st3h5irteuyarh!"和string2="shrey"它应该返回TRUE,但它返回FALSE。那是为什么?"

  • 问题内容: 如何检查是否是那里的? 我想分配给是否有结果,否则。 我当前的代码是: 问题答案:

  • 本文向大家介绍C ++中的元字符串(检查一个字符串交换后两个字符串是否可以相同),包括了C ++中的元字符串(检查一个字符串交换后两个字符串是否可以相同)的使用技巧和注意事项,需要的朋友参考一下 在本节中,我们将看到如何检查两个字符串是否为元字符串。元字符串是非常相似的那些字符串。如果我们在一个字符串中交换两个元素,那么它将与另一个字符串匹配。假设两个字符串是“ HELLO”和“ OELLH”,则

  • 所以基本上我必须检查另一个字符串是否有相同顺序的相同字符。 所以如果血液中的字母和冠状病毒的顺序相同,就像第二个一样,我必须打印阳性。在Java如何做到这一点?提前道谢。

  • 问题内容: 我正在使用Python v2,并且试图找出是否可以判断字符串中是否包含单词。 我发现了一些有关识别单词是否在字符串中的信息-使用.find,但是有一种方法可以执行IF语句。我想要以下内容: 谢谢你的帮助。 问题答案: 出什么问题了:

  • 本文向大家介绍检查字符串在Python中是否有效JSON,包括了检查字符串在Python中是否有效JSON的使用技巧和注意事项,需要的朋友参考一下 JSON是一种文本格式,用于在各种计算机程序之间轻松交换数据。它具有Python可以验证的特定格式。在本文中,我们将考虑一个字符串,并使用JSON模块验证该字符串是否表示有效的JSON格式。 创建JSON对象 json模块具有称为load的方法。它加载