Contoh program : Program Python untuk Menghitung semua Permutasi String

0
(0)

Contoh 1: Menggunakan rekursi

def get_permutation(string, i=0):

    if i == len(string):   	 
        print("".join(string))

    for j in range(i, len(string)):

        words = [c for c in string]
   
        # swap
        words[i], words[j] = words[j], words[i]
   	 
        get_permutation(words, i + 1)

print(get_permutation('yup'))

Keluaran

yup
ypu
uyp
upy
puy
pyu
None

Contoh 2: Menggunakan itertools

from itertools import permutations

words = [''.join(p) for p in permutations('prog')]

print(words)

Keluaran

Hello python

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.