Python
 Computer >> コンピューター >  >> プログラミング >> Python

文字列の両方の半分がPythonで同じ文字セットを持っているかどうかを確認します


Python で、文字列の2つの半分が同じ文字セットを持っているかどうかを確認する必要があります 。 2つの半分の文字の頻度は同じでなければなりません。文字列の長さが奇数の場合は、中央を無視して残りの文字を確認してください。以下の手順に従って、プログラムのコードを記述します。

アルゴリズム

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!

結論

チュートリアルについて疑問がある場合は、コメントセクションにその旨を記載してください。


  1. 指定された文字列がパングラムであるかどうかを確認するPythonプログラム

    この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 文字列入力が与えられた場合、その文字列がパングラムであるかどうかを確認するPythonプログラムを生成する必要があります。 パングラムは、英語のアルファベットコレクションのすべての文字を含む文/一連の単語です。 では、問題を解決する方法を見てみましょう 入力文字列に存在する各文字が、手動で宣言するアルファベットセットに属しているかどうかをチェックするループを使用します。 上記のアプローチの実装は、-によって与えられます。 例 import string def ispangram

  2. 文字列にすべての一意の文字が含まれているかどうかを確認するPythonプログラム

    この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 sring入力が与えられた場合、文字列にすべての一意の文字が含まれているかどうかを確認する必要があります。 アプローチ ブール値の配列を作成します。ここで、インデックスiの変数フラグは、アルファベットの文字iが文字列に含まれているかどうかを示します。 この文字に2回目に遭遇したとき、文字列文字は一意ではなくなったため、すぐにfalseを返すことができます。 文字列の長さがアルファベットに表示される一意の文字数の値を超える場合も、falseを返すことができます。 文