Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเรียงสับเปลี่ยนของสตริงที่กำหนดโดยใช้ฟังก์ชัน inbuilt ใน Python


ในบทช่วยสอนนี้ เราจะค้นหาการเปลี่ยนแปลงของสตริงโดยใช้ฟังก์ชัน inbuilt ของ Python เรียกว่า การเรียงสับเปลี่ยน . วิธีการ การเรียงสับเปลี่ยน มีอยู่ใน itertools โมดูล

ขั้นตอนในการหาการเรียงสับเปลี่ยนของสตริง

  • นำเข้า itertools โมดูล
  • เริ่มต้นสตริง
  • ใช้ itertools.permutations วิธีการหาการเรียงสับเปลี่ยนของสตริง
  • ในขั้นตอนที่สาม เมธอดจะคืนค่าอ็อบเจ็กต์และแปลงเป็นรายการ
    • รายการมีการเรียงสับเปลี่ยนของสตริงเป็นทูเพิล

ตัวอย่าง

มาดูโปรแกรมกันครับ

## importing the module
import itertools
## initializing a string
string = "XYZ"
## itertools.permutations method
permutaion_list = list(itertools.permutations(string))
## printing the obj in list
print("-----------Permutations Of String In Tuples----------------")
print(permutaion_list)
## converting the tuples to string using 'join' method
print("-------------Permutations In String Format-----------------")
for tup in permutaion_list:
   print("".join(tup))

ผลลัพธ์

หากคุณเรียกใช้โปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังต่อไปนี้

-----------Permutations Of String In Tuples----------------
[('X', 'Y', 'Z'), ('X', 'Z', 'Y'), ('Y', 'X', 'Z'), ('Y', 'Z', 'X'), ('Z', 'X', 'Y'), ('Z', 'Y', 'X')]
-------------Permutations In String Format-----------------
XYZ
XZY
YXZ
YZX
ZXY
ZYX

หากคุณมีข้อสงสัยเกี่ยวกับโปรแกรม โปรดระบุในส่วนความคิดเห็น