2つの数値の2進表現がアナグラムであるかどうかをチェックするPythonプログラム。
与えられた2つの数字。私たちの仕事は、それらがバイナリ表現でお互いのアナグラムであるかどうかを確認することです。カウンター(反復可能)メソッドと辞書比較を使用して、Pythonでこの問題をすばやく解決できます。
例
Input: a = 8, b = 16 Output : Yes Binary representations of both numbers have same 0s and 1s.
アルゴリズム
Step 1 : Given two numbers. Step 2 : Convert both number into its binary using bin() function and remove first two characters because of bin(). Step 3 : Since binary representation of both numbers could differ in length so we will append zeroes in start of shorter string to make both string of equal length. Step 4 : Compare both dictionaries, if value of 0’s and 1’s in both dictionaries are equal then binary representations of two numbers are anagram otherwise not. Binary representations into dictionary.
サンプルコード
# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def anagramoftwonumber(p1,p2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
#'0b' as prefix in output string
bno1 = bin(p1)[2:]
bno2 = bin(p2)[2:]
# append zeros in shorter string
zeros = abs(len(bno1)-len(bno2))
if (len(bno1)>len(bno2)):
bno2 = zeros * '0' + bno2
else:
bno1 = zeros * '0' + bno1
# convert binary representations
# into dictionary
dict1 = Counter(bno1)
dict2 = Counter(bno2)
# compare both dictionaries
if dict1 == dict2:
print(p1, p2 ,"are two anagram number")
else:
print(p1 , p2 ,"are not anagram number")
# Driver program
if __name__ == "__main__":
n1 = int(input("Enter First number ::>"))
n2 = int(input("Enter Second number ::>"))
anagramoftwonumber(n1,n2)
出力
Enter First number ::>8 Enter Second number ::>16 8 16 are two anagram number Enter First number ::>3 Enter Second number ::>2 3 2 are not anagram number
-
素数をチェックするPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −数が与えられているので、与えられた数が素数であるかどうかを確認する必要があります。 1より大きい特定の正の数で、1以外の要素はなく、その数自体は素数と呼ばれます。 2、3、5、7などは他の要素がないため素数です。 以下のこのプログラムでは、素数または非素数の性質について番号がチェックされます。 1以下の数は素数とは言えません。したがって、数値が1より大きい場合にのみ反復します。 ここで、その数が2から(num-1 // 2)の範囲の任意の数で正確に割り切れるかどうかを確認します。指定された範囲内に何ら
-
アームストロング数をチェックするPythonプログラム
この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 整数nが与えられた場合、与えられた整数がアームストロング数であることを確認する必要があります。 正の整数は、次の場合、n次のアームストロング数と呼ばれます abcd... = a^n + b^n + c^n + d^n + … ここでは、3桁のアームストロング数、つまり3桁のブルートフォースアプローチについて説明します。 オーダーnのアームストロング番号を確認するには、3を行番号7の対応するオーダー値に置き換える必要があります。 それでは、実装を見てみましょう- 例