"""This program prints the number of permutations of a given input. The number of permutation of a given input of length n is n! The algorithm is as follows 1. If the input length is less than or equal to 1, just return 2. For each element in the input, until the end of input is reached 3. Get the sub elements in the input except the current element that's being processed 4. Recursively traverse the sub elements 5. Append the recursive sublements to the current element 6. Return the list. """ def permutate(seq):#check the length of the input. If its less than or equal to 1, return the input as 1! is 1 if len(seq) <= 1: return [seq] else: #Create a temporary list to hold the values temp = [] #for each element in the given input, traverse until end of the the string for k in range(len(seq)): #get the subset of all the elements except the element
#that's being processed #string slicing works this way #get the elements until the current element +
#elements after the current element part = seq[:k] + seq[k+1:] #recursively traverse for the subset of elements for m in permutate(part): #append recursive element to the current element temp.append(seq[k] + m) #return the final output after all the possible recursions are complete return temp #Main Program #Prompt the user to enter input. Save it in user_input variable user_input = input("Enter the string of characters or numbers for permutations: ") #Call the permutate function and store the output into a list permutations = permutate(user_input) #traverse the list and print the permutations for perm in permutations: print(perm)
Monday, August 15, 2016
String Permutations in Python
Subscribe to:
Posts (Atom)