与えられたサイズのグループで配列を逆にするPythonプログラム?
ここでは、1つのユーザー入力配列とグループのサイズを使用します。そして、グループのサイズに基づいてサブ配列を作成し、それを逆にします。グループ(p)のサイズが配列(n)のサイズの倍数でない場合、最後のグループは残りのk要素未満になり、残りのすべての要素を反転します。 p =1の場合、配列は変更されません。p> =1の場合、配列内のすべての要素を逆にします。
アルゴリズム
Revarray(A,n,p)
/* A is an integer Array, n is the size of an array and every sub-array of size p starting from the beginning of the array and reverse it.*/
Step 1: i is the loop control variable which is initialized by 0.
Step 2: using while loop check i is less than n or not. If true
Step 2.1: L=i /* Left sub array
Step 2.2: R=min (i+p-1, n-1) /*Right sub array
Step 2.3: Using while loop check L is than R or not. If yes
Step 2.3.1: swap left sub array A (L) and Right Sub Array A(R).
Step 2.3.2: L is incremented by 1.
Step 2.3.3: R is stepping backward one step at a time.
Step 2.4: End While
Step 2.5: i=i+p
Step 3: End While
Step 4: Stop
サンプルコード
#reverse of an array in groups of given size
def arrayreverse(A, n, p):
i = 0
while(i<n):
L = i
R = min(i + p - 1, n - 1)
while (L < R):
A[L], A[R] = A[R], A[L]
L+= 1;
R-+1
i+= p
# Driver code
#Insert data in an array
A=list()
n=int(input("Enter the size of the array ::"))
print("Enter the number ::")
for i in range(int(n)):
k=int(input(""))
A.append(int(k))
p=int(input("Enter the size of the group ::"))
arrayreverse(A, n, p)
for i in range(0, n):
print(A[i], end =" ")
出力
Enter the size of the array ::6 Enter the number :: 11 22 33 44 55 66 Enter the size of the group ::2 22 11 44 33 66 55
-
配列内の反転をカウントするPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −リストが表示されます。必要な反転をカウントして表示する必要があります。 反転カウントは、配列をソートするために必要なステップ数をカウントすることによって取得されます。 次に、以下の実装のソリューションを見てみましょう- 例 # count def InvCount(arr, n): inv_count = 0 for i in range(n): for j in range(i + 1, n):
-
配列ローテーション用のPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −テキストとパターンが与えられた場合、パターンのすべての出現とその順列(またはアナグラム)をテキストで印刷する必要があります。 次に、以下の実装のソリューションを見てみましょう- 例 # maximum value MAX = 300 # compare def compare(arr1, arr2): for i in range(MAX): if arr1[i] != arr2[i]: &nbs