Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Tạo tất cả hoán vị có thể của từ trong câu

Khi cần tạo tất cả hoán vị của từ trong câu, định nghĩa hàm lặp qua chuỗi và hiển thị theo điều kiện.

Ví dụ

from itertools import permutations

def calculate_permutations(my_string):
    my_list = list(my_string.split())
    permutes = permutations(my_list)
    for i in permutes:
        permute_list = list(i)
        for j in permute_list:
            print(j)
        print()

my_string = "hi there"
print("The string is:")
print(my_string)
print("All possible permutation are:")
calculate_permutations(my_string)

Đầu ra

The string is: hi there
All possible permutation are:
hi
there

there
hi

Giải thích

  • Nhập itertools.permutations.
  • Hàm calculate_permutations tách chuỗi thành từ, sinh hoán vị, in từng hoán vị.
  • Định nghĩa chuỗi, gọi hàm.