用遞迴按照詞典排序列印字串所有排列的 Python 程式
當需要使用遞迴按照詞典排序列印字串的所有排列,定義一個方法,使用 ‘for’ 迴圈迭代元素序列,然後使用 ‘join’ 方法連線元素。
以下是對此的演示 −
示例
from math import factorial
def lexicographic_permutation_order(s):
my_sequence = list(s)
for _ in range(factorial(len(my_sequence))):
print(''.join(my_sequence))
next = next_in_permutation(my_sequence)
if next is None:
my_sequence.reverse()
else:
my_sequence = next
def next_in_permutation(my_sequence):
if len(my_sequence) == 0:
return None
next = next_in_permutation(my_sequence[1:])
if next is None:
my_sequence[1:] = reversed(my_sequence[1:])
q = 1
while q < len(my_sequence) and my_sequence[0] > my_sequence[q]:
q += 1
if q == len(my_sequence):
return None
my_sequence[0], my_sequence[q] = my_sequence[q], my_sequence[0]
return my_sequence
else:
return [my_sequence[0]] + next
my_input = input('Enter a string : ')
print("The string is :")
print(my_input)
print("The method is being called...")
lexicographic_permutation_order(my_input)輸出
Enter a string : hey The string is : hey The method is being called... hey hye yeh yhe hey hye
說明
匯入所需的包。
定義了一個名為 ‘lexicographic_permutation_order’ 的方法,用於查詢元素的詞典排序。
‘next_in_permutation’ 方法用於確定字串中的下一個排列。
使用者輸入一個字串,並顯示在控制檯上。
透過將此字串作為引數來呼叫此方法。
輸出顯示在控制檯上。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
mySQL
Javascript
PHP