เมื่อจำเป็นต้องพิมพ์การเรียงสับเปลี่ยนทั้งหมดของสตริงในลำดับพจนานุกรมโดยใช้การเรียกซ้ำ จะมีการกำหนดวิธีการที่ใช้การวนซ้ำ 'for' เพื่อวนซ้ำลำดับขององค์ประกอบ และใช้วิธี 'เข้าร่วม' เพื่อรวมองค์ประกอบ
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
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' ที่ช่วยในการค้นหาลำดับขององค์ประกอบ lexicographic
-
เมธอด 'next_in_permutation' ช่วยกำหนดการเปลี่ยนลำดับถัดไปในสตริง
-
ผู้ใช้ป้อนสตริงและแสดงบนคอนโซล
-
วิธีการนี้ถูกเรียกโดยการส่งผ่านสตริงนี้เป็นพารามิเตอร์
-
เอาต์พุตจะแสดงบนคอนโซล