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

โปรแกรม Python หาการจัดเรียง (Permutation) ของสตริงด้วย itertools


แสดงการจัดเรียงทั้งหมดของสตริงที่กำหนดโดยใช้ itertools.permutations

ตัวอย่าง

Input: 'XYZ'
Output: XYZ XZY YXZ YZX ZXY ZYX

อัลกอริทึม

  1. รับสตริง
  2. เรียก permutations(str)
  3. พิมพ์ทุก permutation

โค้ดตัวอย่าง

from itertools import permutations

def allPermutations(str1):
    per = permutations(str1)
    print("Permutation Of this String:")
    for i in list(per):
        print(''.join(i))

if __name__ == "__main__":
    str1 = input("Enter the string: ")
    allPermutations(str1)

ผลลัพธ์

Enter the string: abc
Permutation Of this String:
abc
acb
bac
bca
cab
cba