指定された文字列からすべての可能な有効なIDアドレスを生成するPythonプログラム
文字列が与えられます。文字列には数字のみが含まれます。私たちのタスクは、考えられるすべての有効なIPアドレスの組み合わせを確認することです。
ここでは、最初に文字列の長さを確認してから、「。」で分割します。次に、「。」のさまざまな組み合わせを確認します。
例
Input : "255011123222" It's not a valid IP address. Input : 255011345890 Valid IP address is 255.011.123.222
アルゴリズム
Step 1: First check the length of the string. Step 2: Split the string by ".". We will place 3 dots in the given string. W, X, Y, and Z are numbers from 0-255 the numbers cannot be 0 prefixed unless they are 0. Step 3: Generating different combinations. Step 4: Check for the validity of combination.
サンプルコード
# Python code to check valid possible IP
# Function checks wheather IP digits
# are valid or not.
def ipvalid(ip):
# Spliting by "."
ip = ip.split(".")
# Checking for the corner cases
for i in ip:
if len(i) > 3 or int(i) < 0 or int(i) > 255:
return False
if len(i) > 1 and int(i) == 0:
return False
if len(i) > 1 and int(i) != 0 and i[0] == '0':
return False
return True
# Function converts string to IP address
def ipconvert(A):
con = len(A)
# Check for string size
if con > 12:
return []
newip = A
l = []
# Generating different combinations.
for i in range(1, con - 2):
for j in range(i + 1, con - 1):
for k in range(j + 1, con):
newip = newip[:k] + "." + newip[k:]
newip = newip[:j] + "." + newip[j:]
newip = newip[:i] + "." + newip[i:]
# Check for the validity of combination
if ipvalid(newip):
l.append(newip)
newip = A
return l
# Driver code
A = input("Enter IP address")
print(ipconvert(A))
出力
Enter IP address25525522134 ['255.255.22.134', '255.255.221.34']
-
Pythonで可能なすべての有効なパスから最大スコアを見つけるプログラム
2つの配列nums1とnums2があるとします。有効なパスは次のように定義されます- トラバースするnums1またはnums2を選択します(インデックス0から)。 配列を左から右にトラバースします。 ここで、nums1とnums2に存在する値を移動している場合は、他の配列へのパスを変更できます。ここで、スコアは有効なパスの一意の値の合計です。考えられるすべての有効なパスから取得できる最大スコアを見つける必要があります。答えが大きすぎる場合は、10 ^ 9+7を法とする結果を返します。 したがって、入力がnums1 =[3,5,6,9,11] nums2 =[5,7,9,10
-
指定された文字列のすべての順列を出力するPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −文字列の可能なすべての順列を表示するために必要な文字列が与えられます。 次に、以下の実装のソリューションを見てみましょう- 例 # conversion def toString(List): return ''.join(List) # permutations def permute(a, l, r): if l == r: print (toString(a)) e