1636586580
指定された文字列のすべての順列を出力するPythonプログラム。このPythonチュートリアルでは、組み込みモジュールを使用し、モジュールを使用せずに、Pythonで特定の文字列の順列を見つけて出力する2つの方法を紹介します。
私たちがあなたと共有する前に、Pythonで与えられた文字列のすべての順列を見つけるプログラム。このモジュールは特定の文字列のすべての順列を見つけるのに役立つため、Pythonitertoolsモジュールについて知っておく必要があります。
順列:-ご存知のとおり、順列は、グループの要素を整理する方法、または別のグループを形成する特定の順序または順序で設定する方法です。
次の手順を使用して、指定された文字列のすべての順列を出力するPythonプログラムを作成します。
# import the module
from itertools import permutations
# input the sting
str=input('Enter a string: ')
A=[]
b=[]
p=permutations(str)
for k in list(p):
A.append(list(k))
for j in A:
r=''.join(str(l) for l in j)
b.append(r)
print('Number of all permutations: ',len(b))
print('All permutations are: ')
print(b)
プログラムの実行後、出力は次のようになります。
Enter a string: cba
Number of all permutations: 21
All permutations are:
['cba', 'cba', 'cab', 'cba', 'cab', 'bca', 'cba', 'cab', 'bca', 'bac', 'cba', 'cab', 'bca', 'bac', 'acb', 'cba', 'cab', 'bca', 'bac', 'acb', 'abc']
# conversion
def toString(List):
return ''.join(List)
# find all permutations
def permuteFunc(a, l, r):
if l == r:
print (toString(a))
else:
for i in range(l, r + 1):
a[l], a[i] = a[i], a[l]
permuteFunc(a, l + 1, r)
a[l], a[i] = a[i], a[l] # backtracking
# main
str=input('Enter a string: ')
n = len(str)
a = list(str)
print("The possible permutations are:",end="\n")
permuteFunc(a, 0, n-1)
プログラムの実行後、出力は次のようになります。
Enter a string: abc
The possible permutations are:
abc
acb
bac
bca
cba
cab
リンク: https://www.tutsmake.com/print-all-permutations-of-given-string-in-python/
1636586580
指定された文字列のすべての順列を出力するPythonプログラム。このPythonチュートリアルでは、組み込みモジュールを使用し、モジュールを使用せずに、Pythonで特定の文字列の順列を見つけて出力する2つの方法を紹介します。
私たちがあなたと共有する前に、Pythonで与えられた文字列のすべての順列を見つけるプログラム。このモジュールは特定の文字列のすべての順列を見つけるのに役立つため、Pythonitertoolsモジュールについて知っておく必要があります。
順列:-ご存知のとおり、順列は、グループの要素を整理する方法、または別のグループを形成する特定の順序または順序で設定する方法です。
次の手順を使用して、指定された文字列のすべての順列を出力するPythonプログラムを作成します。
# import the module
from itertools import permutations
# input the sting
str=input('Enter a string: ')
A=[]
b=[]
p=permutations(str)
for k in list(p):
A.append(list(k))
for j in A:
r=''.join(str(l) for l in j)
b.append(r)
print('Number of all permutations: ',len(b))
print('All permutations are: ')
print(b)
プログラムの実行後、出力は次のようになります。
Enter a string: cba
Number of all permutations: 21
All permutations are:
['cba', 'cba', 'cab', 'cba', 'cab', 'bca', 'cba', 'cab', 'bca', 'bac', 'cba', 'cab', 'bca', 'bac', 'acb', 'cba', 'cab', 'bca', 'bac', 'acb', 'abc']
# conversion
def toString(List):
return ''.join(List)
# find all permutations
def permuteFunc(a, l, r):
if l == r:
print (toString(a))
else:
for i in range(l, r + 1):
a[l], a[i] = a[i], a[l]
permuteFunc(a, l + 1, r)
a[l], a[i] = a[i], a[l] # backtracking
# main
str=input('Enter a string: ')
n = len(str)
a = list(str)
print("The possible permutations are:",end="\n")
permuteFunc(a, 0, n-1)
プログラムの実行後、出力は次のようになります。
Enter a string: abc
The possible permutations are:
abc
acb
bac
bca
cba
cab
リンク: https://www.tutsmake.com/print-all-permutations-of-given-string-in-python/